/* global React */
const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

// =============== WAITLIST ===============
function Waitlist({ openRef }) {
  const [step, setStep] = useStateW(0); // 0 = intro, 1,2,3 = form steps, 4 = done
  const [data, setData] = useStateW({
    businessName: '',
    contact: '',
    phone: '',
    website: '',
    helpFirst: [],
    describes: '',
    why: '',
    package: '',
  });

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggleMulti = (k, v) => setData(d => {
    const arr = d[k] || [];
    return { ...d, [k]: arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v] };
  });

  useEffectW(() => {
    if (openRef) openRef.current = () => {
      document.getElementById('waitlist')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      setTimeout(() => setStep(1), 400);
    };
  }, [openRef]);

  const canNext = (() => {
    if (step === 1) return data.businessName.trim() && data.contact.trim();
    if (step === 2) return data.helpFirst.length > 0 && data.describes;
    if (step === 3) return data.why.trim() && data.package;
    return true;
  })();

  return (
    <section className="section" id="waitlist" data-screen-label="10 Waitlist">
      <div className="container narrow">
        <Reveal>
          <div className="eyebrow" style={{ marginBottom: 40 }}>09 — Waitlist</div>
        </Reveal>
        <Reveal delay={0.1}>
          <h2 className="h-section" style={{ marginBottom: 24 }}>
            Get early access to Han Ai.
          </h2>
        </Reveal>
        <Reveal delay={0.18}>
          <p className="lede" style={{ marginBottom: 56 }}>
            We're rolling Han Ai out with a small number of businesses first.
          </p>
        </Reveal>

        {step === 0 && (
          <Reveal delay={0.2}>
            <div className="grid-3" style={{ marginBottom: 56 }}>
              <BlockCard
                kicker="Block 01"
                title="Why join early"
                items={[
                  'Priority onboarding',
                  'Closer founder involvement',
                  'Early influence on product direction',
                  'Access before wider rollout',
                ]}
              />
              <BlockCard
                kicker="Block 02"
                title="What changes"
                items={[
                  { before: 'Content is inconsistent', after: 'Content gets planned' },
                  { before: 'Approvals are slow', after: 'Approvals are structured' },
                  { before: 'Execution depends on follow-up', after: 'Publishing runs consistently' },
                ]}
                paired
              />
              <BlockCard
                kicker="Block 03"
                title="Who early access is for"
                intro="Premium SMEs that:"
                items={[
                  'Care about brand and execution',
                  'Are already active in marketing',
                  'Want leverage without more staff',
                  'Are open to structured workflows',
                ]}
              />
            </div>
            <div style={{ textAlign: 'center' }}>
              <p className="mono-num" style={{ marginBottom: 18, color: 'var(--faint)' }}>Takes less than 60 seconds.</p>
              <button className="btn btn-primary" onClick={() => setStep(1)} style={{ padding: '18px 32px', fontSize: 16 }}>
                Start early access application
                <Arrow />
              </button>
            </div>
          </Reveal>
        )}

        {step >= 1 && step <= 3 && (
          <div className="card" style={{ padding: 'clamp(32px, 4vw, 56px)', borderRadius: 28, marginTop: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 36 }}>
              <div className="step-dots">
                {[1, 2, 3].map(i => (
                  <span key={i} className={`step-dot ${i === step ? 'active' : i < step ? 'done' : ''}`} />
                ))}
              </div>
              <span className="mono-num">STEP {step} / 3</span>
            </div>

            {step === 1 && (
              <div>
                <h3 className="h-sub" style={{ marginBottom: 8 }}>Tell us about the business.</h3>
                <p className="body" style={{ marginBottom: 36 }}>A few basics so we know who we're talking to.</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }} className="form-grid">
                  <div className="field">
                    <label className="field-label">Business name</label>
                    <input className="field-input" placeholder="e.g. Amber Hospitality Group" value={data.businessName} onChange={e => update('businessName', e.target.value)} />
                  </div>
                  <div className="field">
                    <label className="field-label">Main contact</label>
                    <input className="field-input" placeholder="Full name" value={data.contact} onChange={e => update('contact', e.target.value)} />
                  </div>
                  <div className="field">
                    <label className="field-label">Telegram or phone</label>
                    <input className="field-input" placeholder="@handle or +855…" value={data.phone} onChange={e => update('phone', e.target.value)} />
                  </div>
                  <div className="field">
                    <label className="field-label">Website / Meta page</label>
                    <input className="field-input" placeholder="https://" value={data.website} onChange={e => update('website', e.target.value)} />
                  </div>
                </div>
              </div>
            )}

            {step === 2 && (
              <div>
                <h3 className="h-sub" style={{ marginBottom: 8 }}>Where do we start?</h3>
                <p className="body" style={{ marginBottom: 36 }}>Pick anything that applies.</p>

                <div style={{ marginBottom: 40 }}>
                  <label className="field-label" style={{ display: 'block', marginBottom: 16 }}>What do you want help with first?</label>
                  <div className="choice-row">
                    {['Content consistency', 'Publishing', 'Meta growth support', 'Broader operations'].map(o => (
                      <button key={o} className={`choice ${data.helpFirst.includes(o) ? 'active' : ''}`} onClick={() => toggleMulti('helpFirst', o)} type="button">{o}</button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="field-label" style={{ display: 'block', marginBottom: 16 }}>Which best describes your business right now?</label>
                  <div className="choice-row">
                    {['Posting inconsistently', 'Active but messy execution', 'Running ads but need better performance', 'Want stronger operating structure'].map(o => (
                      <button key={o} className={`choice ${data.describes === o ? 'active' : ''}`} onClick={() => update('describes', o)} type="button">{o}</button>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {step === 3 && (
              <div>
                <h3 className="h-sub" style={{ marginBottom: 8 }}>The last bit.</h3>
                <p className="body" style={{ marginBottom: 36 }}>Helps us prioritize strong-fit conversations.</p>

                <div className="field" style={{ marginBottom: 40 }}>
                  <label className="field-label">Why are you interested in Han Ai now?</label>
                  <textarea className="field-textarea" placeholder="A sentence or two is enough." value={data.why} onChange={e => update('why', e.target.value)} />
                </div>

                <div>
                  <label className="field-label" style={{ display: 'block', marginBottom: 16 }}>Preferred package</label>
                  <div className="choice-row">
                    {['Content & Publishing System', 'Content + Ad Performance System', 'Business Operations Layer', 'Not sure yet'].map(o => (
                      <button key={o} className={`choice ${data.package === o ? 'active' : ''}`} onClick={() => update('package', o)} type="button">{o}</button>
                    ))}
                  </div>
                </div>
              </div>
            )}

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 48, gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-ghost" onClick={() => step > 1 ? setStep(step - 1) : setStep(0)} type="button">
                {step === 1 ? 'Back' : '← Previous'}
              </button>
              {step < 3 ? (
                <button className="btn btn-primary" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.35 }} onClick={() => canNext && setStep(step + 1)} type="button">
                  Continue
                  <Arrow />
                </button>
              ) : (
                <button className="btn btn-primary" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.35 }} onClick={() => canNext && setStep(4)} type="button">
                  Submit application
                  <Arrow />
                </button>
              )}
            </div>
          </div>
        )}

        {step === 4 && (
          <div className="card" style={{ padding: 'clamp(40px, 6vw, 80px)', textAlign: 'center', borderRadius: 28, background: 'linear-gradient(180deg, #EDF2F8 0%, #DCE6F0 100%)', border: '1px solid transparent' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--ink)', color: 'var(--paper)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 11.5L9 15.5L17 7.5" />
              </svg>
            </div>
            <h3 className="h-section" style={{ fontSize: 'clamp(28px, 3.2vw, 44px)', marginBottom: 16 }}>Application received.</h3>
            <p className="lede" style={{ margin: '0 auto' }}>
              Thanks, {data.contact || 'we\u2019ll'} — we'll review and come back within a few working days if there's a strong fit.
            </p>
            <button className="btn btn-ghost" onClick={() => { setStep(0); setData({ businessName: '', contact: '', phone: '', website: '', helpFirst: [], describes: '', why: '', package: '' }); }} style={{ marginTop: 32 }} type="button">
              Start another
            </button>
          </div>
        )}
      </div>
      <style>{`@media(max-width:640px){.form-grid{grid-template-columns:1fr !important}}`}</style>
    </section>
  );
}

function BlockCard({ kicker, title, items, intro, paired }) {
  return (
    <article className="card" style={{ display: 'flex', flexDirection: 'column', gap: 20, minHeight: 320 }}>
      <div className="mono-num">{kicker}</div>
      <h3 style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', margin: 0, lineHeight: 1.2 }}>{title}</h3>
      {intro && <p className="body" style={{ fontSize: 14, margin: 0 }}>{intro}</p>}
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it, i) => (
          <li key={i} style={{ fontSize: 14, color: 'var(--ink)', paddingTop: 10, borderTop: '1px solid var(--hair)' }}>
            {paired && typeof it === 'object' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span style={{ color: 'var(--faint)', fontSize: 12, textDecoration: 'line-through' }}>{it.before}</span>
                <span style={{ color: 'var(--ink)', fontWeight: 500 }}>{it.after}</span>
              </div>
            ) : (
              <span>{typeof it === 'string' ? it : it.after}</span>
            )}
          </li>
        ))}
      </ul>
    </article>
  );
}

