// AI walkthrough — animated multi-scene video showing the Thraxel AI Hub in action
// Auto-cycles between scenes; user can also click chapter markers to jump.

const { useState: useStateAI, useEffect: useEffectAI, useRef: useRefAI, useMemo: useMemoAI } = React;

const SCENES = [
  { id:'replace',  title:'Replace 12+ softwares', dur: 6500 },
  { id:'voice',    title:'AI voice answers your business', dur: 6500 },
  { id:'avatar',   title:'On-brand AI avatars', dur: 6500 },
  { id:'booking',  title:'Booking on autopilot', dur: 6500 },
  { id:'leadmap',  title:'God\u2019s-eye lead map', dur: 7000 },
];

function useSceneCycle(scenes){
  const [i, setI] = useStateAI(0);
  const [paused, setPaused] = useStateAI(false);
  const [progress, setProgress] = useStateAI(0); // 0..1 within scene
  const startRef = useRefAI(performance.now());
  useEffectAI(()=>{
    let raf;
    const tick = ()=>{
      if (!paused){
        const elapsed = performance.now() - startRef.current;
        const dur = scenes[i].dur;
        const p = Math.min(1, elapsed / dur);
        setProgress(p);
        if (p >= 1){
          setI((i+1) % scenes.length);
          startRef.current = performance.now();
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return ()=> cancelAnimationFrame(raf);
  }, [i, paused]);
  const goto = (idx)=>{
    setI(idx);
    startRef.current = performance.now();
    setProgress(0);
  };
  return { i, progress, paused, setPaused, goto };
}

// ---------- SCENE 1: Replace 12+ softwares ----------
function SceneReplace({ progress }){
  const apps = [
    { name:'QuickBooks', color:'#2CA01C', mark:'qb' },
    { name:'HubSpot',    color:'#FF7A59', mark:'hs' },
    { name:'ServiceTitan',color:'#FFB200',mark:'st' },
    { name:'Jobber',     color:'#1E73BE', mark:'jb' },
    { name:'Stripe',     color:'#635BFF', mark:'st2' },
    { name:'Gmail',      color:'#EA4335', mark:'gm' },
    { name:'Twilio',     color:'#F22F46', mark:'tw' },
    { name:'Calendly',   color:'#006BFF', mark:'cl' },
    { name:'Slack',      color:'#4A154B', mark:'sl' },
    { name:'Mailchimp',  color:'#FFE01B', mark:'mc' },
    { name:'Zendesk',    color:'#03363D', mark:'zd' },
    { name:'Asana',      color:'#F06A6A', mark:'as' },
  ];
  // Phase 0-0.5: apps fly in around perimeter
  // Phase 0.5-0.75: red sweep eliminates them
  // Phase 0.75-1: THRAXEL hub pulses with $ savings counter

  const eliminated = progress > 0.55;
  const finalPhase = progress > 0.78;
  const sweepX = (progress - 0.55) / 0.2; // 0..1 during sweep

  return (
    <div style={{position:'absolute',inset:0,padding:32}}>
      {/* perimeter apps */}
      {apps.map((a, idx)=>{
        const ang = (idx / apps.length) * Math.PI * 2 - Math.PI/2;
        const r = 36;
        const x = 50 + Math.cos(ang)*r;
        const y = 50 + Math.sin(ang)*r;
        const flyIn = Math.min(1, progress*3 - idx*0.04);
        const op = eliminated ? Math.max(0, 1 - sweepX*1.4 - idx*0.05) : Math.max(0, flyIn);
        const scale = eliminated ? 0.6 + (1-Math.max(0,1-sweepX))*0 : 0.4 + 0.6*Math.max(0,flyIn);
        const xOff = eliminated ? (idx%2?-1:1) * sweepX * 200 : 0;
        return (
          <div key={a.name} style={{
            position:'absolute',left:`${x}%`,top:`${y}%`,
            transform:`translate(-50%,-50%) translate(${xOff}px, ${eliminated? sweepX*40:0}px) scale(${scale})`,
            opacity: op,
            transition:'opacity 0.3s, transform 0.3s',
            display:'flex',alignItems:'center',gap:10,
            padding:'10px 16px',background:'#161616',border:`1px solid ${a.color}66`,
            boxShadow: eliminated ? 'none' : `0 0 14px ${a.color}33`,
            whiteSpace:'nowrap',
          }}>
            <div style={{width:14,height:14,borderRadius:3,background:a.color}}/>
            <div style={{fontFamily:'Orbitron,sans-serif',fontSize:10,fontWeight:700,letterSpacing:'0.12em',color:'#fff'}}>{a.name}</div>
            {eliminated && (
              <svg style={{position:'absolute',inset:0,pointerEvents:'none',opacity:1-sweepX*0.6}} viewBox="0 0 100 30" preserveAspectRatio="none">
                <line x1="0" y1="0" x2="100" y2="30" stroke="#C8102E" strokeWidth="2" opacity={Math.min(1,sweepX*3)}/>
              </svg>
            )}
          </div>
        );
      })}

      {/* red sweep wave */}
      {progress > 0.5 && progress < 0.78 && (
        <div style={{
          position:'absolute',top:0,bottom:0,left:`${-20 + sweepX*120}%`,width:'30%',
          background:'linear-gradient(90deg,transparent,rgba(200,16,46,0.5),transparent)',
          filter:'blur(8px)',pointerEvents:'none',
        }}/>
      )}

      {/* central THRAXEL hub */}
      <div style={{
        position:'absolute',left:'50%',top:'50%',transform:`translate(-50%,-50%) scale(${finalPhase?1.1:0.85})`,
        transition:'transform 0.5s',
        width:170,height:170,borderRadius:'50%',
        background:'radial-gradient(circle,rgba(200,16,46,0.35) 0%,rgba(200,16,46,0.05) 60%,transparent 100%)',
        border:'2px solid var(--thraxel-red)',
        boxShadow: finalPhase ? '0 0 80px rgba(200,16,46,0.6),inset 0 0 40px rgba(200,16,46,0.2)' : '0 0 30px rgba(200,16,46,0.3)',
        display:'flex',alignItems:'center',justifyContent:'center',
      }}>
        <div style={{textAlign:'center'}}>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:900,fontSize:15,letterSpacing:'0.22em',color:'#fff'}}>THRAXEL</div>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:10,letterSpacing:'0.2em',color:'var(--thraxel-red)',marginTop:4}}>AI HUB</div>
        </div>
      </div>

      {/* savings stat */}
      {finalPhase && (
        <div style={{
          position:'absolute',left:'50%',bottom:24,transform:'translateX(-50%)',
          padding:'10px 22px',background:'rgba(0,0,0,0.7)',border:'1px solid rgba(58,255,122,0.4)',
          fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:12,letterSpacing:'0.18em',color:'#3aff7a',
          opacity: Math.min(1,(progress-0.78)*5),
        }}>
          ↓ ${Math.floor(2400 + (progress-0.78)*4000)}/mo SAVED
        </div>
      )}
    </div>
  );
}

