const { useState, useEffect, useRef } = React;

// ——— API ENDPOINT ———
// Paste your deployed Cloudflare Worker URL here. Leave as REPLACE_ME for local-only
// (the form will still work and show success, but nothing will be persisted).
const API_URL = "REPLACE_ME";

// ——— TWEAKS ———
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#c6ff4e",
  "serifFont": "Instrument Serif",
  "headline": "Skip the queue.",
  "sublineMode": "editorial"
}/*EDITMODE-END*/;

// ——— Noise / grain overlay ———
const Grain = () => (
  <div aria-hidden="true" style={{
    position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 100,
    opacity: 0.06, mixBlendMode: 'overlay',
    backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/></filter><rect width='100%' height='100%' filter='url(%23n)' opacity='0.6'/></svg>\")",
  }}/>
);

// ——— Top nav ———
const Nav = ({ onOpenForm }) => {
  const [t, setT] = useState('');
  useEffect(() => {
    const tick = () => {
      const d = new Date();
      const hh = String(d.getUTCHours()).padStart(2,'0');
      const mm = String(d.getUTCMinutes()).padStart(2,'0');
      const ss = String(d.getUTCSeconds()).padStart(2,'0');
      setT(`${hh}:${mm}:${ss} UTC`);
    };
    tick(); const id = setInterval(tick, 1000); return () => clearInterval(id);
  }, []);
  return (
    <header className="nav">
      <div className="nav-left">
        <div className="mark" aria-label="Checkout Service">
          <span className="mark-dot" />
          <span className="mark-word" style={{ fontFamily: 'system-ui' }}>BlackBoxAIO</span>
        </div>
        <span className="mark-tag">CHECKOUT&nbsp;SERVICE™</span>
      </div>
      <nav className="nav-mid">
        <a href="#how">How it works</a>
        <a href="#drops">Drops</a>
        <a href="#faq">FAQ</a>
        <a href="#log">Log</a>
      </nav>
      <div className="nav-right">
        <span className="clock">{t}</span>
        <button className="nav-cta" onClick={onOpenForm}>
          Join waitlist <span aria-hidden>↗</span>
        </button>
      </div>
    </header>
  );
};

// ——— Marquee ticker ———
const Ticker = () => {
  const items = [
    'LIVE — NEXT DROP WINDOW TBA',
    'FREE FOR THE FIRST 500',
    'NO SEED · NO KEY · NO FEE',
    'AVG CHECKOUT 4.8s',
    'PUBLIC BETA',
  ];
  const line = items.join('   ✦   ');
  return (
    <div className="ticker" aria-hidden>
      <div className="ticker-track">
        <span>{line}</span><span>{line}</span><span>{line}</span>
      </div>
    </div>
  );
};

