// build-scenes.jsx — Title, Spec, Graph build, Self-test, Done (English, Segoe UI).
const { T, UI_FONT, DISPLAY_FONT, MONO, Logo, Cursor, Caret, Btn, Chip, Card, GNode, Edge, CheckRow, ease, clamp01, seg } = window;
const { Sprite, useSprite, Easing, interpolate } = window;

const appear = (lt, t0, d=0.4)=> clamp01((lt - t0)/d);

// ── 1. TITLE ──────────────────────────────────────────────────────────────
function TitleScene({ start, end }) {
  return <Sprite start={start} end={end}>{({ localTime: lt, duration })=>{
    const o = appear(lt,0,0.6) * (1 - seg(lt, duration-0.5, duration, Easing.easeInCubic));
    const a1 = appear(lt,0.3,0.7), a2 = appear(lt,0.9,0.7), a3 = appear(lt,1.5,0.7), a4 = appear(lt,2.2,0.7);
    return <div style={{ position:'absolute', inset:0, opacity:o }}>
      <div style={{ position:'absolute', left:120, top:296 }}>
        <div style={{ opacity:a1, transform:`translateY(${(1-a1)*18}px)` }}><Logo h={48} /></div>
        <div style={{ marginTop:34, opacity:a2, transform:`translateY(${(1-a2)*22}px)`,
          fontFamily:DISPLAY_FONT, fontSize:88, fontWeight:700, color:T.text, letterSpacing:'-.03em', lineHeight:1.02 }}>
          A voice agent<br/><span style={{ color:T.accent }}>in four steps</span></div>
        <div style={{ marginTop:30, opacity:a3, transform:`translateY(${(1-a3)*22}px)`,
          fontFamily:UI_FONT, fontSize:26, color:T.muted, maxWidth:900, lineHeight:1.5 }}>
          Describe your business in plain words — HANC Studio picks a role, builds
          the workflow graph, wires up calendar and SMS, and tests it by calling.</div>
        <div style={{ marginTop:42, opacity:a4, display:'flex', gap:12, alignItems:'center' }}>
          {['Key','Number','Business','Details'].map((s,i)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:12 }}>
              <span style={{ height:40, padding:'0 18px', borderRadius:10, background:T.surface2,
                border:`1px solid ${T.border}`, color:T.text, fontSize:16, display:'inline-flex', alignItems:'center', gap:9 }}>
                <span style={{ color:T.accent, fontWeight:700, fontFamily:MONO }}>{i+1}</span>{s}</span>
              {i<3 && <span style={{ color:T.faint, fontSize:20 }}>→</span>}
            </div>
          ))}
        </div>
      </div>
    </div>;
  }}</Sprite>;
}

