/* global React */
const { useState: useState2, useEffect: useEffect2, useRef: useRef2 } = React;

// =============== LIVE CHAT STACK ===============
const CHAT_MESSAGES = [
  { sender: 'ai', meta: 'Han Ai · 09:42', body: (
    <>
      <strong style={{ fontWeight: 500 }}>3 posts ready for your review.</strong><br/>
      <span style={{ color: 'var(--muted)' }}>Campaign: Spring launch</span>
    </>
  )},
  { sender: 'me', body: 'Approve all ✓' },
  { sender: 'ai', meta: 'Han Ai · 09:43', body: 'Scheduled. Publishing over the next 7 days.' },
];

function ChatStack() {
  const ref = useRef2(null);
  const [step, setStep] = useState2(0);
  const [running, setRunning] = useState2(false);

  useEffect2(() => {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) setRunning(true); });
    }, { threshold: 0.35 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  useEffect2(() => {
    if (!running) return;
    const total = CHAT_MESSAGES.length * 2;
    const isTyping = step % 2 === 1;
    const isFinal = step >= total;
    let delay;
    if (step === 0) delay = 600;
    else if (isFinal) delay = 4500;
    else if (isTyping) delay = 1200;
    else delay = 700;
    const id = setTimeout(() => {
      setStep(s => (s >= total ? 0 : s + 1));
    }, delay);
    return () => clearTimeout(id);
  }, [step, running]);

  return (
    <div className="chat-stack" ref={ref}>
      {CHAT_MESSAGES.map((m, i) => {
        const visibleStep = (i + 1) * 2;
        const typingStep = i * 2 + 1;
        const isVisible = step >= visibleStep;
        const isTyping = step === typingStep;
        if (isVisible) {
          return (
            <div key={`m${i}`} className={`chat-bubble ${m.sender === 'me' ? 'sent' : ''}`}>
              {m.meta && <span className="meta">{m.meta}</span>}
              {m.body}
            </div>
          );
        }
        if (isTyping) {
          return (
            <div key={`t${i}`} className={`chat-bubble typing ${m.sender === 'me' ? 'sent' : ''}`}>
              <span className="dot" /><span className="dot" /><span className="dot" />
            </div>
          );
        }
        return null;
      })}
    </div>
  );
}