// ——— Hero with inline form ———
const Hero = ({ tweaks, onSubmit, submitted }) => {
  const [email, setEmail] = useState('');
  const [handle, setHandle] = useState('');
  const [touched, setTouched] = useState({});
  const [err, setErr] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [apiError, setApiError] = useState('');

  const validate = () => {
    const e = {};
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) e.email = 'Enter a valid email.';
    const h = handle.replace(/^@/, '');
    if (!/^[A-Za-z0-9_]{1,15}$/.test(h)) e.handle = '1–15 chars, letters/numbers/underscore.';
    setErr(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (ev) => {
    ev.preventDefault();
    setTouched({ email: true, handle: true });
    setApiError('');
    if (!validate()) return;
    const cleanHandle = handle.replace(/^@/, '');

    // If no API is configured, just show success locally (dev/preview mode).
    if (!API_URL || API_URL === 'REPLACE_ME') {
      onSubmit({ email, handle: cleanHandle });
      return;
    }

    setSubmitting(true);
    try {
      const res = await fetch(API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, handle: cleanHandle }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (res.status === 409) setApiError("You're already on the list.");
        else setApiError(data.error || 'Something went wrong. Try again.');
        return;
      }
      onSubmit({ email, handle: cleanHandle, id: data.id });
    } catch (_) {
      setApiError('Network error. Try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="hero">
      <div className="hero-grid">
        {/* left: headline */}
        <div className="hero-copy">
          <div className="eyebrow">
            <span className="pulse" /> <span>FREE SUPREME CHECKOUT SERVICE</span>
            <span className="eye-sep">/</span>
            <span>INVITE-ONLY BETA</span>
          </div>
          <h1 className="display" style={{ fontFamily: `'${tweaks.serifFont}', serif` }}>
            {tweaks.headline}<br/>
            <em>Own&nbsp;the&nbsp;drop.</em>
          </h1>
          <p className="lede">
            A private checkout co-op for Supreme releases. We designed an algorithm to efficiently checkout supreme for completely free.
          </p>

          <div className="kpi-row">
            <div className="kpi">
              <div className="kpi-num">4.8<span>s</span></div>
              <div className="kpi-lbl">avg. cart → pay</div>
            </div>
            <div className="kpi">
              <div className="kpi-num">94<span>%</span></div>
              <div className="kpi-lbl">hit rate, SS26</div>
            </div>
            <div className="kpi">
              <div className="kpi-num">0<span>$</span></div>
              <div className="kpi-lbl">to join</div>
            </div>
          </div>
        </div>

        {/* right: form card */}
        <aside className="card" id="join">
          <div className="card-head">
            <span className="card-index">01 / REGISTER</span>
            <span className="card-status">● OPEN</span>
          </div>

          {!submitted ? (
            <form onSubmit={handleSubmit} noValidate>
              <label className="field">
                <span className="field-lbl">
                  <span>Email address</span>
                  <span className="field-hint">for drop alerts</span>
                </span>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onBlur={() => { setTouched(t => ({...t, email:true})); validate(); }}
                  placeholder="you@domain.com"
                  className={touched.email && err.email ? 'input err' : 'input'}
                  autoComplete="email"
                />
                {touched.email && err.email && <span className="err-msg">{err.email}</span>}
              </label>

              <label className="field">
                <span className="field-lbl">
                  <span>X / Twitter handle</span>
                  <span className="field-hint">we verify activity</span>
                </span>
                <div className={touched.handle && err.handle ? 'input-wrap err' : 'input-wrap'}>
                  <span className="input-prefix">@</span>
                  <input
                    type="text"
                    value={handle.replace(/^@/, '')}
                    onChange={(e) => setHandle(e.target.value.replace(/^@/, ''))}
                    onBlur={() => { setTouched(t => ({...t, handle:true})); validate(); }}
                    placeholder="yourhandle"
                    className="input bare"
                    autoComplete="off"
                    maxLength={15}
                  />
                </div>
                {touched.handle && err.handle && <span className="err-msg">{err.handle}</span>}
              </label>

              <div className="consent">
                <label className="check">
                  <input type="checkbox" defaultChecked />
                  <span>I agree to receive drop alerts and confirm I'm a human, not a bot.</span>
                </label>
              </div>

              <button type="submit" className="submit" disabled={submitting}>
                <span>{submitting ? 'Securing…' : 'Secure my seat'}</span>
                <span className="submit-arrow" aria-hidden>→</span>
              </button>

              {apiError && <div className="err-msg" style={{ textAlign: 'center', marginTop: 10 }}>{apiError}</div>}

              <div className="meta-row">
                <span>Spot #4,213</span>
                <span>·</span>
                <span>No password required</span>
                <span>·</span>
                <span>Unsubscribe anytime</span>
              </div>
            </form>
          ) : (
            <div className="success">
              <div className="check-bubble" aria-hidden>
                <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12.5l4.5 4.5L19 7"/>
                </svg>
              </div>
              <h3>You're in the queue.</h3>
              <p>
                Spot <b>#4,213</b> confirmed for <b>@{submitted.handle}</b>.<br/>
                Watch <b>{submitted.email}</b> — we'll send an invite if selected.
              </p>
              <div className="success-meta">
                <div><span>STATUS</span><b>QUEUED</b></div>
                <div><span>INVITE</span><b>IF SELECTED</b></div>
                <div><span>CHANNEL</span><b>EMAIL</b></div>
              </div>
            </div>
          )}
        </aside>
      </div>
    </section>
  );
};

// ——— How it works ———
const How = () => {
  const steps = [
    { n: '01', t: 'Drop your handles', d: 'Email + X. That\'s it. We cross-reference your X to make sure you\'re not a bot farm.' },
    { n: '02', t: 'Receive a seat', d: 'Randomly select people to join the discord to get free beta key.' },
    { n: '03', t: 'Click once, own it', d: 'Place the link of item desired and checkout.' },
  ];
  return (
    <section className="how" id="how">
      <div className="section-head">
        <span className="sec-idx">§ 02</span>
        <h2>Three fields. Three steps. One checkout.</h2>
      </div>
      <div className="steps">
        {steps.map(s => (
          <article key={s.n} className="step">
            <div className="step-n">{s.n}</div>
            <h3>{s.t}</h3>
            <p>{s.d}</p>
          </article>
        ))}
      </div>
    </section>
  );
};

// ——— Drops log table ———
const Log = () => {
  const rows = [
    { wk: 'WK-1', item: 'Arabic Tee -- Gray',  size: 'L',  status: 'SECURED', t: '1.42s' },
    { wk: 'WK-1', item: 'Arabic Tee -- Black', size: 'M',  status: 'SECURED', t: '2.01s' },
    { wk: 'WK-1', item: 'Arabic Tee -- Black', size: 'OS', status: 'SECURED', t: '0.98s' },
    { wk: 'WK-1', item: 'Arabic Tee -- Black', size: 'XL', status: 'MISSED',  t: '—'     },
    { wk: 'WK-1', item: 'Arabic Tee -- Pink',  size: '32', status: 'SECURED', t: '1.76s' },
    { wk: 'WK-1', item: 'Arabic Tee -- Black', size: 'S',  status: 'SECURED', t: '2.33s' },
  ];
  return (
    <section className="log" id="log">
      <div className="section-head">
        <span className="sec-idx">§ 03</span>
        <h2>The log doesn't lie.</h2>
        <p className="sec-sub">Recent member checkouts. Raw, timestamped, unedited.</p>
      </div>
      <div className="table">
        <div className="tr th">
          <div>Week</div><div>Item</div><div>Size</div><div>Status</div><div>Cart-time</div>
        </div>
        {rows.map((r, i) => (
          <div className="tr" key={i}>
            <div className="mono">{r.wk}</div>
            <div>{r.item}</div>
            <div className="mono">{r.size}</div>
            <div>
              <span className={`pill ${r.status === 'SECURED' ? 'ok' : 'miss'}`}>{r.status}</span>
            </div>
            <div className="mono">{r.t}</div>
          </div>
        ))}
      </div>
    </section>
  );
};

// ——— FAQ ———
const FAQ = () => {
  const qs = [
    { q: 'Is this really free?', a: 'As for the 1.0 version this is completely free. We developed this as a senior project for university.' },
    { q: 'Why do you need my X handle?', a: 'We do a light human-check against your X activity (account age, followers, post history). It filters out bot farms trying to brute-force seats.' },
    { q: 'Do you touch my payment info?', a: 'Never. You pay Supreme directly with your card. We store all your information locally on your device and never see it.' },
    { q: 'Will you help?', a: 'We will help guide you and set it everything and push new updates weekly.' },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section className="faq" id="faq">
      <div className="section-head">
        <span className="sec-idx">§ 04</span>
        <h2>Frequently, honestly.</h2>
      </div>
      <div className="faq-list">
        {qs.map((x, i) => (
          <div className={'faq-item ' + (open === i ? 'open' : '')} key={i}>
            <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
              <span className="faq-idx">{String(i+1).padStart(2,'0')}</span>
              <span className="faq-text">{x.q}</span>
              <span className="faq-toggle" aria-hidden>{open === i ? '–' : '+'}</span>
            </button>
            <div className="faq-a"><p>{x.a}</p></div>
          </div>
        ))}
      </div>
    </section>
  );
};

// ——— Footer ———
const Footer = () => (
  <footer className="footer">
    <div className="foot-top">
      <div className="foot-mark">
        <span className="mark-dot" /> C/S
      </div>
      <div className="foot-lines">
        <div>Independent · not affiliated with Supreme NY or any rights-holder.</div>
        <div>Made by humans who also wanted a box logo.</div>
      </div>
    </div>
    <div className="foot-bot">
      <span>© 2026 Checkout Service</span>
      <span className="mono">v0.4.2-beta</span>
      <span>Brooklyn · Tokyo</span>
    </div>
  </footer>
);

// ——— Tweaks panel ———
const TweaksPanel = ({ tweaks, setTweaks, visible }) => {
  if (!visible) return null;
  const update = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
  };
  const accents = [
    { name: 'Acid',    v: '#c6ff4e' },
    { name: 'Ember',   v: '#ff5a1f' },
    { name: 'Iris',    v: '#7c5cff' },
    { name: 'Paper',   v: '#f3f0e7' },
  ];
  const fonts = ['Instrument Serif', 'Fraunces', 'DM Serif Display', 'Playfair Display'];
  const headlines = ['Skip the queue.', 'The cop, solved.', 'Drop days, handled.', 'Retail or nothing.'];
  return (
    <div className="tweaks">
      <div className="tw-head">TWEAKS</div>

      <div className="tw-row">
        <div className="tw-lbl">Accent</div>
        <div className="tw-swatches">
          {accents.map(a => (
            <button key={a.v}
              className={'swatch ' + (tweaks.accent === a.v ? 'on' : '')}
              style={{ background: a.v }}
              onClick={() => update({ accent: a.v })}
              title={a.name}
            />
          ))}
        </div>
      </div>

      <div className="tw-row">
        <div className="tw-lbl">Display font</div>
        <select value={tweaks.serifFont} onChange={(e) => update({ serifFont: e.target.value })}>
          {fonts.map(f => <option key={f} value={f}>{f}</option>)}
        </select>
      </div>

      <div className="tw-row">
        <div className="tw-lbl">Headline</div>
        <div className="tw-chips">
          {headlines.map(h => (
            <button key={h}
              className={'chip ' + (tweaks.headline === h ? 'on' : '')}
              onClick={() => update({ headline: h })}
            >{h}</button>
          ))}
        </div>
      </div>
    </div>
  );
};

// ——— App ———
const App = () => {
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [submitted, setSubmitted] = useState(null);
  const [tweaksVisible, setTweaksVisible] = useState(false);

  useEffect(() => {
    document.documentElement.style.setProperty('--accent', tweaks.accent);
  }, [tweaks.accent]);

  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const scrollToForm = () => {
    const el = document.getElementById('join');
    if (el) {
      const r = el.getBoundingClientRect();
      window.scrollTo({ top: window.scrollY + r.top - 80, behavior: 'smooth' });
    }
  };

  return (
    <>
      <Grain />
      <Nav onOpenForm={scrollToForm} />
      <Ticker />
      <Hero tweaks={tweaks} submitted={submitted} onSubmit={setSubmitted} />
      <How />
      <Log />
      <FAQ />
      <Footer />
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} visible={tweaksVisible} />
    </>
  );
};

Object.assign(window, { App });