// ---------- SCENE 2: AI Voice ----------
function SceneVoice({ progress }){
  // Phase 0-0.3: phone rings/incoming call
  // Phase 0.3-0.7: AI voice waveform + caller transcript
  // Phase 0.7-1: actions fire — calendar block created, lead saved
  const showCall = progress > 0.05;
  const showWave = progress > 0.25;
  const showTranscript = progress > 0.32;
  const showActions = progress > 0.7;
  const wavePhase = progress * 14;

  const transcript = [
    { who:'CALLER', text:'"Hey, looking for a quote on permanent lights."', t:0.34 },
    { who:'RANDY',  text:'"Got it. What city are you in?"', t:0.46 },
    { who:'CALLER', text:'"Cranberry Township."', t:0.56 },
    { who:'RANDY',  text:'"Perfect — that\'s in our route. Single story or two?"', t:0.66 },
  ];

  return (
    <div style={{position:'absolute',inset:0,padding:'24px 32px',display:'flex',flexDirection:'column',gap:14}}>
      {/* top: incoming call card */}
      <div style={{
        display:'flex',alignItems:'center',gap:16,
        padding:'14px 20px',background:'#0a0a0a',border:'1px solid #2a2a2e',
        opacity: showCall ? 1 : 0,transform: `translateX(${showCall?0:-20}px)`,
        transition:'opacity 0.5s, transform 0.5s',
      }}>
        <div style={{
          width:42,height:42,borderRadius:'50%',background:'#1a1a1e',
          display:'flex',alignItems:'center',justifyContent:'center',
          border:'1px solid #2a2a2e',position:'relative',
        }}>
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#3aff7a" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
          {/* pulse ring */}
          <div style={{position:'absolute',inset:-6,border:'2px solid rgba(58,255,122,0.5)',borderRadius:'50%',animation:'ringPulse 1.4s ease-out infinite'}}/>
        </div>
        <div style={{flex:1}}>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.18em',color:'#3aff7a'}}>● INCOMING · AI ANSWERED</div>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:14,color:'#fff',marginTop:2}}>+1 (724) 555-0188</div>
        </div>
        <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:11,letterSpacing:'0.16em',color:'var(--thraxel-mid-grey)'}}>00:0{Math.floor(progress*5)}</div>
      </div>

      {/* waveform */}
      <div style={{
        height:64,background:'linear-gradient(180deg,#0a0a0a,#080808)',border:'1px solid #2a2a2e',
        display:'flex',alignItems:'center',justifyContent:'center',gap:3,padding:'0 20px',
        opacity: showWave ? 1 : 0, transition:'opacity 0.4s',
      }}>
        {Array.from({length:48}).map((_,i)=>{
          const h = 6 + Math.abs(Math.sin(i*0.5 + wavePhase))*30 * (1 - Math.abs((i-24)/30));
          return <div key={i} style={{width:3,height:h,background:i<24+wavePhase*4 && i>24-wavePhase*4 ? 'var(--thraxel-red)':'#2a2a2e',borderRadius:2,transition:'height 0.05s'}}/>;
        })}
      </div>

      {/* transcript */}
      <div style={{flex:1,display:'flex',flexDirection:'column',gap:8,overflow:'hidden'}}>
        {transcript.map((t,i)=>{
          const visible = showTranscript && progress > t.t;
          return (
            <div key={i} style={{
              display:'flex',gap:10,alignItems:'flex-start',
              opacity: visible ? 1 : 0, transform: `translateY(${visible?0:6}px)`,
              transition:'opacity 0.3s, transform 0.3s',
            }}>
              <div style={{
                fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:9,letterSpacing:'0.18em',
                color: t.who==='RANDY' ? 'var(--thraxel-red)' : '#9a9a9f',
                minWidth:60,paddingTop:3,
              }}>{t.who}</div>
              <div style={{
                padding:'8px 14px',
                background: t.who==='RANDY'? 'rgba(200,16,46,0.08)':'#0a0a0a',
                border:`1px solid ${t.who==='RANDY'?'rgba(200,16,46,0.3)':'#2a2a2e'}`,
                fontSize:13,color:'#fff',lineHeight:1.4,
              }}>{t.text}</div>
            </div>
          );
        })}
      </div>

      {/* actions row */}
      <div style={{display:'flex',gap:10,opacity: showActions?1:0, transform:`translateY(${showActions?0:8}px)`,transition:'opacity 0.4s, transform 0.4s'}}>
        {[
          {label:'LEAD CREATED',color:'#3aff7a'},
          {label:'CALLBACK SCHEDULED',color:'#FFB347'},
          {label:'QUOTE PREP QUEUED',color:'var(--thraxel-red)'},
        ].map(a=>(
          <div key={a.label} style={{
            flex:1,padding:'10px 12px',background:'#0a0a0a',border:`1px solid ${a.color}55`,
            fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:9,letterSpacing:'0.16em',color:a.color,textAlign:'center',
          }}>✓ {a.label}</div>
        ))}
      </div>

      <style>{`@keyframes ringPulse{0%{transform:scale(1);opacity:0.7}100%{transform:scale(1.6);opacity:0}}`}</style>
    </div>
  );
}

