/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

// ===== TWEAKABLE DEFAULTS =====
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 85,
  "bgHue": 220,
  "showCursor": true,
  "showTicker": true,
  "headlineVariant": "through",
  "ctaLabel": "Join the waitlist",
  "waitlistCount": 0,
  "showGrid": false
}/*EDITMODE-END*/;

// ===== ROOT =====
function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [liveCount, setLiveCount] = useState(t.waitlistCount);

  // Fetch real count from Supabase on load
  useEffect(() => {
    fetch('/api/count')
      .then((r) => r.json())
      .then((d) => { if (d.count !== undefined) setLiveCount(d.count); })
      .catch(() => {}); // silently fall back to default
  }, []);

  // Apply CSS vars globally
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty('--accent-hue', t.accentHue);
    root.style.setProperty('--bg-hue', t.bgHue);
  }, [t.accentHue, t.bgHue]);

  return (
    <>
      <TopNav count={liveCount} showTicker={t.showTicker} />
      <Hero headlineVariant={t.headlineVariant} ctaLabel={t.ctaLabel} count={liveCount} showCursor={t.showCursor} />
      <Positioning />
      <ForWhom />
      <HowItWorks />
      <WaitlistForm ctaLabel={t.ctaLabel} count={liveCount} setLiveCount={setLiveCount} />
      <Footer />
      {t.showGrid && <GridOverlay />}
      <TweaksUI t={t} setTweak={setTweak} />
    </>
  );
}

// ===== TOP NAV =====
function TopNav({ count, showTicker }) {
  return (
    <header className="nav">
      <div className="nav-inner">
        <a href="#top" className="nav-mark" aria-label="LIV">
          <LivWordmark small />
        </a>
        {showTicker && count > 0 && (
          <div className="nav-ticker" aria-live="polite">
            <span className="dot" />
            <span className="mono">{count.toLocaleString()} on the waitlist</span>
          </div>
        )}
        <a href="#waitlist" className="nav-cta">
          Join
          <span className="arrow">→</span>
        </a>
      </div>
      <div className="rule rule--full" />
    </header>
  );
}

// ===== HERO =====
function Hero({ headlineVariant, ctaLabel, count, showCursor }) {
  const [typed, setTyped] = useState('');
  const phrases = [
    'open my game launcher',
    'summarize this lecture',
    'fix my notes for tomorrow',
    'queue up the next match',
    'explain this proof step by step',
    'listen to my lecture and take notes',
    'what did I learn about calculus last week?',
  ];
  const [phraseIdx, setPhraseIdx] = useState(0);
  const [deleting, setDeleting] = useState(false);

  useEffect(() => {
    const target = phrases[phraseIdx];
    const speed = deleting ? 30 : 55;
    const timer = setTimeout(() => {
      if (!deleting) {
        if (typed.length < target.length) setTyped(target.slice(0, typed.length + 1));
        else setTimeout(() => setDeleting(true), 1800);
      } else {
        if (typed.length > 0) setTyped(target.slice(0, typed.length - 1));
        else {
          setDeleting(false);
          setPhraseIdx((phraseIdx + 1) % phrases.length);
        }
      }
    }, speed);
    return () => clearTimeout(timer);
  }, [typed, deleting, phraseIdx]);

  return (
    <section id="top" className="hero">
      <div className="hero-meta">
        <span className="mono muted">LIV / 2026 · WINDOWS</span>
        <span className="mono muted">PRIVATE BETA — OPENING SOON</span>
      </div>

      <h1 className={`headline headline--${headlineVariant}`}>
        <span className="headline-line">
          <span className="word">An AI</span>{' '}
          <span className="word">that works</span>
        </span>
        <span className="headline-line headline-line--strike">
          <span className="word">with your</span>{' '}
          <span className="word word--accent">computer</span>
          <span className="strike" aria-hidden="true" />
        </span>
        <span className="headline-line">
          <span className="word muted">— not just inside a chat.</span>
        </span>
      </h1>

      <div className="hero-prompt">
        <div className="prompt-rule" />
        <div className="prompt-body">
          <span className="mono muted">you</span>
          <span className="prompt-text">
            Hey LIV, {typed}
            {showCursor && <span className="caret">▍</span>}
          </span>
        </div>
      </div>

      <div className="hero-cta">
        <a href="#waitlist" className="btn btn--primary">
          <span>{ctaLabel}</span>
          <span className="btn-arrow">→</span>
        </a>
        <span className="mono muted cta-side">
          {count > 0 ? `${count.toLocaleString()} already in · ` : ''}no spam, one email at launch · Windows · Mac coming later
        </span>
      </div>
    </section>
  );
}

