// v3-howitworks.jsx — "How it works" + a LIVING product visual + the control line.
// Placement: right after MindModel ("One mind for your whole world"), before
// PromiseLines. Answers the skeptical SMB owner's "is this real / how do I start
// / does it act behind my back?" questions in one beat.
//
// The phone is the real Lantic Everyday surface: the Cortex orb is the HERO,
// Lantic says one thoughtful thing, and ONE category card surfaces at a time.
// It auto-cycles through a real day (morning → money → team → family → evening)
// so it feels alive and human, not like a static app screenshot.
//
// Reuses window primitives from lantic-ui.jsx: BRAND, SAT, SF, MONO, Cortex,
// PhoneFrame, useInView, useViewport, useReducedMotion.

const { BRAND: HIW_BRAND, SAT: HIW_SAT, SF: HIW_SF, MONO: HIW_MONO } = window;

if (typeof document !== 'undefined' && !document.getElementById('hiw-kf')) {
  const s = document.createElement('style'); s.id = 'hiw-kf';
  s.textContent = `
    @keyframes hiw-cardin { 0%{opacity:0;transform:translateY(22px)} 100%{opacity:1;transform:translateY(0)} }
    @keyframes hiw-linein { 0%{opacity:0;transform:translateY(8px)} 100%{opacity:1;transform:translateY(0)} }
    @keyframes hiw-breath { 0%,100%{transform:scale(1)} 50%{transform:scale(1.03)} }
    @keyframes hiw-eq { 0%,100%{transform:scaleY(.32)} 50%{transform:scaleY(1)} }
    @keyframes hiw-ring { 0%{transform:scale(.8);opacity:.5} 100%{transform:scale(1.9);opacity:0} }
  `;
  document.head.appendChild(s);
}

// The day, as a sequence of moments. Each = Lantic's spoken line + the one card
// it surfaces. mode 'approve' shows the control (Approve / Edit); 'handled'/'soft'
// show a quieter state.
const HIW_MOMENTS = [
  { time: 'TUE · 7:02 AM', col: '#10B981', cat: 'MONEY',
    line: 'Morning, Dave. Two things need a nod before your 9.',
    headline: 'Morrison’s invoice is 8 days over.',
    context: 'I drafted a friendly chase. Have a read before it goes.',
    mode: 'approve' },
  { time: 'TUE · 7:03 AM', col: '#38BDF8', cat: 'WORK',
    line: 'Two new leads came in overnight. Both your kind of job.',
    headline: 'Replies drafted, in your voice.',
    context: 'Residential, both in your postcode. Want them sent?',
    mode: 'approve' },
  { time: 'TUE · 11:40 AM', col: '#7DD3FC', cat: 'TEAM',
    line: 'Friday’s cover is sorted. You don’t need to call anyone.',
    headline: 'Jordan’s covering Friday.',
    context: 'Agreed it with his Lantic. Your calendar’s already updated.',
    mode: 'handled' },
  { time: 'TUE · 2:18 PM', col: '#FB923C', cat: 'FAMILY',
    line: 'Pickup’s at 3. Want me to hold your calls till 3:30?',
    headline: 'Sophie’s game is Friday, 4 PM.',
    context: 'I’ve guarded the slot so nothing books over it.',
    mode: 'soft', actions: ['Hold calls', 'Not today'] },
  { time: 'TUE · 7:42 PM', col: '#F472B6', cat: 'HEALTH',
    line: 'That’s the day done. Tomorrow’s set. Go enjoy your evening.',
    headline: 'Your walk’s still open at 6.',
    context: 'I kept it clear. Want a nudge at quarter to?',
    mode: 'soft', actions: ['Nudge me', 'I’m good'] },
];

// ── The orb, as hero, with a speaking waveform ──────────────────────────────
function HiwOrbHero({ col, speaking, reduced }) {
  const Orb = window.Cortex;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <div style={{ position: 'relative', width: 132, height: 132, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {!reduced && speaking && [0, 1].map(r => (
          <span key={r} aria-hidden style={{ position: 'absolute', inset: 14, borderRadius: '50%',
            border: `1.5px solid ${col}`, animation: `hiw-ring 2.2s ease-out ${r * 1.1}s infinite` }}/>
        ))}
        <div style={{ animation: reduced ? 'none' : 'hiw-breath 5s ease-in-out infinite' }}>
          <Orb size={112} animate={!reduced} glowLobe={col} glowAlpha={speaking ? 0.9 : 0.6}/>
        </div>
      </div>
      {/* waveform — present while Lantic is speaking */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3.5, height: 16, marginTop: 10,
        opacity: speaking ? 1 : 0, transition: 'opacity 300ms ease' }}>
        {[0, 1, 2, 3, 4, 5, 6].map(b => (
          <span key={b} style={{ width: 2.5, height: 16, borderRadius: 2, background: col, transformOrigin: 'bottom',
            animation: reduced ? 'none' : `hiw-eq ${0.85 + (b % 3) * 0.16}s ease-in-out ${b * 0.08}s infinite` }}/>
        ))}
      </div>
    </div>
  );
}