// ---------- SCENE 3: Avatar ----------
function SceneAvatar({ progress }){
  // Phase 0-0.4: avatar generates in (skeletal -> filled portrait)
  // Phase 0.4-0.8: avatar speaks; controls show ("voice", "tone", "video reply")
  // Phase 0.8-1: video reply preview generated

  const generated = progress > 0.35;
  const showControls = progress > 0.42;
  const showOutput = progress > 0.78;

  return (
    <div style={{position:'absolute',inset:0,padding:'24px 28px',display:'grid',gridTemplateColumns:'220px 1fr',gap:20}}>
      {/* avatar window */}
      <div style={{
        position:'relative',background:'linear-gradient(180deg,#1a0d0f 0%,#08080a 100%)',
        border:'1px solid #2a2a2e',overflow:'hidden',borderRadius:6,
      }}>
        {/* synthetic portrait silhouette */}
        <svg viewBox="0 0 200 240" style={{width:'100%',height:'100%',display:'block'}}>
          <defs>
            <linearGradient id="hairGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0" stopColor="#3a2a1a"/>
              <stop offset="1" stopColor="#1a1208"/>
            </linearGradient>
            <linearGradient id="skinGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0" stopColor="#e0b896"/>
              <stop offset="1" stopColor="#b08866"/>
            </linearGradient>
            <linearGradient id="shirtGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0" stopColor="#1a1a1e"/>
              <stop offset="1" stopColor="#0a0a0a"/>
            </linearGradient>
          </defs>
          {/* shoulders */}
          <path d="M20 240 Q20 180 60 170 L140 170 Q180 180 180 240 Z" fill={generated?'url(#shirtGrad)':'#1a1a1e'} opacity={generated?1:0.4}/>
          {/* neck */}
          <rect x="86" y="150" width="28" height="30" fill={generated?'url(#skinGrad)':'#444'} opacity={generated?1:0.4}/>
          {/* head */}
          <ellipse cx="100" cy="100" rx="50" ry="58" fill={generated?'url(#skinGrad)':'#444'} opacity={generated?1:0.4}/>
          {/* hair */}
          <path d="M50 80 Q50 40 100 40 Q150 40 150 80 Q150 70 130 65 L70 65 Q50 70 50 80 Z" fill={generated?'url(#hairGrad)':'#222'} opacity={generated?1:0.4}/>
          {/* eyes */}
          <ellipse cx="82" cy="98" rx="3.5" ry={generated?2.5:0.8} fill="#1a1208"/>
          <ellipse cx="118" cy="98" rx="3.5" ry={generated?2.5:0.8} fill="#1a1208"/>
          {/* mouth — animated when speaking */}
          {generated && (
            <ellipse cx="100" cy="125"
              rx={6 + Math.abs(Math.sin(progress*40))*4}
              ry={1.5 + Math.abs(Math.sin(progress*40))*2}
              fill="#3a1a14"/>
          )}
          {/* generation scan line */}
          {!generated && (
            <line x1="0" y1={progress*600} x2="200" y2={progress*600} stroke="var(--thraxel-red)" strokeWidth="2" opacity="0.8"/>
          )}
          {/* polygon mesh on generation */}
          {!generated && (
            <g stroke="rgba(200,16,46,0.5)" strokeWidth="0.6" fill="none">
              <path d="M50 80 L100 40 L150 80 L130 130 L100 158 L70 130 Z"/>
              <line x1="100" y1="40" x2="100" y2="158"/>
              <line x1="50" y1="80" x2="150" y2="80"/>
              <line x1="70" y1="130" x2="130" y2="130"/>
            </g>
          )}
        </svg>
        <div style={{
          position:'absolute',bottom:8,left:8,right:8,
          padding:'5px 10px',background:'rgba(0,0,0,0.7)',border:'1px solid #2a2a2e',
          fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.18em',color: generated?'#3aff7a':'var(--thraxel-red)',
        }}>{generated ? '● LIVE · AVATAR_RANDY_01' : '○ GENERATING…'}</div>
        {/* status badge */}
        <div style={{
          position:'absolute',top:8,left:8,
          fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:8,letterSpacing:'0.18em',color:'#fff',
          padding:'3px 8px',background:'rgba(200,16,46,0.5)',
        }}>FOR YOUR BUSINESS</div>
      </div>

      {/* right side: controls + output */}
      <div style={{display:'flex',flexDirection:'column',gap:12,minWidth:0}}>
        <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:10,letterSpacing:'0.22em',color:'var(--thraxel-mid-grey)'}}>AVATAR FOR YOUR BUSINESS</div>
        <div style={{
          display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,
          opacity: showControls ? 1 : 0, transform:`translateY(${showControls?0:6}px)`, transition:'opacity 0.4s, transform 0.4s',
        }}>
          {[
            ['VOICE','Western PA · Warm'],
            ['TONE','Friendly · Direct'],
            ['CHANNEL','SMS · Email · Video'],
            ['LANGUAGE','EN · ES'],
          ].map(([l,v])=>(
            <div key={l} style={{padding:'8px 12px',background:'#0a0a0a',border:'1px solid #2a2a2e'}}>
              <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.16em',color:'var(--thraxel-mid-grey)'}}>{l}</div>
              <div style={{fontSize:11,color:'#fff',marginTop:2}}>{v}</div>
            </div>
          ))}
        </div>

        {/* output: video reply preview */}
        <div style={{
          marginTop:'auto',padding:'10px 14px',background:'#0a0a0a',border:'1px solid rgba(58,255,122,0.3)',
          opacity: showOutput?1:0,transform:`translateY(${showOutput?0:8}px)`,transition:'opacity 0.4s, transform 0.4s',
          display:'flex',alignItems:'center',gap:10,
        }}>
          <div style={{
            width:38,height:38,background:'#1a1a1e',display:'flex',alignItems:'center',justifyContent:'center',
            border:'1px solid #2a2a2e',
          }}>
            <svg viewBox="0 0 24 24" width="16" height="16" fill="#3aff7a"><polygon points="6,4 20,12 6,20"/></svg>
          </div>
          <div style={{flex:1}}>
            <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:9,letterSpacing:'0.18em',color:'#3aff7a'}}>VIDEO REPLY · GENERATED</div>
            <div style={{fontSize:11,color:'#fff',marginTop:2}}>"Hey Sarah — saw your inquiry…"</div>
          </div>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.16em',color:'var(--thraxel-mid-grey)'}}>0:24</div>
        </div>
      </div>
    </div>
  );
}

