/* global React, ScreenPuzzle, ScreenWelcome, ScreenChooseApp, ScreenUnlock, InteractiveBoard, AppIcon, PieceImage, Chessboard, FORK_POSITION */

const { useState: useStateA, useEffect: useEffectA } = React;

const HERO_SCREENS = ['puzzle', 'welcome', 'unlock'];
const HERO_LABEL   = { puzzle: 'Puzzle gate', welcome: 'Welcome', unlock: 'Unlocked' };

function HeroPhone() {
  const [idx, setIdx] = useStateA(0);

  useEffectA(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % HERO_SCREENS.length), 4200);
    return () => clearInterval(t);
  }, []);

  const screen = HERO_SCREENS[idx];

  return (
    <div className="lp-hero-device" data-screen-label="hero-phone">
      {/* floaters */}
      <div className="lp-floater" style={{ top: 60, left: -10, ['--rot']: '-12deg', animationDelay: '0s' }}>
        <FloatPiece kind="N" size={62} />
      </div>
      <div className="lp-floater" style={{ top: 380, right: 0, ['--rot']: '14deg', animationDelay: '-2s' }}>
        <FloatPiece kind="Q" size={56} />
      </div>
      <div className="lp-floater" style={{ bottom: 80, left: 30, ['--rot']: '8deg', animationDelay: '-4s' }}>
        <FloatPiece kind="P" size={48} />
      </div>

      <div className="lp-device-stage">
        <div style={{
          width: 402, height: 874, borderRadius: 48,
          overflow: 'hidden', position: 'relative', background: '#0a1030',
          boxShadow: '0 60px 120px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.06), 0 0 0 12px #1a1a22',
        }}>
          <div style={{
            position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
            width: 126, height: 37, borderRadius: 24, background: '#000', zIndex: 50,
          }} />
          <div key={screen} style={{
            position: 'absolute', inset: 0,
          }}>
            {screen === 'puzzle'  && <ScreenPuzzle />}
            {screen === 'welcome' && <ScreenWelcome />}
            {screen === 'unlock'  && <ScreenUnlock />}
          </div>
        </div>
      </div>

      {/* tiny screen-pager dots under the phone */}
      <div style={{
        position: 'absolute', bottom: -8, left: 0, right: 0,
        display: 'flex', justifyContent: 'center', gap: 8, zIndex: 5,
      }}>
        {HERO_SCREENS.map((_, i) => (
          <div key={i} style={{
            width: i === idx ? 24 : 6, height: 6, borderRadius: 4,
            background: i === idx ? '#4a73ff' : 'rgba(255,255,255,0.15)',
            transition: 'all 0.3s',
          }} />
        ))}
      </div>
    </div>
  );
}

function FloatPiece({ kind = 'P', size = 64 }) {
  return (
    <div style={{
      width: size + 20, height: size + 20, borderRadius: 16,
      background: 'linear-gradient(135deg, rgba(40,86,255,0.18), rgba(40,86,255,0.04))',
      border: '1px solid rgba(255,255,255,0.1)',
      backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <PieceImage kind={kind} size={size} />
    </div>
  );
}

// =====================================================================
// SECTIONS
// =====================================================================
function HowItWorks() {
  return (
    <section className="lp-section" id="how">
      <div className="lp-section-eyebrow">How it works</div>
      <h2>One quick tactic. Then you scroll.</h2>
      <p className="lp-section-lede">
        Three steps. No nags, no shame, no hidden mode where the app pretends you didn’t open it.
      </p>

      <div className="lp-steps">
        <Step
          num="01"
          title="Pick an app to gate"
          body="Instagram or TikTok. Start with one. Add more when you’re ready."
          art={<StepArtApps />}
        />
        <Step
          num="02"
          title="Solve a quick tactic"
          body="A short puzzle at your level appears the moment you open the app. Find the best move."
          art={<StepArtBoard />}
        />
        <Step
          num="03"
          title="Earn your scroll"
          body="+5 minutes for a clean solve. Want more? The next puzzle is harder — and worth more."
          art={<StepArtLadder />}
        />
      </div>
    </section>
  );
}

function Step({ num, title, body, art }) {
  return (
    <div className="lp-step">
      <div className="lp-step-art">{art}</div>
      <div className="lp-step-num">STEP {num}</div>
      <h3>{title}</h3>
      <p>{body}</p>
    </div>
  );
}

function StepArtApps() {
  return (
    <div style={{ display: 'flex', gap: 14, justifyContent: 'center', alignItems: 'center' }}>
      <AppIcon kind="ig" size={58} />
      <AppIcon kind="tt" size={58} />
    </div>
  );
}
function StepArtBoard() {
  return (
    <div style={{
      transform: 'rotate(-3deg)',
      filter: 'drop-shadow(0 16px 32px rgba(40,86,255,0.4))',
    }}>
      <Chessboard
        position={FORK_POSITION}
        size={120}
        showCoords={false}
        highlightFrom="e5"
        highlightTo="f7"
      />
    </div>
  );
}
function StepArtLadder() {
  const bars = [
    { h: 26, label: '+5' },
    { h: 46, label: '+5' },
    { h: 74, label: '+7' },
  ];
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 90 }}>
      {bars.map((b, i) => (
        <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div className="sg-mono" style={{ fontSize: 11, fontWeight: 700, color: '#4a73ff' }}>{b.label}</div>
          <div style={{
            width: 22, height: b.h, borderRadius: 5,
            background: i === 2
              ? 'linear-gradient(180deg, #4a73ff, #2856ff)'
              : 'linear-gradient(180deg, rgba(40,86,255,0.55), rgba(40,86,255,0.25))',
            border: '1px solid rgba(255,255,255,0.1)',
          }} />
        </div>
      ))}
    </div>
  );
}