// ── The one focused category card ───────────────────────────────────────────
function HiwFocusCard({ m, idx, total }) {
  return (
    <div key={idx} style={{ animation: 'hiw-cardin 560ms cubic-bezier(.22,1,.36,1)' }}>
      <div style={{ padding: 15, borderRadius: 18,
        background: 'rgba(255,255,255,.05)', border: `1px solid ${m.col}3d`,
        boxShadow: `0 18px 40px -22px ${m.col}` }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 9 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: m.col, boxShadow: `0 0 7px ${m.col}` }}/>
            <span style={{ fontFamily: HIW_MONO, fontSize: 10, color: m.col, letterSpacing: '0.18em', fontWeight: 700 }}>{m.cat}</span>
          </div>
          <span style={{ fontFamily: HIW_MONO, fontSize: 9.5, color: HIW_BRAND.dim }}>{m.time.split('·')[1].trim()}</span>
        </div>
        <div style={{ fontFamily: HIW_SAT, fontWeight: 600, fontSize: 16, lineHeight: 1.28, letterSpacing: -0.4, color: HIW_BRAND.ink, marginBottom: 6 }}>{m.headline}</div>
        <div style={{ fontFamily: HIW_SF, fontSize: 12.5, lineHeight: 1.45, color: HIW_BRAND.sub, textWrap: 'pretty' }}>{m.context}</div>

        {m.mode === 'approve' ? (
          <div style={{ display: 'flex', gap: 7, marginTop: 13 }}>
            <span style={{ height: 30, padding: '0 14px', borderRadius: 15, display: 'inline-flex', alignItems: 'center', gap: 6,
              background: m.col, color: '#04121e', fontFamily: HIW_SF, fontSize: 12, fontWeight: 700 }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="#04121e" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
              Approve &amp; send
            </span>
            <span style={{ height: 30, padding: '0 14px', borderRadius: 15, display: 'inline-flex', alignItems: 'center',
              background: 'transparent', color: HIW_BRAND.sub, border: `1px solid ${HIW_BRAND.cardBorder}`, fontFamily: HIW_SF, fontSize: 12, fontWeight: 600 }}>Edit</span>
          </div>
        ) : m.mode === 'handled' ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 12,
            fontFamily: HIW_MONO, fontSize: 9.5, letterSpacing: '0.14em', fontWeight: 700, color: HIW_BRAND.good }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke={HIW_BRAND.good} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
            HANDLED · FYI
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 7, marginTop: 13 }}>
            <span style={{ height: 30, padding: '0 14px', borderRadius: 15, display: 'inline-flex', alignItems: 'center',
              background: `${m.col}22`, color: m.col, border: `1px solid ${m.col}55`, fontFamily: HIW_SF, fontSize: 12, fontWeight: 600 }}>{m.actions[0]}</span>
            <span style={{ height: 30, padding: '0 14px', borderRadius: 15, display: 'inline-flex', alignItems: 'center',
              background: 'transparent', color: HIW_BRAND.sub, border: `1px solid ${HIW_BRAND.cardBorder}`, fontFamily: HIW_SF, fontSize: 12, fontWeight: 600 }}>{m.actions[1]}</span>
          </div>
        )}
      </div>
      {/* page dots — which category we're on */}
      <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 14 }}>
        {Array.from({ length: total }).map((_, d) => (
          <span key={d} style={{ width: d === idx ? 18 : 6, height: 6, borderRadius: 4,
            background: d === idx ? m.col : 'rgba(255,255,255,.22)',
            boxShadow: d === idx ? `0 0 7px ${m.col}` : 'none', transition: 'all 360ms cubic-bezier(.22,1,.36,1)' }}/>
        ))}
      </div>
    </div>
  );
}

