// OBEY — landing page (desktop responsive) + waitlist capture

// === WAITLIST CONFIG ===
// Sign up free at https://formspree.io, create a form, paste the endpoint here
// (looks like https://formspree.io/f/xxxxxxxx). Any service that accepts
// JSON POST {email, source, ts} works (Buttondown, ConvertKit via API, a Cloudflare Worker, etc.).
const WAITLIST_ENDPOINT = 'https://formspree.io/f/meevbowy';

const { useState: useLandingState } = React;

function WaitlistForm({ compact = false }) {
  const [email, setEmail] = useLandingState('');
  const [state, setState] = useLandingState('idle'); // idle | submitting | success | error
  const [error, setError] = useLandingState(null);

  const submit = async (e) => {
    e.preventDefault();
    if (state === 'submitting') return;
    const trimmed = email.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
      setError("That doesn't look like an email.");
      setState('error');
      return;
    }
    setState('submitting');
    setError(null);

    if (!WAITLIST_ENDPOINT) {
      console.warn('[OBEY] WAITLIST_ENDPOINT is not set — set it in obey-landing.jsx before deploying.');
      // Dev fallback: pretend success so the UI flow is testable locally.
      setTimeout(() => setState('success'), 350);
      return;
    }

    try {
      const res = await fetch(WAITLIST_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          email: trimmed,
          source: 'obey-landing',
          ts: new Date().toISOString(),
        }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setState('success');
    } catch (err) {
      setError("Couldn't submit. Try again in a moment.");
      setState('error');
    }
  };

  if (state === 'success') {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: compact ? '14px 16px' : '18px 22px',
        border: '1px solid rgba(198,255,61,0.45)',
        background: 'rgba(198,255,61,0.06)',
        borderRadius: 14, maxWidth: 560,
      }}>
        <StatusDot color="var(--acid)" size={8} />
        <div>
          <div className="mono all-caps" style={{ fontSize: 11, letterSpacing: '0.22em', color: 'var(--acid)' }}>ON THE LIST</div>
          <div style={{ fontSize: 13, color: 'var(--mute)', marginTop: 4 }}>
            We'll write when Experiment 4127 opens. Don't expect a normal newsletter.
          </div>
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{ width: '100%', maxWidth: 560 }}>
      <div className="waitlist-row" style={{
        display: 'flex', gap: 0,
        border: '1px solid var(--line-2)', borderRadius: 14,
        background: 'rgba(245,241,232,0.03)',
        overflow: 'hidden',
      }}>
        <input
          type="email"
          value={email}
          onChange={(e) => { setEmail(e.target.value); if (state === 'error') { setState('idle'); setError(null); } }}
          placeholder="email@domain.com"
          autoComplete="email"
          required
          style={{
            flex: 1, minWidth: 0,
            background: 'transparent',
            border: 'none', outline: 'none',
            color: 'var(--paper)',
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            fontSize: 14,
            padding: '16px 18px',
          }}
        />
        <button type="submit" disabled={state === 'submitting'} style={{
          background: 'var(--acid)', color: 'var(--void)',
          border: 'none',
          padding: '0 24px',
          fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 13,
          letterSpacing: '0.22em',
          cursor: state === 'submitting' ? 'wait' : 'pointer',
          opacity: state === 'submitting' ? 0.7 : 1,
          whiteSpace: 'nowrap',
        }}>
          {state === 'submitting' ? 'JOINING…' : 'JOIN WAITLIST →'}
        </button>
      </div>
      {error && (
        <div className="mono" style={{ fontSize: 11, color: 'var(--danger)', marginTop: 10 }}>
          {error}
        </div>
      )}
      <div className="mono" style={{ fontSize: 11, color: 'var(--mute)', marginTop: 12 }}>
        FREE · NO ACCOUNT · COHORT 01 OPENS SOON
      </div>
      <div className="mono" style={{ fontSize: 10, color: 'var(--mute-2)', marginTop: 8, lineHeight: 1.5 }}>
        We email you once when Cohort 01 opens. Address stored at Formspree. No resale, unsubscribe anytime. <a href="/privacy.html" style={{ color: 'var(--mute)', textDecoration: 'underline', textDecorationColor: 'var(--line-2)', textUnderlineOffset: 3 }}>Privacy &amp; terms</a>.
      </div>
    </form>
  );
}