function DemoSection() {
  return (
    <section className="lp-section" id="demo">
      <div className="lp-demo">
        <div className="lp-demo-board">
          <InteractiveBoard size={420} />
        </div>
        <div className="lp-demo-side">
          <div className="lp-section-eyebrow">Try it now</div>
          <h2>This is what your phone hands you instead.</h2>
          <p style={{ fontSize: 16.5, color: 'var(--sg-text-mid)', lineHeight: 1.55, margin: 0 }}>
            White to move. Your knight is sitting on e5. There’s a square that wins material on the spot.
            Find it, and you’d earn five minutes in the real app.
          </p>
          <ul style={{
            listStyle: 'none', padding: 0, margin: '28px 0 0',
            display: 'flex', flexDirection: 'column', gap: 14, fontSize: 15, color: 'var(--sg-text-mid)',
          }}>
            <li style={{ display: 'flex', gap: 12 }}>
              <Check /> Puzzles scale to your rating — no mate-in-one if you’re strong.
            </li>
            <li style={{ display: 'flex', gap: 12 }}>
              <Check /> Hints exist, but they cost you reward time.
            </li>
            <li style={{ display: 'flex', gap: 12 }}>
              <Check /> Solving more makes the next puzzle harder — and worth more.
            </li>
          </ul>
        </div>
      </div>
    </section>
  );
}

function Check() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" style={{ flexShrink: 0, marginTop: 1 }}>
      <circle cx="10" cy="10" r="9" fill="rgba(40,86,255,0.15)" stroke="rgba(40,86,255,0.5)" strokeWidth="1"/>
      <path d="M6 10l3 3 5-6" fill="none" stroke="#4a73ff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function BlocksSection() {
  const apps = [
    { kind: 'ig', name: 'Instagram' },
    { kind: 'tt', name: 'TikTok' },
  ];
  return (
    <section className="lp-section" id="apps">
      <div className="lp-section-eyebrow">What it gates</div>
      <h2>Two apps to start. More on the way.</h2>
      <div className="lp-blocks" style={{ gridTemplateColumns: 'repeat(3, 1fr)', maxWidth: 720 }}>
        {apps.map(a => (
          <div key={a.kind} className="lp-block">
            <AppIcon kind={a.kind} size={72} />
            <span style={{ fontSize: 14, marginTop: 4 }}>{a.name}</span>
          </div>
        ))}
        <div className="lp-block coming">
          More<br/>soon
        </div>
      </div>
    </section>
  );
}