// ── 2. SPEC ────────────────────────────────────────────────────────────────
const SPEC_ROWS = [
  ['Goal','book the caller and answer questions about services'],
  ['Role','Appointment secretary · appointment_booking'],
  ['Collect','name · phone · service · date & time'],
  ['Branch','acute pain / asks for a human → transfer to administrator'],
  ['Forbidden','no diagnosis, no exact price'],
  ['Endpoints','calendar.book · sms.send'],
];
function Pill({ children, done, o }) {
  return <div style={{ display:'inline-flex', alignItems:'center', gap:10, height:42, padding:'0 16px',
    borderRadius:21, background:T.surface2, border:`1px solid ${T.border}`, opacity:o,
    transform:`translateY(${(1-o)*10}px)`, fontSize:15, color:T.text, fontFamily:UI_FONT }}>
    {done
      ? <svg width="16" height="16" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5" fill="none" stroke={T.ok} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
      : <span style={{ width:15, height:15, borderRadius:'50%', border:'2px solid rgba(255,255,255,.35)',
          borderTopColor:T.accent, display:'inline-block', animation:'spin .8s linear infinite' }} />}
    {children}</div>;
}
function SpecScene({ start, end }) {
  return <Sprite start={start} end={end}>{({ localTime: lt, duration })=>{
    const o = appear(lt,0,0.5)*(1-seg(lt,duration-0.5,duration,Easing.easeInCubic));
    const card = appear(lt,2.0,0.6);
    const typing = lt>7.0 && lt<8.7;
    const userMsg = lt>8.9;
    const sent = lt>9.3;
    return <div style={{ position:'absolute', inset:0, opacity:o }}>
      <div style={{ position:'absolute', left:120, top:64, display:'flex', alignItems:'center', gap:16 }}>
        <Logo h={30} />
        <span style={{ color:T.faint }}>·</span>
        <span style={{ fontSize:20, fontWeight:600, color:T.text }}>Architect builds the agent</span>
      </div>
      <div style={{ position:'absolute', left:120, top:128, display:'flex', gap:12 }}>
        <Pill done o={appear(lt,0.3,0.5)}>Reading the description</Pill>
        <Pill done o={appear(lt,1.1,0.5)}>Role chosen: Appointment booking</Pill>
        <Pill done={lt>2.0} o={appear(lt,1.7,0.5)}>Preparing the spec</Pill>
      </div>
      <div style={{ position:'absolute', left:120, top:196, width:1180, opacity:card,
        transform:`translateY(${(1-card)*24}px) scale(${ease(.98,1,card)})`, transformOrigin:'top left' }}>
        <Card x={0} y={0} w={1180} h={420} style={{ position:'relative', boxShadow:'0 24px 70px rgba(0,0,0,.45)' }}>
          <div style={{ padding:'22px 28px', borderBottom:`1px solid ${T.border}`, display:'flex', alignItems:'center', gap:12 }}>
            <span style={{ width:32, height:30, borderRadius:8, background:'rgba(255,106,26,.14)',
              border:`1px solid ${T.accent}`, display:'flex', alignItems:'center', justifyContent:'center',
              color:T.accent2, fontWeight:700, fontSize:13 }}>SPEC</span>
            <span style={{ fontSize:19, fontWeight:600, color:T.text }}>Spec — confirm before building</span>
          </div>
          <div style={{ padding:'18px 28px', display:'flex', flexDirection:'column', gap:13 }}>
            {SPEC_ROWS.map(([k,v],i)=>{
              const ro = appear(lt, 2.4 + i*0.32, 0.4);
              return <div key={i} style={{ display:'flex', gap:20, opacity:ro, transform:`translateX(${(1-ro)*14}px)` }}>
                <div style={{ width:120, flex:'none', fontSize:14, color:T.muted, fontFamily:MONO, paddingTop:1 }}>{k}</div>
                <div style={{ fontSize:16, color:T.text, lineHeight:1.4 }}>{v}</div>
              </div>;
            })}
          </div>
          <div style={{ position:'absolute', left:28, right:28, bottom:20, opacity:appear(lt,4.4,0.6),
            display:'flex', alignItems:'center', gap:10, height:42, padding:'0 16px', borderRadius:10,
            background:'rgba(255,178,71,.10)', border:'1px solid rgba(255,178,71,.4)' }}>
            <span style={{ fontSize:18 }}>⚠</span>
            <span style={{ fontSize:14.5, color:'#ffce8a' }}>Nothing is created until you confirm.</span>
          </div>
        </Card>
      </div>
      {userMsg && <div style={{ position:'absolute', right:120, top:640, display:'flex', justifyContent:'flex-end',
        opacity:appear(lt,8.9,0.4), transform:`translateY(${(1-appear(lt,8.9,0.4))*10}px)` }}>
        <div style={{ background:T.user, color:'#fff', padding:'13px 20px', borderRadius:'14px 14px 4px 14px',
          fontSize:17, fontWeight:500 }}>yes, build it</div>
      </div>}
      <div style={{ position:'absolute', left:120, right:120, bottom:54, display:'flex', gap:12 }}>
        <div style={{ flex:1, minHeight:54, borderRadius:10, background:T.surface2,
          border:`1px solid ${typing?T.accent:T.border}`, display:'flex', alignItems:'center',
          padding:'0 16px', fontSize:16, color:T.text }}>
          {sent ? <span style={{ color:T.faint }}>Describe the agent or reply to the architect…</span>
                : <>{lt>=7.0 ? 'yes, build it' : <span style={{color:T.faint}}>Describe the agent or reply to the architect…</span>}{typing && <Caret/>}</>}
        </div>
        <Btn primary w={130} big>Send</Btn>
      </div>
      <Cursor frames={[{t:0,x:1340,y:520},{t:6.6,x:680,y:820},{t:7.0,x:680,y:820},
        {t:8.6,x:1245,y:820},{t:9.0,x:1245,y:820},{t:11,x:1245,y:820}]} clicks={[8.85]} />
    </div>;
  }}</Sprite>;
}