// ---------- SCENE 4: Booking ----------
function SceneBooking({ progress }){
  // Phase 0-0.3: calendar grid renders
  // Phase 0.3-0.6: AI suggests slot, confirms via SMS
  // Phase 0.6-1: booking confirmed; deposit captured

  const showCal = progress > 0.05;
  const showSuggested = progress > 0.32;
  const showSMS = progress > 0.5;
  const showConfirm = progress > 0.78;

  // 5-day x 4-row grid
  const days = ['MON','TUE','WED','THU','FRI'];
  const rows = ['9A','11A','1P','3P'];
  // mark booked vs available
  const grid = [
    ['B','A','B','A','B'],
    ['B','A','A','B','A'],
    ['A','S','B','A','A'],   // S = AI suggested slot at TUE 1P
    ['B','B','A','A','B'],
  ];

  return (
    <div style={{position:'absolute',inset:0,padding:'22px 28px',display:'grid',gridTemplateColumns:'1.4fr 1fr',gap:18}}>
      {/* calendar */}
      <div style={{display:'flex',flexDirection:'column',gap:8,opacity: showCal?1:0, transition:'opacity 0.4s'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:10,letterSpacing:'0.22em',color:'#fff'}}>WEEK OF APR 14</div>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.18em',color:'var(--thraxel-mid-grey)'}}>TECH · AJ</div>
        </div>
        <div style={{display:'grid',gridTemplateColumns:`50px repeat(${days.length},1fr)`,gap:4}}>
          <div/>
          {days.map(d=>(
            <div key={d} style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.18em',color:'var(--thraxel-mid-grey)',textAlign:'center',padding:'4px 0'}}>{d}</div>
          ))}
          {rows.map((r,ri)=>(
            <React.Fragment key={r}>
              <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:10,color:'#9a9a9f',textAlign:'right',paddingRight:8,paddingTop:8}}>{r}</div>
              {grid[ri].map((c,ci)=>{
                const isSuggested = c==='S';
                const isBooked = c==='B';
                const pulse = isSuggested && showSuggested;
                const becomesBooked = isSuggested && showConfirm;
                return (
                  <div key={ci} style={{
                    aspectRatio:'2/1',minHeight:30,
                    background: becomesBooked ? 'rgba(58,255,122,0.12)' : (isBooked ? '#161616' : (pulse?'rgba(200,16,46,0.18)':'#0a0a0a')),
                    border: becomesBooked ? '1px solid #3aff7a' : (pulse ? '2px solid var(--thraxel-red)' : '1px solid #1f1f23'),
                    display:'flex',alignItems:'center',justifyContent:'center',
                    fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.12em',
                    color: becomesBooked ? '#3aff7a' : (isBooked ? 'var(--thraxel-mid-grey)' : (pulse?'var(--thraxel-red)':'#3a3a3e')),
                    boxShadow: pulse ? '0 0 16px rgba(200,16,46,0.4)' : 'none',
                    transition:'all 0.3s',
                  }}>
                    {becomesBooked ? '✓ BOOKED' : (isBooked ? '·' : (pulse ? 'AI ↗' : ''))}
                  </div>
                );
              })}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* SMS conversation */}
      <div style={{display:'flex',flexDirection:'column',gap:8,minWidth:0}}>
        <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:10,letterSpacing:'0.22em',color:'#fff'}}>SMS · CARRIE J.</div>
        <div style={{display:'flex',flexDirection:'column',gap:6,flex:1}}>
          {[
            { who:'me',  text:'Tue Apr 15, 1–3 PM works for the walkthrough?', t:0.55 },
            { who:'them',text:'Yes! Perfect.', t:0.66 },
            { who:'me',  text:'Booked. $150 deposit holds the slot.', t:0.74 },
            { who:'them',text:'Sending now 👍', t:0.85 },
          ].map((m,i)=>{
            const visible = progress > m.t;
            return (
              <div key={i} style={{
                alignSelf: m.who==='me'?'flex-end':'flex-start',
                maxWidth:'85%',
                padding:'7px 12px',
                background: m.who==='me'?'rgba(200,16,46,0.18)':'#0a0a0a',
                border:`1px solid ${m.who==='me'?'rgba(200,16,46,0.4)':'#2a2a2e'}`,
                fontSize:11,color:'#fff',lineHeight:1.35,
                opacity: visible?1:0, transform: `translateY(${visible?0:6}px)`,
                transition:'opacity 0.3s, transform 0.3s',
              }}>{m.text}</div>
            );
          })}
        </div>
        {/* deposit captured */}
        <div style={{
          padding:'9px 13px',background:'#0a0a0a',border:'1px solid rgba(58,255,122,0.4)',
          display:'flex',alignItems:'center',justifyContent:'space-between',
          opacity: showConfirm?1:0,transform:`translateY(${showConfirm?0:8}px)`,transition:'opacity 0.4s, transform 0.4s',
        }}>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:9,letterSpacing:'0.18em',color:'#3aff7a'}}>● DEPOSIT CAPTURED</div>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:900,fontSize:13,color:'#fff'}}>$150.00</div>
        </div>
      </div>
    </div>
  );
}

