/* AI Edge — interactive demos. Requires React, window.AE, I, useInView, Reveal. */
(function(){
const { useState, useEffect, useRef } = React;
const AE = window.AE, I = window.I, useInView = window.useInView, Reveal = window.Reveal;
const motionOff = ()=> document.documentElement.dataset.motion==="off";

/* ---------- Video centerpiece ---------- */
function VideoSection(){
  const [playing,setPlaying]=useState(false);
  const [poster,setPoster]=useState(null);
  const vref=useRef(null), frameRef=useRef(null);
  useEffect(()=>{
    const v=vref.current; if(!v) return; let done=false, canceled=false;
    const cap=()=>{ if(done)return; try{
      const w=v.videoWidth,h=v.videoHeight; if(!w) return;
      const c=document.createElement("canvas"); c.width=w; c.height=h;
      c.getContext("2d").drawImage(v,0,0,w,h);
      if(!canceled){ setPoster(c.toDataURL("image/jpeg",0.72)); done=true; }
    }catch(e){} };
    const onLoaded=()=>{ try{ v.currentTime=Math.min(1.4,(v.duration||4)*0.08); }catch(e){ cap(); } };
    const onSeeked=()=>cap();
    v.addEventListener("loadeddata",onLoaded); v.addEventListener("seeked",onSeeked);
    return ()=>{ canceled=true; v.removeEventListener("loadeddata",onLoaded); v.removeEventListener("seeked",onSeeked); };
  },[]);
  const play=()=>{ const v=vref.current; if(v){ try{ v.currentTime=0; v.play(); }catch(e){} setPlaying(true); } };
  const tilt=(e)=>{ if(document.documentElement.dataset.motion==="off")return; const el=frameRef.current; if(!el)return;
    const r=el.getBoundingClientRect(); const px=(e.clientX-r.left)/r.width-0.5, py=(e.clientY-r.top)/r.height-0.5;
    el.style.transform=`perspective(1800px) rotateX(${(-py*1.3).toFixed(2)}deg) rotateY(${(px*1.3).toFixed(2)}deg)`; };
  const untilt=()=>{ const el=frameRef.current; if(el) el.style.transform="perspective(1500px) rotateX(0deg) rotateY(0deg)"; };
  return (
    <section className="section-pad" id="video">
      <div className="wrap">
        <Reveal className="section-head" style={{textAlign:"center",margin:"0 auto 32px"}}>
          <div className="eyebrow" style={{justifyContent:"center"}}>{AE.ui.vEyebrow}</div>
          <h2>{AE.ui.vTitle}</h2>
          <p style={{margin:"16px auto 0"}}>{AE.ui.vLead}</p>
        </Reveal>
        <Reveal className="video-wrap" delay={100}>
          <div className="video-frame" ref={frameRef} onMouseMove={tilt} onMouseLeave={untilt}>
            <div className="video-glow"></div>
            <div className="video-bar">
              <div className="tl"><i></i><i></i><i></i></div>
              <div className="addr mono">{AE.ui.vAddr}</div>
            </div>
            <div className="video-stage">
              <video ref={vref} src={AE.video} controls={playing} preload="metadata" playsInline></video>
              {!playing && (
                <button className="video-play" onClick={play} aria-label="play"
                  style={poster?{ backgroundImage:`linear-gradient(color-mix(in oklab,var(--bg) 30%,transparent),color-mix(in oklab,var(--bg) 55%,transparent)), url(${poster})`, backgroundSize:"cover", backgroundPosition:"center" }:null}>
                  <span className="vp-btn"><I.play/></span>
                </button>
              )}
            </div>
            <div className="video-foot">
              {AE.ui.vcaps.map((c,i)=>(<React.Fragment key={i}>{i>0 && <span className="sep">·</span>}<span>{c}</span></React.Fragment>))}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- helpers ---------- */
function Parts({ parts }){
  return <>{parts.map((p,i)=>{
    if(p.cite) return <span key={i} className="cite">{p.cite}</span>;
    if(p.b) return <b key={i}>{p.b}</b>;
    return <span key={i}>{p.t}</span>;
  })}</>;
}

/* ---------- Doc QA demo (recreated product side panel) ---------- */
function DocQA(){
  const [mode,setMode]=useState("success");   // success | fallback
  const [run,setRun]=useState(0);
  const [ref,seen]=useInView({ threshold:0.35 });
  const [phase,setPhase]=useState(0);          // 0..5
  const started=useRef(false);

  // start when first in view
  useEffect(()=>{ if(seen && !started.current){ started.current=true; setRun(r=>r+1); } },[seen]);

  // run the sequence on mode change / replay
  useEffect(()=>{
    if(run===0) return;
    if(motionOff()){ setPhase(5); return; }
    setPhase(0);
    const ts=[];
    ts.push(setTimeout(()=>setPhase(1),120));
    ts.push(setTimeout(()=>setPhase(2),650));   // tool loading
    ts.push(setTimeout(()=>setPhase(3),1500));  // tool done
    ts.push(setTimeout(()=>setPhase(4),1750));  // answer streams
    ts.push(setTimeout(()=>setPhase(5),2300));  // sources / warn
    return ()=>ts.forEach(clearTimeout);
  },[run,mode]);

  const d = AE.qa[mode];
  const replay=()=>setRun(r=>r+1);
  const pick=(m)=>{ setMode(m); setRun(r=>r+1); };

  const answerBlocks = mode==="success" ? AE.qa.success.answer : [];

  return (
    <section className="section-pad" id="demo">
      <div className="wrap">
        <Reveal className="section-head">
          <div className="eyebrow">{AE.ui.qaEyebrow}</div>
          <h2>{AE.ui.qaTitle}</h2>
          <p>{AE.ui.qaLead}</p>
        </Reveal>

        <div className="demo-grid" ref={ref}>
          {/* left: controls */}
          <div className="demo-side">
            <div className="tabs">
              <button className={`tab ${mode==="success"?"on":""}`} onClick={()=>pick("success")}>
                <span className="tg">J1</span>{AE.ui.tabSuccess}</button>
              <button className={`tab ${mode==="fallback"?"on":""}`} onClick={()=>pick("fallback")}>
                <span className="tg">J2</span>{AE.ui.tabFallback}</button>
            </div>
            <p className="lead">
              {mode==="success" ? AE.ui.leadSuccess : AE.ui.leadFallback}
            </p>
            <div className="qlist">
              {[AE.qa.success, AE.qa.fallback].map((q)=>{
                const m = q===AE.qa.success ? "success":"fallback";
                return (
                  <button key={m} className={`qrow ${mode===m?"on":""}`} onClick={()=>pick(m)}>
                    <span className="qi"><I.spark style={{width:16,height:16}}/></span>
                    {q.q}<span className="tg">{q.tag}</span>
                  </button>
                );
              })}
            </div>
            <button className="btn btn-ghost btn-sm" style={{marginTop:18}} onClick={replay}><I.refresh/>{AE.ui.replay}</button>
          </div>

          {/* right: side panel */}
          <div className="sp">
            <div className="sp-head">
              <span className="sq"><I.glyph/></span>
              <div>
                <div className="nm">ai-edge · hr</div>
                <div className="meta">{AE.ui.panelMeta}</div>
              </div>
              <span className="live"><span className="dot"></span>live</span>
            </div>
            <div className="sp-body">
              {phase>=1 && <div className="bubble-q">{d.q}</div>}
              {phase>=2 && (
                <div className="tool-chip">
                  {phase>=3 ? <span className="ok"><I.check style={{width:14,height:14}}/></span>
                            : <span className="ms">…</span>}
                  <b>{d.tool.name}</b>
                  <span className="ms">· {d.tool.chunks} chunks</span>
                  {phase>=3 && <span className="ms">{d.tool.ms}ms</span>}
                </div>
              )}

              {mode==="success" && phase>=4 && (
                <div className="answer">
                  {answerBlocks.map((blk,bi)=> (
                    <div key={bi} className="rv in" style={{transitionDelay:(bi*180)+"ms"}}>
                      {blk.type==="p"
                        ? <p><Parts parts={blk.parts}/></p>
                        : <ol>{blk.items.map((li,li2)=><li key={li2}><Parts parts={li.parts}/></li>)}</ol>}
                    </div>
                  ))}
                </div>
              )}
              {mode==="success" && phase>=5 && (
                <div className="sources rv in">
                  <div className="sources-h">
                    <I.glyph style={{width:14,height:14,color:"var(--faint)"}}/>
                    SOURCES <span className="badge">{d.sources.items.length}</span>
                    <span className="avg">avg score {d.sources.avg}</span>
                  </div>
                  {d.sources.items.map(s=>(
                    <div className="src" key={s.i}>
                      <span className="idx">{s.i}</span>
                      <div><div className="t">{s.t}</div><div className="f">{s.f}</div></div>
                      <span className="sc">score {s.sc}</span>
                    </div>
                  ))}
                </div>
              )}

              {mode==="fallback" && phase>=4 && (
                <div className="fallback rv in">
                  <div className="h"><I.warn style={{width:17,height:17}}/>{AE.ui.warnTitle}<span className="rr">{d.warn.rr}</span></div>
                  <p>{d.warn.text}</p>
                  <div className="acts">
                    <span className="b"><I.user style={{width:15,height:15}}/>{AE.ui.askHR}</span>
                    <span className="b"><I.refresh style={{width:15,height:15}}/>{AE.ui.rephrase}</span>
                  </div>
                </div>
              )}
              {mode==="fallback" && phase>=5 && (
                <div className="sources rv in">
                  <div className="sources-h">{AE.ui.srcUncertain} <span className="badge">1</span><span className="avg">avg score {d.warn.avg}</span></div>
                  <div className="src">
                    <span className="idx">{d.warn.src.i}</span>
                    <div><div className="t">{d.warn.src.t}</div><div className="f">{d.warn.src.f}</div></div>
                    <span className="sc">score {d.warn.src.sc}</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- NL2SQL demo (typing) ---------- */
function NL2SQL(){
  const [ref,seen]=useInView({ threshold:0.35 });
  const [n,setN]=useState(0);       // chars typed
  const [done,setDone]=useState(false);
  const started=useRef(false);

  // flatten code tokens -> [{cls,text}] with \n between lines
  const segs = [];
  AE.sql.code.forEach((line,li)=>{
    if(line.cm){ segs.push({cls:"cm",text:line.cm}); }
    else line.parts.forEach(p=>{
      const cls = p.kw?"kw":p.fn?"fn":p.str?"str":"";
      segs.push({cls, text:(p.kw||p.fn||p.str||p.t)});
    });
    if(li<AE.sql.code.length-1) segs.push({cls:"nl",text:"\n"});
  });
  const full = segs.reduce((a,s)=>a+s.text,0+"").length || segs.reduce((a,s)=>a+s.text.length,0);
  const total = segs.reduce((a,s)=>a+s.text.length,0);

  const start=()=>{
    if(started.current) return; started.current=true;
    if(motionOff()){ setN(total); setDone(true); return; }
    let i=0; const id=setInterval(()=>{ i+=2; setN(i); if(i>=total){ clearInterval(id); setN(total); setDone(true); } }, 26);
  };
  useEffect(()=>{ if(seen) start(); },[seen]);

  // render typed portion with coloring
  let remaining=n; const out=[];
  for(let k=0;k<segs.length;k++){
    if(remaining<=0) break;
    const s=segs[k]; const take=Math.min(s.text.length,remaining); remaining-=take;
    const txt=s.text.slice(0,take);
    if(s.cls==="nl") out.push(<br key={k}/>);
    else out.push(<span key={k} className={s.cls}>{txt}</span>);
  }

  return (
    <section className="section-pad" id="sql">
      <div className="wrap">
        <Reveal className="section-head">
          <div className="eyebrow">{AE.ui.sqlEyebrow}</div>
          <h2>{AE.ui.sqlTitle}</h2>
          <p>{AE.ui.sqlLead}</p>
        </Reveal>
        <Reveal className="sql-card" delay={80}>
          <div className="sql-q" ref={ref}>
            <span className="ai"><I.spark/></span>
            <span className="txt"><b>{AE.ui.sqlQ}</b>{AE.sql.q[0]}</span>
          </div>
          <div className="sql-code">
            {out}{!done && <span className="caret"></span>}
          </div>
          <div className="sql-guards" style={{opacity:done?1:0.35, transition:"opacity .4s"}}>
            {AE.sql.guards.map((g,i)=>(
              <span key={i} className={`guard ${g.ok?"":"block"}`}>
                {g.ok? <I.shield/> : <I.ban/>}{g.t}
              </span>
            ))}
          </div>
          {done && (
            <div className="sql-res rv in">
              <table>
                <thead><tr>{AE.sql.cols.map((c,i)=><th key={i} style={i>0?{textAlign:"right"}:null}>{c}</th>)}</tr></thead>
                <tbody>
                  {AE.sql.rows.map((r,ri)=>(
                    <tr key={ri}>{r.map((cell,ci)=> ci===0
                      ? <td key={ci}>{cell}</td>
                      : <td key={ci} className="n">{cell}</td>)}</tr>
                  ))}
                </tbody>
              </table>
              <div className="sql-trace">
                <span style={{color:"var(--accent)"}}>{AE.ui.sqlTrace}</span>
                {AE.sql.trace.map((t,i)=><span key={i}><b>{t}</b></span>)}
              </div>
            </div>
          )}
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { VideoSection, DocQA, NL2SQL });
})();
