// HIWStage: a rich, step-by-step animated stage for the How It Works page.
// Each step shows a custom mini-scene: a Slack post, a sync engine processing it,
// email delivery, Circle replies, and finally analytics materializing.

const { useState: useStateHW, useEffect: useEffectHW, useRef: useRefHW, useMemo: useMemoHW } = React;

// -------- shared tiny primitives --------
function MiniAvatar({ name, color, size = 24 }) {
  // use PortraitAvatar if available globally, else fall back
  if (window.PortraitAvatar) return <window.PortraitAvatar name={name} color={color} size={size}/>;
  const ini = (name||'?').split(' ').map(n=>n[0]).slice(0,2).join('').toUpperCase();
  return <div style={{width:size,height:size,borderRadius:'50%',background:color,color:'#fff',fontSize:10,fontWeight:700,display:'flex',alignItems:'center',justifyContent:'center'}}>{ini}</div>;
}

function MsgBubble({ author, color, text, delay = 0, time = '9:14 AM', align = 'left' }) {
  return (
    <div style={{
      display: 'flex', gap: 10, alignItems: 'flex-start',
      animation: `hiw-in .5s ${delay}s both`,
      flexDirection: align === 'right' ? 'row-reverse' : 'row',
    }}>
      <MiniAvatar name={author} color={color} size={28}/>
      <div style={{ minWidth: 0, flex: 1, textAlign: align }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#1A1B3A' }}>
          {author} <span style={{ fontWeight: 400, color: '#8B8695', marginLeft: 6 }}>{time}</span>
        </div>
        <div style={{ fontSize: 12, color: '#2B2C54', lineHeight: 1.45, marginTop: 2 }}>{text}</div>
      </div>
    </div>
  );
}

// ========== STEP 1: Slack post ==========
function Step1Slack() {
  return (
    <div style={{ width: '100%', height: '100%', display: 'grid', gridTemplateColumns: '70px 1fr', borderRadius: 14, overflow: 'hidden', border: '1px solid var(--site-line)', background: '#fff' }}>
      {/* Slack sidebar */}
      <div style={{ background: '#3F0E40', padding: '14px 10px', color: '#fff', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ fontSize: 10, fontWeight: 700, opacity: 0.7 }}>Leadership Exchange</div>
        <div style={{ fontSize: 10, opacity: 0.55, marginTop: 6 }}>Channels</div>
        {['general','intros','#cfo','wins'].map((c,i)=>(
          <div key={c} style={{
            fontSize: 11, padding: '3px 6px', borderRadius: 4,
            background: i===2?'#1164A3':'transparent',
            fontWeight: i===2?700:400,
          }}>#{c}</div>
        ))}
      </div>
      {/* channel content */}
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--site-line)', fontSize: 12, fontWeight: 700 }}>
          #cfo <span style={{ color: '#8B8695', fontWeight: 400, marginLeft: 6 }}>238 members</span>
        </div>
        <div style={{ padding: '14px', display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
          <MsgBubble author="Marisol D." color="#4242F0" time="9:12 AM"
            text="Anyone navigated series-B due diligence with a fractional finance team? Looking for playbooks on how you structured the data room."
            delay={0.1}/>
          {/* typing indicator morphs into send */}
          <div style={{ animation: 'hiw-in .5s .8s both', fontSize: 11, color: '#8B8695', fontStyle: 'italic' }}>
            Jordan C. is typing<span className="hiw-dots">...</span>
          </div>
          {/* send pulse */}
          <div style={{
            marginTop: 'auto',
            border: '1.5px solid #4242F0',
            borderRadius: 8, padding: '8px 10px',
            fontSize: 11, color: '#4242F0', fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 8,
            animation: 'hiw-pulse 2s infinite',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#4242F0' }}/>
            Message posted · syncing
          </div>
        </div>
      </div>
    </div>
  );
}

// ========== STEP 2: Sync engine ==========
function Step2Sync() {
  return (
    <div style={{ width: '100%', height: '100%', position: 'relative', background: '#fff', border: '1px solid var(--site-line)', borderRadius: 14, overflow: 'hidden' }}>
      {/* Three surface nodes around a central hub */}
      <svg viewBox="0 0 400 380" style={{ width: '100%', height: '100%' }}>
        {/* connecting lines from each surface to hub with travelling dots */}
        {[
          { x: 60,  y: 80,  color: '#611F69', label: 'Slack',  angle: -180 },
          { x: 340, y: 80,  color: '#D93025', label: 'Email',  angle: 0 },
          { x: 200, y: 320, color: '#2F7CFF', label: 'Circle', angle: 90 },
        ].map((n, i) => (
          <g key={n.label}>
            <line x1={n.x} y1={n.y} x2={200} y2={190}
              stroke="#E8E3D6" strokeWidth="1.5" strokeDasharray="3 4"/>
            <line x1={n.x} y1={n.y} x2={200} y2={190}
              stroke={n.color} strokeWidth="2" strokeOpacity="0.6"
              strokeDasharray="40 120" >
              <animate attributeName="stroke-dashoffset" from={i===0?'0':i===1?'80':'160'} to={i===0?'-160':i===1?'-80':'-0'} dur="2.4s" repeatCount="indefinite"/>
            </line>
          </g>
        ))}

        {/* Hub with a beating core. */}
        <g transform="translate(200,190)">
          <circle r="62" fill="#4242F0" opacity="0.06">
            <animate attributeName="r" values="62;72;62" dur="2.2s" repeatCount="indefinite"/>
          </circle>
          <circle r="46" fill="#4242F0" opacity="0.12"/>
          <circle r="34" fill="#4242F0"/>
          <text y="10" textAnchor="middle" fontFamily="Petrona" fontStyle="italic" fontSize="36" fill="#fff">S</text>
        </g>

        {/* Surface bubbles */}
        {[
          { x: 60,  y: 80,  color: '#611F69', label: 'Slack'  },
          { x: 340, y: 80,  color: '#D93025', label: 'Email'  },
          { x: 200, y: 320, color: '#2F7CFF', label: 'Circle' },
        ].map(n => (
          <g key={n.label}>
            <circle cx={n.x} cy={n.y} r="30" fill="#fff" stroke={n.color} strokeWidth="2"/>
            <text x={n.x} y={n.y+4} textAnchor="middle" fontFamily="Host Grotesk" fontSize="11" fontWeight="700" fill={n.color}>{n.label}</text>
          </g>
        ))}

        {/* fingerprint-style metadata ticker near the hub */}
        <g transform="translate(200,265)" opacity="0.85">
          {['author: marisol.d', 'ts: 09:12:04', 'thread: t-9821', 'attach: 0', 'channel: #cfo'].map((t, i) => (
            <text key={t} x="0" y={i*14} textAnchor="middle" fontFamily="Host Grotesk" fontSize="8.5" fill="#1A1B3A" opacity={0.55 - i*0.08}>
              <tspan>{t}</tspan>
              <animate attributeName="opacity" values={`${0.3 - i*0.03};${0.9 - i*0.08};${0.3 - i*0.03}`} dur="2.2s" begin={`${i*0.2}s`} repeatCount="indefinite"/>
            </text>
          ))}
        </g>
      </svg>

      {/* label overlay */}
      <div style={{ position: 'absolute', top: 12, left: 14, fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#4242F0' }}>
        Sync engine · fingerprinting
      </div>
    </div>
  );
}

// ========== STEP 3: Email delivery ==========
function Step3Email() {
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', background: '#fff', border: '1px solid var(--site-line)', borderRadius: 14, overflow: 'hidden' }}>
      <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--site-line)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 18, height: 18, borderRadius: 4, background: '#D93025', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 10, fontWeight: 800 }}>M</div>
        <span style={{ fontSize: 11, fontWeight: 700 }}>Inbox</span>
        <span style={{ fontSize: 10, color: '#8B8695' }}>· cfo-community digest</span>
      </div>
      <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 6, flex: 1, overflow: 'hidden' }}>
        {[
          { who: 'Leadership Exchange', sub: 'Marisol D. posted: incident communication playbook…', time: 'now', unread: true, hl: true },
          { who: 'Rising Stars', sub: 'Your weekly member pulse is ready', time: '8m', unread: true },
          { who: 'Events', sub: 'RSVP: fractional finance roundtable (Thu)', time: '1h' },
          { who: 'Intros', sub: '3 new introductions to review', time: '3h' },
        ].map((r, i) => (
          <div key={i} style={{
            display: 'flex', gap: 10, alignItems: 'center',
            padding: '8px 10px',
            background: r.hl ? '#EFEFFE' : 'transparent',
            borderRadius: 8,
            border: r.hl ? '1px solid #4242F055' : '1px solid transparent',
            animation: r.hl ? 'hiw-in .5s .3s both, hiw-pulse 2.4s .8s infinite' : `hiw-in .5s ${0.5 + i*0.1}s both`,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: r.unread ? '#4242F0' : 'transparent' }}/>
            <span style={{ fontSize: 11, fontWeight: 700, width: 80, flexShrink: 0 }}>{r.who}</span>
            <span style={{ fontSize: 11, color: '#2B2C54', flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.sub}</span>
            <span style={{ fontSize: 10, color: '#8B8695' }}>{r.time}</span>
          </div>
        ))}

        {/* Reply composer pops up */}
        <div style={{ marginTop: 'auto', border: '1px solid var(--site-line)', borderRadius: 10, padding: 10, background: '#FAF8F3', animation: 'hiw-in .6s 1.2s both' }}>
          <div style={{ fontSize: 10, color: '#8B8695', marginBottom: 6 }}>Replying to <b style={{ color: '#1A1B3A' }}>Marisol D.</b> · thread continues in Slack & Circle</div>
          <div style={{ fontSize: 11, color: '#2B2C54', lineHeight: 1.4 }}>
            We built ours around three workstreams. Happy to share the template we used…
            <span style={{ display: 'inline-block', width: 2, height: 12, background: '#4242F0', marginLeft: 2, verticalAlign: 'middle', animation: 'hiw-blink 1s infinite' }}/>
          </div>
          <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
            <span style={{ fontSize: 10, fontWeight: 700, background: '#1A73E8', color: '#fff', padding: '4px 10px', borderRadius: 4 }}>Send</span>
            <span style={{ fontSize: 10, color: '#8B8695', padding: '4px 8px' }}>Syncs to Slack + Circle</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ========== STEP 4: Circle replies ==========
function Step4Circle() {
  const replies = [
    { who: 'Priya R.',   color: '#21C089', text: 'We phased the data room. Docs first, live model second. Cut 3 weeks off diligence.', time: '12m', reacts: ['🔥','💯'], delay: 0.2 },
    { who: 'Sam G.',     color: '#F5B820', text: 'Curious which workstream you kept fractional vs in-house?', time: '9m', reacts: ['👀'], delay: 0.6 },
    { who: 'Noor A.',    color: '#2F7CFF', text: 'Template here. Steal freely. Works for series-A too.', time: '4m', reacts: ['🙏','⭐','❤️'], delay: 1.0, attach: true },
    { who: 'Dmitri K.',  color: '#B24848', text: 'Reply coming from Slack, same thread.', time: '1m', reacts: [], delay: 1.4, viaSlack: true },
  ];
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', background: '#fff', border: '1px solid var(--site-line)', borderRadius: 14, overflow: 'hidden' }}>
      <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--site-line)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 18, height: 18, borderRadius: 4, border: '2px solid #2F7CFF', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#2F7CFF' }}/>
        </div>
        <span style={{ fontSize: 11, fontWeight: 700 }}>Leadership Exchange · Forum</span>
        <span style={{ marginLeft: 'auto', fontSize: 10, color: '#8B8695', display: 'flex', alignItems: 'center', gap: 4 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#21C089', animation: 'hiw-pulse 1.4s infinite' }}/>
          Live · 4 replies
        </span>
      </div>
      <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 10, flex: 1, overflow: 'hidden' }}>
        {/* OP */}
        <div style={{ padding: 10, background: '#FAF8F3', borderRadius: 10, border: '1px solid var(--site-line)' }}>
          <MsgBubble author="Marisol D." color="#4242F0" time="9:12 AM"
            text="Anyone navigated series-B due diligence with a fractional finance team?"/>
        </div>
        {replies.map((r,i) => (
          <div key={i} style={{ paddingLeft: 14, borderLeft: '2px solid var(--site-line)' }}>
            <MsgBubble author={r.who} color={r.color} time={r.time} text={r.text} delay={r.delay}/>
            <div style={{ display: 'flex', gap: 6, marginTop: 6, marginLeft: 38, alignItems: 'center', animation: `hiw-in .4s ${r.delay + 0.2}s both` }}>
              {r.reacts.map((rx, j) => (
                <span key={j} style={{ fontSize: 10, padding: '2px 6px', background: '#EFEFFE', borderRadius: 999, border: '1px solid #4242F022' }}>{rx} {j+1}</span>
              ))}
              {r.attach && <span style={{ fontSize: 10, color: '#4242F0', fontWeight: 600 }}>📎 series-b-dataroom.pdf</span>}
              {r.viaSlack && <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 6px', background: '#3F0E40', color: '#fff', borderRadius: 4, letterSpacing: '.04em' }}>VIA SLACK</span>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ========== STEP 5: Analytics payoff ==========
function Step5Analytics() {
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', gap: 10, background: '#fff', border: '1px solid var(--site-line)', borderRadius: 14, padding: 14, overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 11, fontWeight: 700 }}>Thread insights</span>
        <span style={{ marginLeft: 'auto', fontSize: 10, color: '#8B8695' }}>Marisol's post · 2h</span>
      </div>

      {/* 4 KPI chips with counting numbers */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
        {[
          { k: 'Reach',    v: '642',  c: '#4242F0' },
          { k: 'Replies',  v: '24',   c: '#21C089' },
          { k: 'Reacts',   v: '87',   c: '#F5B820' },
          { k: 'Surfaces', v: '3/3',  c: '#2F7CFF' },
        ].map((m, i) => (
          <div key={m.k} style={{ border: '1px solid var(--site-line)', borderRadius: 8, padding: '8px 10px', animation: `hiw-in .5s ${i*0.1}s both` }}>
            <div style={{ fontSize: 9, color: '#8B8695', fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase' }}>{m.k}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, color: m.c, lineHeight: 1, marginTop: 2 }}>{m.v}</div>
          </div>
        ))}
      </div>

      {/* Surface split bar */}
      <div style={{ marginTop: 4 }}>
        <div style={{ fontSize: 10, color: '#8B8695', fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 6 }}>Where the activity lived</div>
        <div style={{ display: 'flex', height: 10, borderRadius: 5, overflow: 'hidden', border: '1px solid var(--site-line)' }}>
          <div style={{ width: '46%', background: '#611F69' }}/>
          <div style={{ width: '30%', background: '#D93025' }}/>
          <div style={{ width: '24%', background: '#2F7CFF' }}/>
        </div>
        <div style={{ display: 'flex', gap: 10, fontSize: 10, color: '#8B8695', marginTop: 6 }}>
          <span><span style={{ display: 'inline-block', width: 8, height: 8, background: '#611F69', borderRadius: 2, marginRight: 4 }}/>Slack 46%</span>
          <span><span style={{ display: 'inline-block', width: 8, height: 8, background: '#D93025', borderRadius: 2, marginRight: 4 }}/>Email 30%</span>
          <span><span style={{ display: 'inline-block', width: 8, height: 8, background: '#2F7CFF', borderRadius: 2, marginRight: 4 }}/>Circle 24%</span>
        </div>
      </div>

      {/* Contributor categories tied to participants */}
      <div style={{ marginTop: 6 }}>
        <div style={{ fontSize: 10, color: '#8B8695', fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 6 }}>Who engaged</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { who: 'Priya R.',  tag: 'Super User',     color: '#4242F0' },
            { who: 'Noor A.',   tag: 'Rising Star',    color: '#21C089' },
            { who: 'Sam G.',    tag: 'Active',         color: '#2F7CFF' },
            { who: 'Dmitri K.', tag: 'Rising Star',    color: '#21C089' },
          ].map((r, i) => (
            <div key={r.who} style={{ display: 'flex', alignItems: 'center', gap: 8, animation: `hiw-in .4s ${0.3 + i*0.08}s both` }}>
              <MiniAvatar name={r.who} color={r.color} size={20}/>
              <span style={{ fontSize: 11, fontWeight: 600, color: '#1A1B3A' }}>{r.who}</span>
              <span style={{ marginLeft: 'auto', fontSize: 9, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: r.color + '22', color: r.color, letterSpacing: '.04em' }}>
                {r.tag.toUpperCase()}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ========== Main stage ==========
function HIWStage({ step }) {
  // stage labels for the header
  const labels = [
    { n: '01', t: 'Post lands in Slack',   c: '#611F69' },
    { n: '02', t: 'Synchronize fingerprints + mirrors', c: '#4242F0' },
    { n: '03', t: 'Email members get the thread',    c: '#D93025' },
    { n: '04', t: 'Replies flow back across surfaces', c: '#2F7CFF' },
    { n: '05', t: 'You see the full picture',        c: '#21C089' },
  ];
  const L = labels[step] || labels[0];

  return (
    <div style={{
      background: 'var(--site-bg-alt, #FAF8F3)',
      border: '1px solid var(--site-line)',
      borderRadius: 24,
      padding: 18,
      height: '100%',
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 12px 40px rgba(26,27,58,0.06)',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Ambient floating dots */}
      <svg style={{ position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.4 }} viewBox="0 0 500 460" preserveAspectRatio="none">
        {[...Array(16)].map((_, i) => (
          <circle key={i} cx={30 + (i*29)%470} cy={20 + (i*53)%420} r={1.5}
            fill={i%3===0?'#4242F0':i%3===1?'#D93025':'#21C089'}>
            <animate attributeName="cy" values={`${20 + (i*53)%420};${20 + (i*53)%420 - 14};${20 + (i*53)%420}`} dur={`${3 + (i%5)}s`} repeatCount="indefinite"/>
            <animate attributeName="opacity" values="0.3;1;0.3" dur={`${2 + (i%4)}s`} repeatCount="indefinite"/>
          </circle>
        ))}
      </svg>

      {/* Header with step pills */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 14, position: 'relative' }}>
        {labels.map((l, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 4,
            padding: '4px 8px', borderRadius: 999,
            background: i === step ? l.c : i < step ? l.c + '22' : '#fff',
            border: `1px solid ${i === step ? l.c : 'var(--site-line)'}`,
            fontSize: 10, fontWeight: 700,
            color: i === step ? '#fff' : i < step ? l.c : '#8B8695',
            transition: 'all .3s',
          }}>
            <span>{l.n}</span>
            {i === step && <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#fff', animation: 'hiw-pulse 1.4s infinite' }}/>}
          </div>
        ))}
      </div>

      {/* Stage caption */}
      <div key={step} style={{ marginBottom: 12, animation: 'hiw-in .4s both' }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.08em', color: L.c, textTransform: 'uppercase' }}>
          Step {L.n}
        </div>
        <div style={{ fontSize: 15, fontWeight: 600, color: '#1A1B3A', marginTop: 2 }}>{L.t}</div>
      </div>

      {/* Scene swap */}
      <div style={{ flex: 1, position: 'relative', minHeight: 0 }}>
        <div key={step} style={{ position: 'absolute', inset: 0, animation: 'hiw-swap .5s both' }}>
          {step === 0 && <Step1Slack/>}
          {step === 1 && <Step2Sync/>}
          {step === 2 && <Step3Email/>}
          {step === 3 && <Step4Circle/>}
          {step === 4 && <Step5Analytics/>}
        </div>
      </div>

      {/* progress bar */}
      <div style={{ marginTop: 12, height: 3, borderRadius: 2, background: 'var(--site-line)', overflow: 'hidden' }}>
        <div style={{
          width: `${((step+1)/5)*100}%`, height: '100%', background: L.c,
          transition: 'width .5s, background .3s',
        }}/>
      </div>

      <style>{`
        @keyframes hiw-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
        @keyframes hiw-swap { from { opacity: 0; transform: scale(0.98); } to { opacity: 1; transform: none; } }
        @keyframes hiw-pulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.15); } }
        @keyframes hiw-blink { 0%,100% { opacity: 1; } 50% { opacity: 0; } }
        .hiw-dots::after { content: '...'; animation: hiw-blink 1.4s infinite; }
      `}</style>
    </div>
  );
}

Object.assign(window, { HIWStage });