// ── The living phone ─────────────────────────────────────────────────────────
function HiwPhone({ shown, compact }) {
  const Phone = window.PhoneFrame;
  const reduced = window.useReducedMotion ? window.useReducedMotion() : false;
  const [i, setI] = React.useState(0);
  const [speaking, setSpeaking] = React.useState(true);

  React.useEffect(() => {
    if (!shown || reduced) return;
    let speakT;
    const adv = setInterval(() => {
      setI(p => (p + 1) % HIW_MOMENTS.length);
      setSpeaking(true);
      clearTimeout(speakT);
      speakT = setTimeout(() => setSpeaking(false), 1700);
    }, 3600);
    speakT = setTimeout(() => setSpeaking(false), 1700);
    return () => { clearInterval(adv); clearTimeout(speakT); };
  }, [shown, reduced]);

  const m = HIW_MOMENTS[i];

  return (
    <Phone width={compact ? 286 : 316} height={compact ? 600 : 648} glow={true}>
      <div style={{ position: 'absolute', inset: 0, paddingTop: 44, overflow: 'hidden' }}>
        {/* sky wash that tints to the active lobe */}
        <div aria-hidden style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 260,
          background: `radial-gradient(ellipse 85% 64% at 50% 4%, ${m.col}3a 0%, transparent 70%)`,
          transition: 'background 700ms ease' }}/>

        {/* top chrome: nav handle + profile, no tabs */}
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 20px 0' }}>
          <div style={{ width: 32, height: 32, borderRadius: 16, border: `1px solid ${HIW_BRAND.hair}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: HIW_BRAND.dim }}>
            <svg width="13" height="13" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.6" fill="currentColor"/><circle cx="12" cy="12" r="1.6" fill="currentColor"/><circle cx="19" cy="12" r="1.6" fill="currentColor"/></svg>
          </div>
          <div style={{ width: 30, height: 30, borderRadius: 15, background: `linear-gradient(135deg, ${HIW_BRAND.skyDark}, ${HIW_BRAND.skyDeep})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: HIW_SAT, fontWeight: 700, fontSize: 12, color: HIW_BRAND.ink }}>D</div>
        </div>

        {/* orb hero */}
        <div style={{ position: 'relative', marginTop: compact ? 14 : 20 }}>
          <HiwOrbHero col={m.col} speaking={speaking} reduced={reduced}/>
        </div>

        {/* Lantic's voice line */}
        <div style={{ position: 'relative', padding: '0 22px', marginTop: 16, textAlign: 'center', minHeight: 58 }}>
          <div style={{ fontFamily: HIW_MONO, fontSize: 9.5, color: HIW_BRAND.dim, letterSpacing: '0.16em', marginBottom: 8 }}>{m.time}</div>
          <div key={i} style={{ fontFamily: HIW_SAT, fontWeight: 500, fontSize: 15.5, lineHeight: 1.34, letterSpacing: -0.3,
            color: HIW_BRAND.ink, textWrap: 'balance', animation: 'hiw-linein 520ms cubic-bezier(.22,1,.36,1)' }}>{m.line}</div>
        </div>

        {/* one focused card, swiping up through the day */}
        <div style={{ position: 'absolute', left: 16, right: 16, bottom: compact ? 78 : 84 }}>
          <HiwFocusCard m={m} idx={i} total={HIW_MOMENTS.length}/>
        </div>

        {/* talk-to-Lantic pill */}
        <div style={{ position: 'absolute', left: 16, right: 16, bottom: compact ? 22 : 26,
          height: 46, borderRadius: 23, background: 'rgba(255,255,255,.05)', border: `1px solid ${HIW_BRAND.cardBorder}`,
          display: 'flex', alignItems: 'center', padding: '0 18px', gap: 10 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M4 5h16v11H8l-4 3V5z" stroke={HIW_BRAND.skyMist} strokeWidth="1.6" strokeLinejoin="round"/></svg>
          <span style={{ fontFamily: HIW_SF, fontSize: 13, color: HIW_BRAND.dim }}>Prefer to keep it quiet? Type here…</span>
        </div>
      </div>
    </Phone>
  );
}