// ===== POSITIONING =====
function Positioning() {
  return (
    <section className="positioning">
      <div className="rule rule--full" />
      <div className="positioning-inner">
        <span className="mono muted col-label">[ 01 / POSITIONING ]</span>
        <p className="big-quote">
          More than a chatbot.<br />
          <span className="muted">LIV actually helps you</span> get things done.
        </p>
      </div>
      <div className="rule rule--full" />
    </section>
  );
}

// ===== FOR WHOM =====
function ForWhom() {
  return (
    <section className="for-whom">
      <div className="fw-header">
        <span className="mono muted col-label">[ 02 / BUILT FOR ]</span>
        <h2 className="section-title">Built for people who actually use their PC.</h2>
      </div>

      <div className="fw-grid">
        <PersonaCard
          tag="01"
          title="Gamers"
          pitch="Launch your setup, stay focused, let LIV handle the small stuff while you play."
          groups={[
            {
              heading: 'Focused play',
              lines: [
                'One command to open your stack',
                'Stop app-switching mid-match',
                'Small tasks, handled in the background',
              ],
            },
            {
              heading: 'Smarter performance, zero hassle',
              lines: [
                'Prepares your system for peak performance',
                'Less manual tweaking of settings',
                'Keeps things running smoothly in the background',
              ],
            },
          ]}
          visual={<GamerVisual />}
        />
        <PersonaCard
          tag="02"
          title="Students"
          pitch="A built-in tutor that walks you through math and science — right where you study."
          groups={[
            {
              heading: 'Learn step by step',
              lines: [
                'Step-by-step problem solving',
                'Works across your notes and apps',
                'Explains the why, not just the what',
              ],
            },
            {
              heading: 'Built around how you actually study',
              lines: [
                'Guides consistent, realistic study routines',
                'Works with your notes and textbooks',
                'Adapts to what you\u2019re learning over time',
              ],
            },
            {
              heading: 'Notes from every lecture & meeting',
              lines: [
                'Listens live and captures every point',
                'Turns talks into comprehensive, structured notes',
                'Summaries, key terms, and action items, sorted',
              ],
            },
            {
              heading: 'A second brain, powered by AI',
              lines: [
                'Your notes link themselves into a living map',
                'Ask anything across what you\u2019ve learned',
                'Ideas connect automatically as you add more',
              ],
            },
          ]}
          visual={<StudentVisual />}
        />
      </div>

      <p className="power-line">
        <span className="mono muted pl-tag">[ · ]</span>
        <span>
          LIV adapts to your system, your study, and your workflow
          <span className="muted"> &mdash; so it becomes more useful every day.</span>
        </span>
      </p>
    </section>
  );
}