// ---------- SCENE 5: God's-eye Lead Map ----------
function SceneLeadMap({ progress }){
  // Phase 0-0.25: map fades in with HQ pin pulsing
  // Phase 0.25-0.7: red dots pop into existence across PA/OH/WV/MD/NY (leads streaming in)
  // Phase 0.5-1: live events panel populates one at a time on the right
  // Phase 0.8-1: stats counters tick up

  // Pre-seeded lead positions across the abstract map (percent coords inside the SVG box)
  const leads = useMemoAI(()=> {
    const seeds = [];
    // Cluster heavy in PA (center)
    for (let i=0;i<14;i++) seeds.push({ x: 42 + Math.random()*28, y: 30 + Math.random()*22, t: 0.25 + Math.random()*0.4 });
    // Ohio left
    for (let i=0;i<5;i++) seeds.push({ x: 18 + Math.random()*18, y: 32 + Math.random()*22, t: 0.30 + Math.random()*0.4 });
    // NY top
    for (let i=0;i<5;i++) seeds.push({ x: 28 + Math.random()*46, y: 14 + Math.random()*12, t: 0.35 + Math.random()*0.35 });
    // WV
    for (let i=0;i<4;i++) seeds.push({ x: 36 + Math.random()*28, y: 60 + Math.random()*16, t: 0.40 + Math.random()*0.3 });
    // MD
    for (let i=0;i<3;i++) seeds.push({ x: 60 + Math.random()*22, y: 56 + Math.random()*12, t: 0.45 + Math.random()*0.3 });
    return seeds;
  },[]);

  const events = [
    { label:'New Lead',     value:'724-555-0188 · Cranberry Twp', color:'#3aff7a',     t:0.40 },
    { label:'Quote Sent',   value:'PDF · 4-zone · $4,820',         color:'#3aff7a',     t:0.50 },
    { label:'Booked',       value:'Tue 4/14 · 9-11am · Tech: AJ',  color:'#FFB347',     t:0.60 },
    { label:'Review Filed', value:'★★★★★ · Google · auto-replied', color:'#3aff7a',     t:0.70 },
    { label:'Scrape Match', value:'12 new permits · Butler Co.',   color:'#1a4dcf',     t:0.80 },
  ];

  const statT = (progress - 0.78) / 0.22;
  const tickT = Math.max(0, Math.min(1, statT));
  const stats = [
    { l:'LEADS / 30D',     v: Math.floor(1847 * tickT).toLocaleString() },
    { l:'PERMITS WATCHED', v: Math.floor(12402 * tickT).toLocaleString() },
    { l:'CLOSE RATE',      v: `${Math.floor(38 * tickT)}%` },
    { l:'REGIONS',         v: Math.floor(5 * tickT) },
  ];

  return (
    <div style={{position:'absolute',inset:0,padding:'12px 18px',display:'flex',flexDirection:'column',gap:10}}>
      {/* top header — like the dashboard chrome */}
      <div style={{display:'flex',alignItems:'center',gap:12,opacity: progress>0.05?1:0,transition:'opacity 0.3s'}}>
        <span style={{width:8,height:8,borderRadius:'50%',background:'#3aff7a',boxShadow:'0 0 8px #3aff7a'}}/>
        <span style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:10,letterSpacing:'0.22em',color:'#fff'}}>OPS · LIVE</span>
        <span style={{fontFamily:'Orbitron,sans-serif',fontWeight:600,fontSize:9,letterSpacing:'0.18em',color:'var(--thraxel-mid-grey)'}}>WPA · OHIO · WV · MD · NY</span>
      </div>

      {/* main row: map + events */}
      <div style={{flex:1,display:'grid',gridTemplateColumns:'1fr 220px',gap:12,minHeight:0}}>
        {/* map */}
        <div style={{position:'relative',background:'linear-gradient(180deg,#040608 0%,#020305 100%)',border:'1px solid #1a1a22',overflow:'hidden'}}>
          <svg viewBox="0 0 100 80" preserveAspectRatio="none" style={{position:'absolute',inset:0,width:'100%',height:'100%'}}>
            <defs>
              <radialGradient id="lm-glow" cx="50%" cy="50%" r="55%">
                <stop offset="0%" stopColor="rgba(200,16,46,0.18)"/>
                <stop offset="60%" stopColor="rgba(200,16,46,0.04)"/>
                <stop offset="100%" stopColor="transparent"/>
              </radialGradient>
            </defs>
            <rect width="100" height="80" fill="url(#lm-glow)"/>
            {/* state polys */}
            <path d="M 8,28 L 32,26 L 36,46 L 30,58 L 10,56 Z"  fill="rgba(255,255,255,0.025)" stroke="rgba(255,255,255,0.18)" strokeWidth="0.18"/>
            <path d="M 32,26 L 70,24 L 74,52 L 36,46 Z"          fill="rgba(200,16,46,0.06)"   stroke="rgba(200,16,46,0.55)"   strokeWidth="0.22"/>
            <path d="M 70,24 L 92,30 L 90,56 L 74,52 Z"          fill="rgba(255,255,255,0.025)" stroke="rgba(255,255,255,0.18)" strokeWidth="0.18"/>
            <path d="M 30,58 L 36,46 L 74,52 L 70,68 L 34,70 Z"  fill="rgba(255,255,255,0.025)" stroke="rgba(255,255,255,0.18)" strokeWidth="0.18"/>
            <path d="M 34,70 L 70,68 L 64,80 L 40,80 Z"          fill="rgba(255,255,255,0.025)" stroke="rgba(255,255,255,0.18)" strokeWidth="0.18"/>
            {/* HQ */}
            <circle cx="50" cy="40" r="1.8" fill="var(--thraxel-red)" stroke="#fff" strokeWidth="0.3"/>
            <circle cx="50" cy="40" r={2 + (progress%1)*6} fill="none" stroke="rgba(200,16,46,0.6)" strokeWidth="0.3" opacity={1-(progress%1)}/>
            <text x="52.5" y="38.5" fill="#fff" style={{font:'700 1.8px Orbitron, sans-serif', letterSpacing:'0.05em'}}>HQ · 16037</text>
          </svg>

          {/* lead dots — pop in based on their .t threshold */}
          {leads.map((d,idx)=>{
            const visible = progress > d.t;
            const justPopped = progress > d.t && progress < d.t + 0.05;
            return (
              <div key={idx} style={{
                position:'absolute',left:`${d.x}%`,top:`${d.y}%`,transform:'translate(-50%,-50%)',
                width: justPopped ? 14 : 7, height: justPopped ? 14 : 7,
                borderRadius:'50%',
                background:'var(--thraxel-red)',
                boxShadow: justPopped
                  ? '0 0 18px var(--thraxel-red), 0 0 32px rgba(200,16,46,0.7)'
                  : '0 0 6px rgba(200,16,46,0.7)',
                opacity: visible ? (justPopped?1:0.85) : 0,
                transition:'width 0.3s, height 0.3s, opacity 0.3s',
                pointerEvents:'none',
              }}/>
            );
          })}

          {/* stats strip — bottom-left */}
          <div style={{
            position:'absolute',left:10,bottom:10,
            padding:'9px 14px',background:'rgba(0,0,0,0.85)',backdropFilter:'blur(6px)',
            border:'1px solid #1a1a22',display:'flex',gap:18,
            opacity: progress>0.7?1:0, transform:`translateY(${progress>0.7?0:8}px)`,transition:'opacity 0.4s, transform 0.4s',
          }}>
            {stats.map(s=>(
              <div key={s.l}>
                <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.16em',color:'var(--thraxel-mid-grey)'}}>{s.l}</div>
                <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:900,fontSize:14,color:'#fff',marginTop:2}}>{s.v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* events feed */}
        <div style={{
          background:'rgba(0,0,0,0.7)',border:'1px solid #1a1a22',padding:'10px 12px',
          display:'flex',flexDirection:'column',gap:8,minWidth:0,
        }}>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:9,letterSpacing:'0.2em',color:'#fff',marginBottom:2}}>● LIVE EVENTS</div>
          {events.map((e,i)=>{
            const visible = progress > e.t;
            return (
              <div key={i} style={{
                borderLeft:`2px solid ${e.color}`,paddingLeft:8,
                opacity: visible ? 1 : 0, transform:`translateX(${visible?0:-6}px)`,
                transition:'opacity 0.3s, transform 0.3s',
              }}>
                <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.16em',color:e.color}}>{e.label}</div>
                <div style={{fontSize:9.5,color:'var(--thraxel-light-grey)',marginTop:1,lineHeight:1.35}}>{e.value}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------- Main walkthrough player ----------
function AIWalkthrough(){
  const { i, progress, paused, setPaused, goto } = useSceneCycle(SCENES);
  const SceneEl = [SceneReplace, SceneVoice, SceneAvatar, SceneBooking, SceneLeadMap][i];

  return (
    <div style={{
      position:'relative',aspectRatio:'16/10',
      background:'linear-gradient(180deg,#070708 0%,#020203 100%)',
      border:'1px solid #2a2a2e',overflow:'hidden',
      boxShadow:'0 30px 80px rgba(0,0,0,0.5), inset 0 0 0 1px rgba(255,255,255,0.02)',
    }}
      onMouseEnter={()=>setPaused(true)}
      onMouseLeave={()=>setPaused(false)}
    >
      {/* film-like vignette */}
      <div style={{position:'absolute',inset:0,background:'radial-gradient(ellipse 80% 70% at 50% 50%, transparent 50%, rgba(0,0,0,0.7))',pointerEvents:'none',zIndex:5}}/>

      {/* top status bar */}
      <div style={{
        position:'absolute',top:0,left:0,right:0,zIndex:6,
        display:'flex',justifyContent:'space-between',alignItems:'center',
        padding:'12px 18px',background:'linear-gradient(180deg,rgba(0,0,0,0.7),transparent)',
      }}>
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          <div style={{width:8,height:8,borderRadius:'50%',background:'var(--thraxel-red)',boxShadow:'0 0 8px var(--thraxel-red)'}}/>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:800,fontSize:10,letterSpacing:'0.22em',color:'#fff'}}>● THRAXEL AI HUB · WALKTHROUGH</div>
        </div>
        <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.2em',color:'var(--thraxel-mid-grey)'}}>
          {String(i+1).padStart(2,'0')} / {String(SCENES.length).padStart(2,'0')}
        </div>
      </div>

      {/* the active scene */}
      <div style={{position:'absolute',inset:0,top:42,bottom:78}} key={i}>
        <SceneEl progress={progress}/>
      </div>

      {/* bottom: title + chapters + progress */}
      <div style={{
        position:'absolute',left:0,right:0,bottom:0,zIndex:6,
        padding:'18px 22px',background:'linear-gradient(0deg,rgba(0,0,0,0.85),transparent)',
      }}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:12}}>
          <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:900,fontSize:'clamp(16px,2vw,24px)',color:'#fff',letterSpacing:'0.04em'}}>
            {SCENES[i].title}
          </div>
          {paused && (
            <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.2em',color:'#FFB347'}}>❚❚ PAUSED</div>
          )}
        </div>
        {/* chapter progress segments */}
        <div style={{display:'flex',gap:6}}>
          {SCENES.map((s,idx)=>{
            const filled = idx < i ? 1 : (idx === i ? progress : 0);
            const isActive = idx === i;
            return (
              <button key={s.id}
                onClick={()=>goto(idx)}
                style={{
                  flex:1,position:'relative',height:24,padding:0,
                  background:'transparent',border:'none',cursor:'pointer',
                  display:'flex',flexDirection:'column',gap:6,
                }}>
                <div style={{
                  height:2,background:'rgba(255,255,255,0.15)',position:'relative',overflow:'hidden',
                }}>
                  <div style={{
                    position:'absolute',left:0,top:0,bottom:0,
                    width:`${filled*100}%`,
                    background: isActive ? 'var(--thraxel-red)' : '#fff',
                    boxShadow: isActive ? '0 0 8px rgba(200,16,46,0.5)' : 'none',
                  }}/>
                </div>
                <div style={{
                  fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.16em',
                  color: isActive ? '#fff' : 'var(--thraxel-mid-grey)',textAlign:'left',
                }}>{String(idx+1).padStart(2,'0')} · {s.id.toUpperCase()}</div>
              </button>
            );
          })}
        </div>
      </div>

      {/* corner mini-meta — gives a "captured live" feel */}
      <div style={{
        position:'absolute',top:50,right:14,zIndex:5,
        fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:8,letterSpacing:'0.18em',color:'rgba(255,255,255,0.4)',
        padding:'4px 8px',background:'rgba(0,0,0,0.5)',border:'1px solid rgba(255,255,255,0.06)',
      }}>REC · 1080p</div>
    </div>
  );
}

Object.assign(window, { AIWalkthrough });