// ─────────────────────────────────────────────────────────────────
// HowItWorks — the full section.
// ─────────────────────────────────────────────────────────────────
function HowItWorks() {
  const ref = React.useRef(null);
  const inView = window.useInView(ref, 0.22);
  const vw = window.useViewport();
  const phone = vw < 760;

  const steps = [
    { n: '1', t: 'Connect your world',
      d: 'Link what you already use, email, calendar, Xero, ServiceM8. A couple of taps each. No IT, no training day.' },
    { n: '2', t: 'Lantic learns you',
      d: 'It quietly reads your world: how you work, who matters, how you talk. It gets sharper every day.' },
    { n: '3', t: 'You stay in charge',
      d: 'Lantic plans, drafts and chases in the background, then taps you. You approve. It acts. Never the other way round.' },
  ];

  return (
    <section ref={ref} style={{
      position: 'relative', padding: phone ? '96px 20px 100px' : '150px 32px 160px',
      background: HIW_BRAND.canvas, overflow: 'hidden',
      borderTop: `1px solid ${HIW_BRAND.hair}`
    }}>
      <div aria-hidden style={{ position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 50% 50% at 78% 30%, ${HIW_BRAND.skyDark}22 0%, transparent 62%)` }}/>

      <div style={{ maxWidth: 1160, margin: '0 auto', position: 'relative' }}>
        {/* header */}
        <div style={{ marginBottom: phone ? 44 : 64, maxWidth: 640 }}>
          <div style={{ fontFamily: HIW_MONO, fontSize: 11, color: HIW_BRAND.skyMist,
            letterSpacing: '0.26em', fontWeight: 600, textTransform: 'uppercase', marginBottom: 16 }}>How it works</div>
          <h2 style={{ margin: 0, fontFamily: HIW_SAT, fontWeight: 600,
            fontSize: phone ? 'clamp(32px, 8vw, 44px)' : 'clamp(44px, 4.6vw, 62px)',
            letterSpacing: -2, lineHeight: 1.04, color: HIW_BRAND.ink, textWrap: 'balance' }}>
            Set up once.<br/>Then it just runs.
          </h2>
        </div>

        {/* two columns: steps + phone */}
        <div style={{ display: 'grid',
          gridTemplateColumns: phone ? '1fr' : '1fr minmax(300px, 380px)',
          gap: phone ? 48 : 80, alignItems: 'center' }}>

          {/* steps + control callout */}
          <div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: phone ? 30 : 38 }}>
              {steps.map((s, i) => (
                <div key={s.n} style={{ display: 'flex', gap: 20,
                  opacity: inView ? 1 : 0, transform: inView ? 'none' : 'translateY(14px)',
                  transition: `opacity 640ms ease ${i * 130}ms, transform 640ms cubic-bezier(.22,1,.36,1) ${i * 130}ms` }}>
                  <div style={{ flex: '0 0 auto', width: 46, height: 46, borderRadius: 23,
                    border: `1px solid ${HIW_BRAND.skyDark}`, background: `${HIW_BRAND.skyDark}26`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: HIW_SAT, fontWeight: 600, fontSize: 19, color: HIW_BRAND.skyMist }}>{s.n}</div>
                  <div style={{ paddingTop: 2 }}>
                    <div style={{ fontFamily: HIW_SAT, fontWeight: 600, fontSize: phone ? 21 : 24,
                      letterSpacing: -0.6, color: HIW_BRAND.ink, marginBottom: 7 }}>{s.t}</div>
                    <div style={{ fontFamily: HIW_SF, fontSize: phone ? 15.5 : 16.5, lineHeight: 1.5,
                      color: HIW_BRAND.sub, maxWidth: 460, textWrap: 'pretty' }}>{s.d}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* the control line — a quiet, confident reassurance strip */}
            <div style={{ marginTop: phone ? 36 : 46, display: 'flex', gap: 14, alignItems: 'flex-start',
              padding: phone ? '18px 18px' : '20px 22px', borderRadius: 16,
              background: `${HIW_BRAND.good}12`, border: `1px solid ${HIW_BRAND.good}3a`, maxWidth: 540,
              opacity: inView ? 1 : 0, transform: inView ? 'none' : 'translateY(14px)',
              transition: 'opacity 700ms ease 420ms, transform 700ms cubic-bezier(.22,1,.36,1) 420ms' }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" style={{ flex: '0 0 auto', marginTop: 1 }}>
                <path d="M12 2l8 4v5c0 5-3.5 8.5-8 11-4.5-2.5-8-6-8-11V6l8-4z" stroke={HIW_BRAND.good} strokeWidth="1.6" fill="none"/>
                <path d="M8.5 12l2.5 2.5L15.5 9.5" stroke={HIW_BRAND.good} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <div>
                <div style={{ fontFamily: HIW_SAT, fontWeight: 600, fontSize: 17, color: HIW_BRAND.ink,
                  letterSpacing: -0.3, marginBottom: 4 }}>Nothing happens behind your back.</div>
                <div style={{ fontFamily: HIW_SF, fontSize: 14.5, lineHeight: 1.5, color: HIW_BRAND.sub, textWrap: 'pretty' }}>
                  Lantic proposes. You approve. Then it acts. You can change the rules, or pull it back, any time.
                </div>
              </div>
            </div>
          </div>

          {/* the product visual */}
          <div style={{ display: 'flex', justifyContent: 'center',
            opacity: inView ? 1 : 0, transform: inView ? 'none' : 'translateY(20px) scale(.98)',
            transition: 'opacity 800ms ease 200ms, transform 800ms cubic-bezier(.22,1,.36,1) 200ms' }}>
            <HiwPhone shown={inView} compact={phone}/>
          </div>
        </div>
      </div>
    </section>
  );
}

window.HowItWorks = HowItWorks;