function PersonaCard({ tag, title, pitch, groups, visual }) {
  return (
    <article className="persona">
      <div className="persona-visual">{visual}</div>
      <div className="persona-body">
        <div className="persona-head">
          <span className="mono muted">{tag}</span>
          <h3 className="persona-title">{title}</h3>
        </div>
        <p className="persona-pitch">{pitch}</p>
        {groups.map((g, gi) => (
          <div key={gi} className="persona-group">
            <h4 className="persona-group-title">{g.heading}</h4>
            <ul className="persona-list">
              {g.lines.map((l, i) => (
                <li key={i}>
                  <span className="mono muted li-num">0{i + 1}</span>
                  <span>{l}</span>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </article>
  );
}

function GamerVisual() {
  return (
    <div className="viz viz--gamer">
      <div className="viz-strike" />
      <div className="viz-label mono">ACTIVE_SESSION.exe</div>
      <div className="viz-rows">
        {['DISCORD', 'STEAM', 'OBS', 'SPOTIFY'].map((a, i) => (
          <div key={a} className="viz-row" style={{ animationDelay: `${i * 0.15}s` }}>
            <span className="viz-dot" />
            <span className="mono">{a}</span>
            <span className="mono muted viz-status">launched · {80 + i * 4}ms</span>
          </div>
        ))}
      </div>
      <div className="viz-footer mono muted">└ LIV / 4 apps ready</div>
    </div>
  );
}

function StudentVisual() {
  const [phase, setPhase] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setPhase((p) => (p + 1) % 3), 4200);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="viz viz--student">
      <div className="viz-strike" />
      <div className="viz-tabs mono">
        {['TUTOR', 'LECTURE', 'BRAIN'].map((t, i) => (
          <span key={t} className={`viz-tab ${phase === i ? 'viz-tab--on' : ''}`}>
            {t}
          </span>
        ))}
      </div>

      {phase === 0 && (
        <div className="viz-eq" key="tutor">
          <div className="eq-line">
            <span className="mono muted">Q.</span>
            <span>Solve for x: 3x² − 12 = 0</span>
          </div>
          <div className="eq-step">
            <span className="mono muted">1.</span>
            <span>Add 12 → <em>3x² = 12</em></span>
          </div>
          <div className="eq-step">
            <span className="mono muted">2.</span>
            <span>Divide by 3 → <em>x² = 4</em></span>
          </div>
          <div className="eq-step eq-step--active">
            <span className="mono muted">3.</span>
            <span>Take root → <em>x = ±2</em> <span className="caret">▍</span></span>
          </div>
          <div className="viz-footer mono muted">└ LIV / explained in 3 steps</div>
        </div>
      )}

      {phase === 1 && (
        <div className="viz-eq" key="lecture">
          <div className="eq-line">
            <span className="mono muted live">
              <span className="rec-dot" /> REC
            </span>
            <span>Lecture · Intro to Calculus · 42:18</span>
          </div>
          <div className="eq-step">
            <span className="mono muted">§1</span>
            <span>Limits &amp; continuity — working definition</span>
          </div>
          <div className="eq-step">
            <span className="mono muted">§2</span>
            <span>Derivative as rate of change</span>
          </div>
          <div className="eq-step eq-step--active">
            <span className="mono muted">§3</span>
            <span>Chain rule, worked example <span className="caret">▍</span></span>
          </div>
          <div className="viz-footer mono muted">└ LIV / notes auto-structured</div>
        </div>
      )}

      {phase === 2 && (
        <div className="viz-brain" key="brain">
          <svg className="brain-graph" viewBox="0 0 260 140" preserveAspectRatio="none" aria-hidden="true">
            <line x1="60" y1="40" x2="140" y2="70" />
            <line x1="140" y1="70" x2="220" y2="35" />
            <line x1="140" y1="70" x2="90" y2="115" />
            <line x1="140" y1="70" x2="200" y2="110" />
            <line x1="60" y1="40" x2="90" y2="115" />
            <circle cx="60" cy="40" r="4" />
            <circle cx="140" cy="70" r="6" className="brain-node--active" />
            <circle cx="220" cy="35" r="4" />
            <circle cx="90" cy="115" r="4" />
            <circle cx="200" cy="110" r="4" />
          </svg>
          <div className="brain-tags">
            <span className="mono">#calculus</span>
            <span className="mono brain-tag--on">#chain-rule</span>
            <span className="mono">#derivatives</span>
            <span className="mono">#limits</span>
          </div>
          <div className="viz-footer mono muted">└ LIV / 142 notes · 1,284 links</div>
        </div>
      )}
    </div>
  );
}

// ===== HOW IT WORKS =====
function HowItWorks() {
  const items = [
    {
      n: '01',
      t: 'Watches how you work',
      d: 'LIV sits alongside your apps and learns the shape of your setup.',
    },
    {
      n: '02',
      t: 'Acts on your computer',
      d: 'Not just answers. LIV can actually do things — click, type, open, arrange.',
    },
    {
      n: '03',
      t: 'Gets sharper over time',
      d: 'The more you use it, the more it feels like it was built for you.',
    },
  ];
  return (
    <section className="how">
      <div className="rule rule--full" />
      <div className="how-header">
        <span className="mono muted col-label">[ 03 / HOW IT WORKS ]</span>
        <h2 className="section-title">A natural extension<br/>of your system.</h2>
      </div>
      <div className="how-grid">
        {items.map((it) => (
          <div key={it.n} className="how-item">
            <div className="how-num mono">{it.n}</div>
            <div className="how-rule" />
            <h3 className="how-title">{it.t}</h3>
            <p className="how-desc">{it.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

// ===== WAITLIST FORM =====
function WaitlistForm({ ctaLabel, count, setLiveCount }) {
  const [email, setEmail] = useState('');
  const [use, setUse] = useState('gamer');
  const [state, setState] = useState('idle'); // idle | loading | success | error
  const [error, setError] = useState('');
  const [position, setPosition] = useState(null);

  const submit = async (e) => {
    e.preventDefault();
    if (state === 'loading' || state === 'success') return;
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) {
      setError("That email doesn't look right.");
      setState('error');
      return;
    }
    setError('');
    setState('loading');

    try {
      const res = await fetch('/api/join', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), use_case: use }),
      });
      if (res.ok) {
        const data = await res.json();
        setState('success');
        setPosition(data.position || count + 1);
        setLiveCount((c) => c + 1);
      } else {
        setError('Something went wrong. Try again.');
        setState('error');
      }
    } catch {
      setError('Something went wrong. Try again.');
      setState('error');
    }
  };

  return (
    <section id="waitlist" className="waitlist">
      <div className="rule rule--full" />
      <div className="waitlist-inner">
        <div className="waitlist-left">
          <span className="mono muted col-label">[ 04 / ACCESS ]</span>
          <h2 className="section-title">
            Get in early.<br />
            <span className="muted">Shape what LIV becomes.</span>
          </h2>
          <ul className="waitlist-list">
            <li><span className="mono muted">·</span> First access to the private beta</li>
            <li><span className="mono muted">·</span> Direct line to the team</li>
            <li><span className="mono muted">·</span> Pricing locked at early-supporter rates</li>
            <li><span className="mono muted">·</span> Windows — Mac coming later</li>
          </ul>
        </div>

        <div className="waitlist-right">
          {state !== 'success' ? (
            <form className="form" onSubmit={submit} noValidate>
              <label className="field">
                <span className="field-label mono muted">EMAIL</span>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => { setEmail(e.target.value); if (state === 'error') setState('idle'); }}
                  placeholder="you@domain.com"
                  className={`field-input ${state === 'error' ? 'field-input--error' : ''}`}
                  autoComplete="email"
                />
              </label>

              <fieldset className="field field--group">
                <span className="field-label mono muted">I&apos;M MOSTLY A…</span>
                <div className="radio-row">
                  {[
                    { v: 'gamer', l: 'Gamer' },
                    { v: 'student', l: 'Student' },
                    { v: 'both', l: 'Both' },
                    { v: 'curious', l: 'Just curious' },
                  ].map((o) => (
                    <label key={o.v} className={`radio ${use === o.v ? 'radio--on' : ''}`}>
                      <input
                        type="radio"
                        name="use"
                        value={o.v}
                        checked={use === o.v}
                        onChange={() => setUse(o.v)}
                      />
                      <span>{o.l}</span>
                    </label>
                  ))}
                </div>
              </fieldset>

              {state === 'error' && (
                <div className="form-error mono">! {error}</div>
              )}

              <button
                type="submit"
                className={`btn btn--primary btn--full ${state === 'loading' ? 'btn--loading' : ''}`}
                disabled={state === 'loading'}
              >
                <span>{state === 'loading' ? 'Adding you…' : ctaLabel}</span>
                <span className="btn-arrow">{state === 'loading' ? '' : '→'}</span>
              </button>

              <p className="form-fine mono muted">
                No spam. One email when LIV opens up. Unsubscribe with a click.
              </p>
            </form>
          ) : (
            <SuccessCard position={position} email={email} />
          )}
        </div>
      </div>
      <div className="rule rule--full" />
    </section>
  );
}

function SuccessCard({ position, email }) {
  const [copied, setCopied] = useState(false);
  const shareText = "Just joined the waitlist for LIV — an AI that actually controls your PC. https://getliv.org";

  const copyShareText = () => {
    navigator.clipboard?.writeText(shareText);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="success">
      <div className="success-head">
        <span className="mono muted">[ CONFIRMED ]</span>
        <div className="success-check">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M4 12l5 5L20 6" strokeLinecap="square" />
          </svg>
        </div>
      </div>
      <h3 className="success-title">You&apos;re on the list.</h3>
      <div className="success-strike" />
      <div className="success-stats">
        <div className="success-stat">
          <span className="mono muted">POSITION</span>
          <span className="success-num">#{position?.toLocaleString()}</span>
        </div>
        <div className="success-stat">
          <span className="mono muted">EMAIL</span>
          <span className="success-email">{email}</span>
        </div>
      </div>
      <p className="success-note">
        We&apos;ll send a single email when your seat opens. Want to move up? Share LIV with a friend who&apos;d get it.
      </p>
      <div className="success-share">
        <button className="share-btn" onClick={copyShareText}>
          <span className="mono">{copied ? 'COPIED ✓' : 'COPY SHARE TEXT'}</span>
          <span>↗</span>
        </button>
        <a
          className="share-btn"
          href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}`}
          target="_blank"
          rel="noopener noreferrer"
        >
          <span className="mono">SHARE ON X</span>
          <span>↗</span>
        </a>
      </div>
    </div>
  );
}

// ===== FOOTER =====
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-mark">
          <LivWordmark small />
          <span className="mono muted">© 2026 MatK</span>
        </div>
        <div className="footer-links mono">
          <a href="#">Privacy</a>
          <a href="#">Terms</a>
          <a href="mailto:hello@getliv.org">Contact</a>
        </div>
      </div>
    </footer>
  );
}

// ===== LIV WORDMARK =====
function LivWordmark({ small }) {
  return (
    <span className={`liv-mark ${small ? 'liv-mark--sm' : ''}`}>
      <span className="liv-mark-text">LIV</span>
      <span className="liv-mark-line" />
    </span>
  );
}

// ===== GRID OVERLAY (dev) =====
function GridOverlay() {
  return (
    <div className="grid-overlay" aria-hidden="true">
      {Array.from({ length: 12 }).map((_, i) => <div key={i} className="grid-col" />)}
    </div>
  );
}

// ===== TWEAKS UI =====
function TweaksUI({ t, setTweak }) {
  const { TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakSelect, TweakText, TweakNumber, TweakRadio } = window;
  if (!TweaksPanel) return null;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Color">
        <TweakSlider label="Accent hue" value={t.accentHue} min={0} max={360} step={1}
                     onChange={(v) => setTweak('accentHue', v)} />
        <TweakSlider label="Background hue" value={t.bgHue} min={180} max={260} step={1}
                     onChange={(v) => setTweak('bgHue', v)} />
      </TweakSection>
      <TweakSection label="Hero">
        <TweakRadio label="Headline" value={t.headlineVariant}
                    options={[
                      { value: 'through', label: 'Strike' },
                      { value: 'stacked', label: 'Plain' },
                      { value: 'tight', label: 'Tight' },
                    ]}
                    onChange={(v) => setTweak('headlineVariant', v)} />
        <TweakToggle label="Typing cursor" value={t.showCursor}
                     onChange={(v) => setTweak('showCursor', v)} />
        <TweakText label="CTA label" value={t.ctaLabel}
                   onChange={(v) => setTweak('ctaLabel', v)} />
      </TweakSection>
      <TweakSection label="Social proof">
        <TweakToggle label="Nav ticker" value={t.showTicker}
                     onChange={(v) => setTweak('showTicker', v)} />
        <TweakNumber label="Waitlist count" value={t.waitlistCount} min={0} max={999999} step={1}
                     onChange={(v) => setTweak('waitlistCount', v)} />
      </TweakSection>
      <TweakSection label="Dev">
        <TweakToggle label="12-col grid" value={t.showGrid}
                     onChange={(v) => setTweak('showGrid', v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// expose in case not already
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