// =============== WHAT HAN AI DOES ===============
function WhatItDoes() {
  const items = [
    { n: '01', t: 'Plan content', d: 'A running content plan built around your brand, calendar, and goals.' },
    { n: '02', t: 'Generate ready-to-review drafts', d: 'Drafts arrive written, formatted, and queued — ready for you to approve.' },
    { n: '03', t: 'Route approvals', d: 'The right person reviews at the right time. Nothing sits in limbo.' },
    { n: '04', t: 'Publish consistently', d: 'Scheduled, published, and verified. Cadence holds without reminders.' },
    { n: '05', t: 'Support Meta performance', d: 'We watch what actually performs and adjust direction, not just output.' },
    { n: '06', t: 'Surface what needs attention', d: 'You only see what truly needs your call — nothing else.' },
  ];
  return (
    <section className="section" id="what" data-screen-label="04 What Han Ai does">
      <Scene shapes={[
        { variant: 'violet', position: 'tr', size: '70vh', speed: 0.16 },
      ]} />
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 'clamp(40px, 6vw, 96px)', alignItems: 'start' }} className="what-grid">
          <div style={{ position: 'sticky', top: 120 }}>
            <Reveal>
              <div className="eyebrow" style={{ marginBottom: 28 }}>03 — Capability</div>
            </Reveal>
            <Reveal delay={0.1}>
              <h2 className="h-section">What Han Ai does</h2>
            </Reveal>
            <Reveal delay={0.2}>
              <p className="body" style={{ marginTop: 24, maxWidth: 380 }}>
                Managed and approved directly from your phone.
              </p>
            </Reveal>
          </div>
          <div>
            {items.map((it, i) => (
              <Reveal key={it.n} delay={i * 0.05}>
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '60px 1fr',
                  gap: 24,
                  padding: '28px 0',
                  borderTop: '1px solid var(--hair)',
                }}>
                  <span className="mono-num">{it.n}</span>
                  <div>
                    <h3 className="h-sub" style={{ margin: 0 }}>{it.t}</h3>
                    <p className="body" style={{ marginTop: 8, maxWidth: 520 }}>{it.d}</p>
                  </div>
                </div>
              </Reveal>
            ))}
            <div style={{ borderTop: '1px solid var(--hair)' }} />
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 860px) {
          .what-grid { grid-template-columns: 1fr !important; }
          .what-grid > div:first-child { position: static !important; }
        }
      `}</style>
    </section>
  );
}

// =============== CONTROL / PHONE ===============
function Control() {
  return (
    <section className="section" data-screen-label="05 Run from your phone">
      <Scene shapes={[
        { variant: 'mint', position: 'tl', size: '95vh', speed: 0.2 },
        { variant: 'sky',  position: 'br', size: '60vh', speed: -0.12 },
      ]} />
      <div className="container">
        <Reveal>
          <div className="eyebrow" style={{ marginBottom: 40, textAlign: 'center' }}>04 — Control</div>
        </Reveal>
        <Reveal delay={0.08}>
          <h2 className="h-section text-center" style={{ margin: '0 auto', maxWidth: 900 }}>
            Run your business from your phone.
          </h2>
        </Reveal>
        <Reveal delay={0.16}>
          <p className="lede text-center" style={{ margin: '28px auto 0' }}>
            Han Ai is designed to work where you already are. Plan, review, approve, and manage execution directly from your phone — without logging into complex systems or chasing updates.
          </p>
        </Reveal>

        <Reveal delay={0.28}>
          <div className="phone-scene" style={{ marginTop: 72 }}>
            <div className="phone-wrap">
              <img src="assets/han-ai-phone-portrait.png" alt="Han Ai phone view" />
              <ChatStack />
            </div>
            <div>
              <h3 className="h-sub" style={{ letterSpacing: '-0.02em', marginBottom: 28, fontWeight: 600 }}>
                Stay in control without managing everything.
              </h3>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {[
                  'Approve content instantly',
                  'Review what\u2019s ready',
                  'See what\u2019s blocked',
                  'Get alerts when action is needed',
                  'Stay in control without managing everything',
                ].map((l, i) => (
                  <li key={i} style={{
                    padding: '16px 0',
                    borderTop: '1px solid var(--hair)',
                    display: 'flex', gap: 18, alignItems: 'center',
                    fontSize: 17, color: 'var(--ink)', fontWeight: 500, letterSpacing: '-0.01em'
                  }}>
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ color: 'var(--ink)', flexShrink: 0 }}>
                      <path d="M3 7.2L5.8 10L11 4.5" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                    {l}
                  </li>
                ))}
                <li style={{ borderTop: '1px solid var(--hair)', padding: 0 }} />
              </ul>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// =============== BEFORE / AFTER ===============
function BeforeAfter() {
  const before = [
    'Inconsistent posting',
    'Slow approvals',
    'Unclear performance',
    'Owner chasing execution',
  ];
  const after = [
    'Content gets planned',
    'Approvals are structured',
    'Publishing runs consistently',
    'Performance becomes visible',
  ];
  return (
    <section className="section section-tight" data-screen-label="06 What changes" style={{ background: 'var(--paper-2)' }}>
      <div className="container">
        <Reveal>
          <div className="eyebrow" style={{ marginBottom: 40 }}>05 — What changes</div>
        </Reveal>
        <Reveal delay={0.1}>
          <h2 className="h-section" style={{ marginBottom: 64 }}>What changes with Han Ai</h2>
        </Reveal>
        <div className="grid-2">
          <Reveal delay={0.18}>
            <div className="ba-col before">
              <h4>Before</h4>
              <ul>
                {before.map((l, i) => <li key={i}>— {l}</li>)}
              </ul>
            </div>
          </Reveal>
          <Reveal delay={0.28}>
            <div className="ba-col after">
              <h4>After</h4>
              <ul>
                {after.map((l, i) => <li key={i}>{l}.</li>)}
              </ul>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// =============== SYSTEMS ===============
function Systems() {
  const cards = [
    {
      badge: 'System 01',
      title: 'Content & Publishing System',
      sub: 'Content gets planned, approved, and published without you chasing it.',
      outcome: 'Your content runs without you chasing it.',
      meta: 'Available now',
    },
    {
      badge: 'System 02',
      title: 'Content + Ad Performance System',
      sub: 'We help improve what actually performs, not just what gets posted.',
      outcome: 'Know what works before you spend more.',
      meta: 'Available now',
    },
    {
      badge: 'System 03',
      title: 'Business Operations Layer',
      sub: 'A deeper operating layer for businesses that need more control and leverage.',
      outcome: 'More leverage, without adding more people.',
      meta: 'Coming soon',
      soon: true,
    },
  ];
  return (
    <section className="section" id="systems" data-screen-label="07 Systems">
      <Scene shapes={[
        { variant: 'sky',    position: 'bl', size: '85vh', speed: 0.18 },
        { variant: 'violet', position: 'tr', size: '50vh', speed: -0.1 },
      ]} />
      <div className="container">
        <Reveal>
          <div className="eyebrow" style={{ marginBottom: 40 }}>06 — Systems</div>
        </Reveal>
        <Reveal delay={0.1}>
          <h2 className="h-section" style={{ maxWidth: 820, marginBottom: 64 }}>
            Structured systems,<br/><span style={{ color: 'var(--muted)' }}>not scattered work.</span>
          </h2>
        </Reveal>
        <div className="grid-3">
          {cards.map((c, i) => (
            <Reveal key={i} delay={0.1 + i * 0.08}>
              <article className={`system-card ${c.soon ? 'soon' : ''}`}>
                <div className="badge">{c.badge}</div>
                <h3 className="title">{c.title}</h3>
                <p className="sub">{c.sub}</p>
                <p className="outcome" style={{ marginTop: 12, paddingTop: 16, borderTop: '1px solid var(--hair)', fontSize: 14, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.01em' }}>{c.outcome}</p>
                <div className="meta">
                  <span className="mono-num">{c.meta}</span>
                  {!c.soon && <Arrow />}
                </div>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// =============== WHO IT'S FOR ===============
function Who() {
  const items = [
    'Care about brand and consistency',
    'Already invest in marketing',
    'Want execution to run reliably',
    'Don\u2019t want a large internal team',
  ];
  return (
    <section className="section section-tight" data-screen-label="08 Who it's for">
      <div className="container narrow">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 'clamp(32px, 5vw, 80px)' }} className="who-grid">
          <div>
            <Reveal>
              <div className="eyebrow" style={{ marginBottom: 28 }}>07 — Who it's for</div>
            </Reveal>
            <Reveal delay={0.1}>
              <h2 className="h-section">Who it's for</h2>
            </Reveal>
          </div>
          <div>
            <Reveal delay={0.18}>
              <p className="lede" style={{ marginBottom: 28 }}>
                Han Ai is built for premium SMEs that:
              </p>
            </Reveal>
            {items.map((l, i) => (
              <Reveal key={i} delay={0.22 + i * 0.05}>
                <div style={{
                  padding: '18px 0', borderTop: '1px solid var(--hair)',
                  fontSize: 'clamp(18px, 1.6vw, 22px)', color: 'var(--ink)', fontWeight: 500, letterSpacing: '-0.015em'
                }}>
                  {l}
                </div>
              </Reveal>
            ))}
            <div style={{ borderTop: '1px solid var(--hair)' }} />
          </div>
        </div>
      </div>
      <style>{`@media(max-width:760px){.who-grid{grid-template-columns:1fr !important}}`}</style>
    </section>
  );
}

// =============== TRUST — BUILT BY HAN STUDIOS ===============
function Trust() {
  return (
    <section className="section section-tight" id="trust" data-screen-label="09 Built by Han Studios">
      <Scene shapes={[
        { variant: 'violet', position: 'r', size: '90vh', speed: 0.18 },
      ]} />
      <div className="container narrow">
        <Reveal>
          <div className="eyebrow" style={{ marginBottom: 40 }}>08 — Origin</div>
        </Reveal>
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 'clamp(32px, 5vw, 80px)', alignItems: 'end' }} className="trust-grid">
          <Reveal delay={0.1}>
            <h2 className="h-section">
              Built by <span style={{ fontStyle: 'italic', fontWeight: 500 }}>Han Studios.</span>
            </h2>
          </Reveal>
          <Reveal delay={0.2}>
            <p className="body" style={{ maxWidth: 460, fontSize: 17 }}>
              Han AI is developed by Han Studios — a marketing and production company behind high-performance campaigns across Cambodia.
            </p>
          </Reveal>
        </div>
      </div>
      <style>{`@media(max-width:760px){.trust-grid{grid-template-columns:1fr !important}}`}</style>
    </section>
  );
}

Object.assign(window, { WhatItDoes, Control, BeforeAfter, Systems, Who, Trust });