function FAQ() {
  const items = [
    {
      q: 'I’m bad at chess. Does this just lock me out forever?',
      a: 'No. The first thing you do is pick your level. If you’re new, the puzzles are very gentle — think "the queen takes the free piece." The point is to make you pause and think, not to humiliate you.',
    },
    {
      q: 'What if I genuinely need to open Instagram right now?',
      a: 'Tap "Give up." You’ll get a one-time short pass, but no scroll reward. Most people find they didn’t actually need the app that badly. The rest get to skip the puzzle when it matters.',
    },
    {
      q: 'How is this different from a normal app blocker?',
      a: 'App blockers say no. Scroll Gambit says "earn it." That tiny shift — from punishment to a small game — is the whole point. You feel like you won something instead of feeling lectured.',
    },
    {
      q: 'Will I actually get better at chess?',
      a: 'Probably, yeah. You’ll see hundreds of tactical patterns. We track your rating gently in the background so puzzles stay challenging without becoming impossible.',
    },
    {
      q: 'Can I be in early access?',
      a: 'Drop your email at the top. iOS beta starts soon.',
    },
  ];
  const [open, setOpen] = useStateA(0);
  return (
    <section className="lp-section" id="faq">
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <div className="lp-section-eyebrow">Questions</div>
        <h2 style={{ margin: '0 auto' }}>Reasonable concerns,<br/>answered.</h2>
      </div>
      <div className="lp-faq">
        {items.map((it, i) => (
          <div key={i} className={`lp-faq-item${open === i ? ' open' : ''}`}>
            <div className="lp-faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
              {it.q}
            </div>
            <p className="lp-faq-a">{it.a}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function SignupForm({ size = 'normal' }) {
  const [email, setEmail] = useStateA('');
  const [sent, setSent] = useStateA(false);
  const [sending, setSending] = useStateA(false);
  const [error, setError] = useStateA(null);

  async function submit(e) {
    e.preventDefault();
    if (!email || !email.includes('@') || sending) return;
    setSending(true);
    setError(null);
    try {
      const base = (typeof window !== 'undefined' && window.__API_BASE) || '';
      const r = await fetch(`${base}/api/waitlist`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, source: 'landing' }),
      });
      const body = await r.json().catch(() => ({}));
      if (!r.ok || !body.ok) {
        if (body.error === 'invalid_email') {
          setError('That email doesn’t look right.');
        } else if (body.error === 'rate_limited') {
          setError('Too many tries. Wait a minute and retry.');
        } else {
          setError('Something went wrong. Try again?');
        }
        return;
      }
      setSent(true);
      setEmail('');
    } catch {
      setError('Couldn’t reach the server. Try again?');
    } finally {
      setSending(false);
    }
  }

  if (sent) {
    return (
      <div className="lp-form" style={{ background: 'rgba(40,86,255,0.12)', borderColor: 'rgba(40,86,255,0.4)' }}>
        <div style={{ flex: 1, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <svg width="22" height="22" viewBox="0 0 22 22">
            <circle cx="11" cy="11" r="10" fill="#4a73ff"/>
            <path d="M6 11l3 3 6-7" stroke="#fff" strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span style={{ fontWeight: 600 }}>You’re on the list. We’ll be in touch.</span>
        </div>
      </div>
    );
  }

  return (
    <div>
      <form className="lp-form" onSubmit={submit}>
        <input
          type="email"
          placeholder="you@example.com"
          value={email}
          onChange={e => setEmail(e.target.value)}
          disabled={sending}
        />
        <button type="submit" disabled={sending} style={sending ? { opacity: 0.7, cursor: 'wait' } : null}>
          {sending ? 'Joining…' : 'Join the waitlist'}
          {!sending && (
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M5 3l4 4-4 4" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          )}
        </button>
      </form>
      {error && (
        <div style={{ marginTop: 8, fontSize: 13.5, color: '#ffb1b1' }}>{error}</div>
      )}
    </div>
  );
}

function Hero() {
  return (
    <section className="lp-hero" id="signup">
      <div>
        <div className="lp-hero-eyebrow">
          <div className="lp-hero-eyebrow-dot" />
          iOS beta — invites going out weekly
        </div>
        <h1>
          <span className="ink">Solve a chess<br/>puzzle before</span><br/>
          <span className="blue">you scroll.</span>
        </h1>
        <p className="lp-hero-sub">
          Scroll Gambit puts a quick tactic between you and Instagram. Crack it,
          earn five minutes. Skip it, miss the scroll. No nagging, no shame —
          just a small, clever obstacle.
        </p>
        <SignupForm />
        <div className="lp-hero-meta">
          <div className="lp-avatar-stack">
            <div /><div /><div /><div /><div />
          </div>
          <span><strong style={{ color: '#fff', fontWeight: 600 }}>2,847</strong> on the waitlist</span>
        </div>
      </div>
      <HeroPhone />
    </section>
  );
}

function CTAStrip() {
  return (
    <section className="lp-section" id="signup-bottom">
      <div className="lp-cta">
        <h2>Solve. Scroll. Repeat.</h2>
        <p>The whole product is one screen. Get the email when it ships.</p>
        <SignupForm />
      </div>
    </section>
  );
}

function Nav() {
  return (
    <nav className="lp-nav">
      <a href="#" className="lp-brand">
        <img src={(typeof window !== 'undefined' && window.__resources && window.__resources.logoImg) || "assets/logo.png"} alt="" />
        Scroll Gambit
      </a>
      <div className="lp-nav-links">
        <a href="#how">How it works</a>
        <a href="#demo">Try it</a>
        <a href="#faq">FAQ</a>
        <a href="#signup">Sign up</a>
      </div>
    </nav>
  );
}

function Footer() {
  return (
    <footer className="lp-footer">
      <div>© 2026 Scroll Gambit. Earn your scroll.</div>
      <div className="lp-footer-links">
        <a href="#">Privacy</a>
        <a href="#">Terms</a>
        <a href="#">hello@scrollgambit.app</a>
      </div>
    </footer>
  );
}

function Landing() {
  return (
    <div className="lp-shell">
      <Nav />
      <Hero />
      <HowItWorks />
      <DemoSection />
      <BlocksSection />
      <FAQ />
      <CTAStrip />
      <Footer />
    </div>
  );
}

Object.assign(window, { Landing });