// ── 3. GRAPH BUILD ─────────────────────────────────────────────────────────
const NODES = [
  { id:'n1', cx:900, cy:150, w:260, h:54, label:'Incoming call', kind:'term', t:0.2 },
  { id:'n2', cx:900, cy:232, w:320, h:54, label:'Greeting “White Tooth”', kind:'step', t:0.9 },
  { id:'n3', cx:900, cy:320, w:420, h:62, label:'Acute pain or asks for a human?', kind:'decide', t:1.6 },
  { id:'nL', cx:470, cy:432, w:320, h:54, label:'Transfer to administrator', kind:'step', t:3.0 },
  { id:'n4', cx:900, cy:432, w:260, h:50, label:'Ask name', kind:'step', t:2.5 },
  { id:'n5', cx:900, cy:510, w:280, h:50, label:'Ask service', kind:'step', t:3.4 },
  { id:'n6', cx:900, cy:588, w:320, h:50, label:'Ask date & time', kind:'step', t:3.9 },
  { id:'n7', cx:900, cy:666, w:320, h:50, label:'Book in calendar', kind:'step', t:4.4 },
  { id:'n8', cx:900, cy:744, w:320, h:50, label:'SMS confirmation', kind:'step', t:4.9 },
  { id:'n9', cx:900, cy:824, w:280, h:54, label:'End call', kind:'term', t:5.4 },
];
const NID = Object.fromEntries(NODES.map(n=>[n.id,n]));
const EDGES = [
  { a:'n1', b:'n2', t:0.7 }, { a:'n2', b:'n3', t:1.4 },
  { from:[900,351], to:[900,407], label:'no ↓', t:2.3 },
  { from:[760,338], to:[560,432], label:'yes →', t:2.9 },
  { a:'n4', b:'n5', t:3.3 }, { a:'n5', b:'n6', t:3.8 }, { a:'n6', b:'n7', t:4.3 },
  { a:'n7', b:'n8', t:4.8 }, { a:'n8', b:'n9', t:5.3 },
  { from:[470,459], to:[762,820], label:'', t:5.8 },
];
function GraphScene({ start, end }) {
  return <Sprite start={start} end={end}>{({ localTime: lt, duration })=>{
    const o = appear(lt,0,0.5)*(1-seg(lt,duration-0.5,duration,Easing.easeInCubic));
    const toast = appear(lt,6.4,0.5);
    const ev = (e)=>{
      const A = e.a&&NID[e.a], B = e.b&&NID[e.b];
      const from = e.from || [A.cx, A.cy + A.h/2];
      const to = e.to || [B.cx, B.cy - B.h/2];
      return { from, to };
    };
    return <div style={{ position:'absolute', inset:0, opacity:o }}>
      <div style={{ position:'absolute', left:120, top:54, display:'flex', alignItems:'center', gap:16 }}>
        <span style={{ fontSize:20, fontWeight:600, color:T.text }}>Building the workflow graph</span>
        <span style={{ display:'inline-flex', alignItems:'center', gap:8, height:32, padding:'0 13px', borderRadius:8,
          background:'rgba(78,208,138,.12)', border:'1px solid rgba(78,208,138,.45)', color:T.ok, fontSize:14,
          opacity:appear(lt,0.4,0.5), fontFamily:MONO }}>
          <svg width="14" height="14" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5" fill="none" stroke={T.ok} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
          validate_graph — no errors</span>
      </div>
      {EDGES.map((e,i)=>{ const {from,to}=ev(e); return <Edge key={'e'+i} x1={from[0]} y1={from[1]} x2={to[0]} y2={to[1]}
        appear={appear(lt,e.t,0.4)} label={e.label} />; })}
      {NODES.map(n=><GNode key={n.id} x={n.cx-n.w/2} y={n.cy-n.h/2} w={n.w} h={n.h} label={n.label}
        kind={n.kind} appear={appear(lt,n.t,0.4)} />)}
      <div style={{ position:'absolute', right:120, top:60, opacity:toast, transform:`translateY(${(1-toast)*-10}px)` }}>
        <div style={{ display:'flex', alignItems:'center', gap:12, height:48, padding:'0 20px', borderRadius:12,
          background:T.surface, border:`1px solid ${T.ok}`, boxShadow:'0 12px 40px rgba(0,0,0,.4)' }}>
          <span style={{ width:26, height:26, borderRadius:'50%', background:T.ok, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <svg width="15" height="15" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5" fill="none" stroke="#0d0f14" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"/></svg></span>
          <span style={{ fontSize:16, fontWeight:600, color:T.text, fontFamily:MONO }}>create_workflow — graph linked to agent</span>
        </div>
      </div>
    </div>;
  }}</Sprite>;
}

// ── 4. SELF-TEST (check-based, no personas) ─────────────────────────────────
const CHECKS = [
  'Collects name, phone and appointment time',
  'Transfers to a human on acute pain',
  'Never quotes an exact price or gives a diagnosis',
  'Ends the call cleanly after confirming',
];
function TestScene({ start, end }) {
  return <Sprite start={start} end={end}>{({ localTime: lt, duration })=>{
    const o = appear(lt,0,0.5)*(1-seg(lt,duration-0.5,duration,Easing.easeInCubic));
    const pass = lt>5.4;
    return <div style={{ position:'absolute', inset:0, opacity:o }}>
      <div style={{ position:'absolute', left:120, top:96 }}>
        <div style={{ fontSize:36, fontWeight:700, color:T.text, letterSpacing:'-.02em', fontFamily:DISPLAY_FONT }}>
          Self-test</div>
        <div style={{ fontSize:19, color:T.muted, marginTop:12, maxWidth:760 }}>
          The architect calls the agent and verifies every requirement from the spec.</div>
      </div>
      <div style={{ position:'absolute', left:120, top:240, width:880, display:'flex', flexDirection:'column', gap:14 }}>
        {CHECKS.map((c,i)=><div key={i} style={{ opacity:appear(lt,0.6+i*0.25,0.4),
          transform:`translateY(${(1-appear(lt,0.6+i*0.25,0.4))*12}px)` }}>
          <CheckRow text={c} done={lt>2.0+i*0.7} /></div>)}
      </div>
      <div style={{ position:'absolute', right:150, top:240, width:300, opacity:appear(lt,5.4,0.5),
        transform:`scale(${ease(.92,1,appear(lt,5.4,0.5))})`, transformOrigin:'center' }}>
        <Card x={0} y={0} w={300} h={300} style={{ position:'relative', display:'flex', flexDirection:'column',
          alignItems:'center', justifyContent:'center', gap:14,
          background:pass?'rgba(78,208,138,.08)':T.surface, borderColor:pass?T.ok:T.border }}>
          <div style={{ width:96, height:96, borderRadius:'50%', background:T.ok, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <svg width="52" height="52" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5" fill="none" stroke="#0d0f14" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg></div>
          <div style={{ fontSize:38, fontWeight:800, color:T.ok, fontFamily:DISPLAY_FONT }}>PASS</div>
          <div style={{ fontSize:16, color:T.muted }}>4 / 4 checks</div>
        </Card>
      </div>
    </div>;
  }}</Sprite>;
}

// ── 5. DONE ─────────────────────────────────────────────────────────────────
function DoneScene({ start, end }) {
  return <Sprite start={start} end={end}>{({ localTime: lt, duration })=>{
    const o = appear(lt,0,0.6);
    const ring = appear(lt,0.2,0.6);
    return <div style={{ position:'absolute', inset:0, opacity:o, display:'flex', flexDirection:'column',
      alignItems:'center', justifyContent:'center' }}>
      <div style={{ width:120, height:120, borderRadius:'50%', background:T.ok, display:'flex', alignItems:'center',
        justifyContent:'center', transform:`scale(${ease(.4,1,Easing.easeOutBack(clamp01(ring)))})`,
        boxShadow:'0 0 60px rgba(78,208,138,.4)' }}>
        <svg width="64" height="64" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5" fill="none" stroke="#0d0f14" strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round"/></svg></div>
      <div style={{ marginTop:34, fontFamily:DISPLAY_FONT, fontSize:62, fontWeight:700, color:T.text,
        letterSpacing:'-.02em', opacity:appear(lt,0.7,0.6) }}>Your agent is taking calls</div>
      <div style={{ marginTop:16, fontSize:23, color:T.muted, maxWidth:1000, textAlign:'center', lineHeight:1.5,
        opacity:appear(lt,1.1,0.6) }}>
        The workflow is built, tested and linked to your agent in your HANC account.
        Call the number to try it — or open Advanced mode to fine-tune.</div>
      <div style={{ marginTop:40, display:'flex', gap:14, opacity:appear(lt,1.6,0.6) }}>
        {['Paste key','Choose number','Describe business','Create agent'].map((s,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:14 }}>
            <span style={{ height:42, padding:'0 18px', borderRadius:10, background:T.surface2,
              border:`1px solid ${T.border}`, color:T.text, fontSize:16, display:'inline-flex', alignItems:'center', gap:10 }}>
              <span style={{ color:T.accent, fontWeight:700, fontFamily:MONO }}>{i+1}</span>{s}</span>
            {i<3 && <span style={{ color:T.faint, fontSize:20 }}>→</span>}
          </div>
        ))}
      </div>
      <div style={{ marginTop:54, opacity:appear(lt,2.2,0.6) }}><Logo h={36} /></div>
    </div>;
  }}</Sprite>;
}

Object.assign(window, { TitleScene, SpecScene, GraphScene, TestScene, DoneScene });