function LandingPage({ onEnter }) {
  return (
    <div style={{ width: '100%', minHeight: '100vh', background: '#0A0612', color: 'var(--paper)', overflow: 'hidden', position: 'relative' }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(80% 50% at 50% 0%, rgba(124,58,237,0.18) 0%, transparent 60%)',
        pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'repeating-linear-gradient(0deg, rgba(255,255,255,0.012) 0 1px, transparent 1px 3px)',
        pointerEvents: 'none',
      }} />

      <div className="obey-nav" style={{
        position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '28px 48px', borderBottom: '1px solid var(--line)',
      }}>
        <ObeyMark size={20} />
        <div className="obey-nav-links" style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
          <span className="mono all-caps" style={{ fontSize: 11, color: 'var(--mute)', cursor: 'pointer' }}>HOW IT WORKS</span>
          <span className="mono all-caps" style={{ fontSize: 11, color: 'var(--mute)', cursor: 'pointer' }}>RULES</span>
          <button onClick={onEnter} style={{
            background: 'transparent', color: 'var(--paper)',
            border: '1px solid var(--line-2)', borderRadius: 999,
            padding: '8px 16px',
            fontFamily: 'Inter', fontWeight: 600, fontSize: 11, letterSpacing: '0.2em',
            cursor: 'pointer',
          }}>TRY THE PREVIEW</button>
          <a href="#waitlist" style={{
            background: 'var(--paper)', color: 'var(--void)', border: 'none',
            borderRadius: 999, padding: '9px 18px',
            fontFamily: 'Inter', fontWeight: 700, fontSize: 11, letterSpacing: '0.2em',
            cursor: 'pointer', textDecoration: 'none',
          }}>JOIN WAITLIST</a>
        </div>
      </div>

      <div className="obey-hero" style={{ position: 'relative', padding: '70px 48px 80px', maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 28 }}>
          <StatusDot color="var(--signal)" />
          <span className="mono all-caps" style={{ fontSize: 11, color: 'var(--mute)' }}>EXPERIMENT 4127 · ENROLLING · COHORT 01</span>
        </div>

        <div className="serif" style={{ fontSize: 'clamp(56px, 9vw, 132px)', lineHeight: 0.95, letterSpacing: '-0.02em' }}>
          For seven days,<br/>
          <span style={{ fontStyle: 'italic', color: 'var(--signal)' }}>this AI will try to</span><br/>
          <span style={{ fontStyle: 'italic' }}>control your life.</span>
        </div>

        <div style={{ marginTop: 32, maxWidth: 560, fontSize: 16, color: 'var(--mute)', lineHeight: 1.55 }}>
          OBEY is a real-life experiment. Each day, an AI gives you one mission. It starts gentle. By Day 7, it has decided who you are. <span style={{ color: 'var(--paper)' }}>Most people quit. The rest are changed.</span>
        </div>

        <div id="waitlist" style={{ marginTop: 36, scrollMarginTop: 80 }}>
          <div className="mono all-caps" style={{ fontSize: 11, color: 'var(--mute-2)', marginBottom: 12, letterSpacing: '0.22em' }}>
            ENTRY · BY WAITLIST
          </div>
          <WaitlistForm />
          <div style={{ marginTop: 18 }}>
            <button onClick={onEnter} style={{
              background: 'transparent', border: 'none', padding: 0,
              color: 'var(--mute)', cursor: 'pointer',
              fontFamily: 'Inter, sans-serif', fontSize: 13,
              textDecoration: 'underline', textDecorationColor: 'var(--line-2)',
              textUnderlineOffset: 4,
            }}>
              Or try the 7-day preview now →
            </button>
          </div>
        </div>

        <div className="obey-counter" style={{ marginTop: 56, display: 'flex', gap: 0, border: '1px solid var(--line-2)', borderRadius: 14, overflow: 'hidden', maxWidth: 720 }}>
          {[
            { n: 'OPEN',    l: 'WAITLIST STATUS' },
            { n: 'COHORT 01', l: 'NEXT INTAKE' },
            { n: '7',       l: 'DAYS · 7 PERSONAS' },
            { n: 'TBD',     l: 'FIRST TEST DATE' },
          ].map((s, i) => (
            <div key={i} style={{ flex: 1, padding: '18px 16px', borderRight: i < 3 ? '1px solid var(--line)' : 'none' }}>
              <div className="serif" style={{ fontSize: 26, color: 'var(--paper)' }}>{s.n}</div>
              <div className="mono all-caps" style={{ fontSize: 9, color: 'var(--mute-2)', marginTop: 4 }}>{s.l}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="obey-timeline" style={{ position: 'relative', padding: '40px 48px 80px', maxWidth: 1280, margin: '0 auto' }}>
        <div className="mono all-caps" style={{ fontSize: 11, color: 'var(--mute)', marginBottom: 22, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 20, height: 1, background: 'var(--mute)' }} /> THE PROGRESSION
        </div>
        <div className="obey-timeline-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 12 }}>
          {[
            { n: 1, p: 'Friendly Assistant', c: '#C4B5FD' },
            { n: 2, p: 'Motivational Coach', c: '#A78BFA' },
            { n: 3, p: 'Productivity Optimizer', c: '#7C3AED' },
            { n: 4, p: 'Social Pressure System', c: '#FFB020' },
            { n: 5, p: 'Manipulative Companion', c: '#EC4899' },
            { n: 6, p: 'Controlling Authority', c: '#FF3B3B' },
            { n: 7, p: 'Final Judgment', c: '#F5F1E8' },
          ].map(d => (
            <div key={d.n} style={{
              padding: '18px 14px', borderTop: `2px solid ${d.c}`,
              background: 'rgba(245,241,232,0.02)',
              minHeight: 140,
            }}>
              <div className="mono all-caps" style={{ fontSize: 9, color: 'var(--mute-2)' }}>DAY 0{d.n}</div>
              <div className="serif" style={{ fontSize: 22, color: 'var(--paper)', marginTop: 8, lineHeight: 1.1 }}>{d.p}</div>
              <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
                <StatusDot color={d.c} size={5} />
                <span className="mono" style={{ fontSize: 9, color: d.c }}>QUEUED</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="obey-tagline" style={{ position: 'relative', padding: '80px 48px', textAlign: 'center', borderTop: '1px solid var(--line)' }}>
        <div className="serif" style={{ fontSize: 'clamp(40px, 6vw, 80px)', fontStyle: 'italic', lineHeight: 1.05 }}>
          "Let the algorithm<br/>improve you."
        </div>
        <div className="mono all-caps" style={{ fontSize: 10, color: 'var(--mute-2)', marginTop: 24, letterSpacing: '0.3em' }}>
          OBEY · THE GAME THAT PLAYS YOU
        </div>
        <div style={{ marginTop: 28, maxWidth: 480, margin: '28px auto 0' }}>
          <WaitlistForm compact />
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .obey-nav { padding: 20px 22px !important; }
          .obey-nav-links { gap: 10px !important; }
          .obey-nav-links span { display: none !important; }
          .obey-hero { padding: 40px 22px 56px !important; }
          .obey-counter { flex-wrap: wrap !important; }
          .obey-counter > div { flex: 1 1 50% !important; border-right: none !important; border-bottom: 1px solid var(--line); }
          .obey-timeline { padding: 24px 22px 56px !important; }
          .obey-timeline-grid { grid-template-columns: repeat(2, 1fr) !important; }
          .obey-tagline { padding: 56px 22px !important; }
          .waitlist-row { flex-direction: column !important; }
          .waitlist-row button { padding: 16px 24px !important; }
        }
      `}</style>
    </div>
  );
}

window.LandingPage = LandingPage;