// =============== FINAL CTA ===============
function FinalCTA({ onCta }) {
  return (
    <section className="section" data-screen-label="11 Join us" style={{ paddingTop: 'clamp(60px, 8vw, 100px)', paddingBottom: 'clamp(100px, 14vw, 180px)' }}>
      <Scene shapes={[
        { variant: 'sky',    position: 'cb', size: '120vh', speed: 0.22 },
        { variant: 'violet', position: 'tr', size: '55vh', speed: -0.1 },
      ]} />
      <div className="container narrowest text-center">
        <Reveal>
          <h2 className="h-display" style={{ fontSize: 'clamp(40px, 6vw, 80px)' }}>
            We're starting with a small number of strong-fit businesses.
          </h2>
        </Reveal>
        <Reveal delay={0.12}>
          <p className="lede" style={{ margin: '32px auto 44px' }}>
            If you want early access and a chance to shape how Han Ai evolves —
          </p>
        </Reveal>
        <Reveal delay={0.22}>
          <button className="btn btn-primary" onClick={onCta} style={{ padding: '20px 34px', fontSize: 17 }}>
            Join the early access list
            <Arrow />
          </button>
        </Reveal>
        <Reveal delay={0.27}>
          <p className="body" style={{ marginTop: 18, color: 'var(--faint)', fontSize: 14, fontWeight: 400 }}>
            See if this fits your business.
          </p>
        </Reveal>
        <Reveal delay={0.32}>
          <div style={{ marginTop: 64, display: 'flex', gap: 16, justifyContent: 'center', alignItems: 'center', color: 'var(--faint)', flexWrap: 'wrap' }}>
            <Monogram size={18} />
            <span className="mono-num">Han Ai — where intelligence meets execution.</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// =============== FOOTER ===============
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div className="nav-brand" style={{ marginBottom: 16 }}>
            <Monogram size={24} />
            <span style={{ fontWeight: 600, fontSize: 18, letterSpacing: '-0.02em' }}>Han Ai</span>
          </div>
          <p className="body" style={{ maxWidth: 320, fontSize: 14 }}>
            An execution layer for premium SMEs. Built by Han Studios.
          </p>
        </div>
        <div>
          <div className="mono-num" style={{ marginBottom: 14 }}>PRODUCT</div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
            <li><a href="#what">What it does</a></li>
            <li><a href="#systems">Systems</a></li>
            <li><a href="#waitlist">Waitlist</a></li>
          </ul>
        </div>
        <div>
          <div className="mono-num" style={{ marginBottom: 14 }}>STUDIO</div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
            <li><a href="https://hanstudioskh.com" target="_blank" rel="noopener">Han Studios</a></li>
            <li><a href="mailto:hello@hanstudios.co">hello@hanstudios.co</a></li>
            <li><a href="https://t.me/hanstudios" target="_blank" rel="noopener">Telegram</a></li>
          </ul>
        </div>
        <div>
          <div className="mono-num" style={{ marginBottom: 14 }}>LEGAL</div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
            <li><a href="#">Privacy</a></li>
            <li><a href="#">Terms</a></li>
          </ul>
        </div>
      </div>
      <div style={{ maxWidth: 'var(--max)', margin: '64px auto 0', paddingTop: 24, borderTop: '1px solid var(--hair)', display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--faint)', flexWrap: 'wrap', gap: 12 }}>
        <span className="mono-num">© 2026 HAN STUDIOS · HAN AI</span>
        <span className="mono-num">WHERE INTELLIGENCE MEETS EXECUTION</span>
      </div>
    </footer>
  );
}

// =============== TWEAKS PANEL ===============
function TweaksPanel({ settings, setSettings }) {
  const [visible, setVisible] = useStateW(false);
  useEffectW(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setVisible(true);
      if (e.data?.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const persist = (patch) => {
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
  };
  const update = (k, v) => {
    const next = { ...settings, [k]: v };
    setSettings(next);
    persist({ [k]: v });
  };

  if (!visible) return null;

  return (
    <div className="tweaks-panel">
      <h4>Tweaks</h4>
      <div className="tweaks-row">
        <label>Palette</label>
        <div className="tweaks-seg">
          {[{ k: 'paper', l: 'Paper' }, { k: 'neutral', l: 'Neutral' }, { k: 'ink', l: 'Ink' }].map(o => (
            <button key={o.k} className={settings.palette === o.k ? 'on' : ''} onClick={() => update('palette', o.k)}>{o.l}</button>
          ))}
        </div>
      </div>
      <div className="tweaks-row">
        <label>Display weight</label>
        <div className="tweaks-seg">
          {[{ k: 'light', l: 'Light' }, { k: 'regular', l: 'Regular' }, { k: 'bold', l: 'Bold' }].map(o => (
            <button key={o.k} className={settings.weight === o.k ? 'on' : ''} onClick={() => update('weight', o.k)}>{o.l}</button>
          ))}
        </div>
      </div>
      <div className="tweaks-row">
        <label>Hero status badges</label>
        <div className="tweaks-seg">
          <button className={settings.showBadges ? 'on' : ''} onClick={() => update('showBadges', true)}>Show</button>
          <button className={!settings.showBadges ? 'on' : ''} onClick={() => update('showBadges', false)}>Hide</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Waitlist, BlockCard, FinalCTA, Footer, TweaksPanel });
