// Live embedded mini-demos. Each mounts only if its root exists.
/* global React, ReactDOM */

const { useState, useEffect, useRef, useMemo } = React;

/* ─────────────── Copilot chat demo ─────────────── */
const copilotScript = [
  { who: 'user',  text: 'Reschedule my 3pm with Leo to Thursday and brief the team.' },
  { who: 'agent', text: 'On it. Checking Leo\'s calendar and the team\'s availability.',
    trace: ['calendar.read', 'messages.draft'] },
  { who: 'tool',  text: 'Thursday 3–3:45pm works for everyone. Draft ready.' },
  { who: 'agent', text: 'Moved to Thursday 3pm. Sent a one-line heads-up to #product and a summary to Leo. Anything else?',
    actions: ['Meeting moved', 'Slack posted', 'Summary emailed']
  },
  { who: 'user',  text: 'Also, how was my sleep last night?' },
  { who: 'agent', text: 'Solid. 7h 42m, high deep-sleep share. Resting HR trending –4 bpm week-over-week.',
    trace: ['biosense.read', 'insights.compute']
  },
];

function CopilotDemo() {
  const [msgs, setMsgs] = useState([]);
  const [typing, setTyping] = useState(false);
  const bodyRef = useRef(null);

  useEffect(() => {
    let i = 0, cancelled = false;
    async function run() {
      while (!cancelled) {
        const step = copilotScript[i % copilotScript.length];
        if (step.who !== 'user') { setTyping(true); await wait(650); setTyping(false); }
        if (!cancelled) setMsgs((m) => {
          const next = [...m, { ...step, id: Date.now() + Math.random() }];
          return next.slice(-6);
        });
        await wait(step.who === 'user' ? 1100 : 2600);
        i++;
      }
    }
    run();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [msgs, typing]);

  return (
    <div ref={bodyRef} style={{display:'flex',flexDirection:'column',gap:14,maxHeight:400,overflow:'hidden'}}>
      {msgs.map(m => <Bubble key={m.id} {...m} />)}
      {typing && <Typing />}
    </div>
  );
}

function Bubble({ who, text, trace, actions }) {
  if (who === 'user') {
    return (
      <div style={{alignSelf:'flex-end',maxWidth:'80%'}}>
        <div style={{background:'var(--surface-2)',border:'1px solid var(--line)',padding:'10px 14px',borderRadius:'14px 14px 4px 14px',fontSize:14,color:'var(--ink)'}}>{text}</div>
      </div>
    );
  }
  if (who === 'tool') {
    return (
      <div style={{alignSelf:'flex-start',fontFamily:'var(--font-mono)',fontSize:11,color:'var(--ink-3)',padding:'8px 12px',borderLeft:'2px solid var(--accent)',background:'color-mix(in oklab, var(--accent) 6%, transparent)'}}>
        <span style={{color:'var(--accent)',marginRight:8}}>›</span>{text}
      </div>
    );
  }
  return (
    <div style={{alignSelf:'flex-start',maxWidth:'88%',display:'flex',gap:10}}>
      <AgentDot />
      <div>
        <div style={{background:'#141822',border:'1px solid var(--line-2)',padding:'12px 14px',borderRadius:'14px 14px 14px 4px',fontSize:14,color:'var(--ink)'}}>{text}</div>
        {trace && (
          <div style={{display:'flex',gap:6,marginTop:8,flexWrap:'wrap'}}>
            {trace.map(t => <span key={t} style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--ink-3)',padding:'3px 7px',borderRadius:999,border:'1px solid var(--line)'}}>{t}</span>)}
          </div>
        )}
        {actions && (
          <div style={{display:'flex',gap:6,marginTop:8,flexWrap:'wrap'}}>
            {actions.map(a => (
              <span key={a} style={{fontSize:11,color:'var(--accent)',padding:'3px 8px',borderRadius:999,background:'color-mix(in oklab, var(--accent) 12%, transparent)',border:'1px solid color-mix(in oklab, var(--accent) 30%, transparent)'}}>
                ✓ {a}
              </span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function AgentDot() {
  return <div style={{width:24,height:24,borderRadius:999,flexShrink:0,background:'radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))',boxShadow:'0 0 16px color-mix(in oklab, var(--accent) 60%, transparent)',marginTop:2}} />;
}

function Typing() {
  return (
    <div style={{alignSelf:'flex-start',display:'flex',gap:10,alignItems:'center'}}>
      <AgentDot />
      <div style={{display:'flex',gap:4,padding:'12px 14px',background:'#141822',border:'1px solid var(--line-2)',borderRadius:14}}>
        {[0,1,2].map(i => <span key={i} style={{width:6,height:6,borderRadius:999,background:'var(--ink-3)',animation:`blink 1.2s ${i*0.15}s infinite ease-in-out`}}/>)}
      </div>
      <style>{`@keyframes blink { 0%,60%,100%{opacity:.3;transform:translateY(0)} 30%{opacity:1;transform:translateY(-2px)} }`}</style>
    </div>
  );
}

const wait = (ms) => new Promise(r => setTimeout(r, ms));

/* ─────────────── Heart rate sparkline ─────────────── */
function HRViz() {
  const [data, setData] = useState(() => Array.from({length: 60}, (_, i) => 62 + Math.sin(i/3) * 6 + (Math.random()-0.5)*3));
  const [hr, setHr] = useState(62);
  useEffect(() => {
    const id = setInterval(() => {
      setData(d => {
        const next = [...d.slice(1), d[d.length-1] + (Math.random()-0.5)*4];
        const clamped = next.map(v => Math.max(52, Math.min(84, v)));
        setHr(Math.round(clamped[clamped.length-1]));
        const hrEl = document.getElementById('stat-hr');
        if (hrEl) hrEl.innerHTML = `${Math.round(clamped[clamped.length-1])}<span style="font-size:.55em;color:var(--ink-3)"> bpm</span>`;
        return clamped;
      });
    }, 650);
    return () => clearInterval(id);
  }, []);
  const w = 600, h = 200, pad = 8;
  const min = 50, max = 86;
  const pts = data.map((v, i) => {
    const x = (i/(data.length-1)) * (w - pad*2) + pad;
    const y = h - pad - ((v-min)/(max-min)) * (h - pad*2);
    return [x, y];
  });
  const d = 'M' + pts.map(p => p.join(',')).join(' L');
  const dArea = d + ` L${w-pad},${h-pad} L${pad},${h-pad} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{width:'100%',height:'100%'}} preserveAspectRatio="none">
      <defs>
        <linearGradient id="hrFill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="var(--accent)" stopOpacity="0.35"/>
          <stop offset="1" stopColor="var(--accent)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={dArea} fill="url(#hrFill)"/>
      <path d={d} fill="none" stroke="var(--accent)" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="3.5" fill="var(--accent)">
        <animate attributeName="r" values="3.5;6;3.5" dur="1.4s" repeatCount="indefinite"/>
      </circle>
    </svg>
  );
}

/* ─────────────── Fluid dashboard ─────────────── */
function FluidDashboard() {
  return (
    <div style={{display:'grid',gridTemplateColumns:'260px 1fr 300px',gap:16,minHeight:480}}>
      <SidePanel />
      <MainPanel />
      <RightPanel />
    </div>
  );
}

function SidePanel() {
  const items = [
    {icon:'◐', label:'Today', active:true},
    {icon:'⊹', label:'Agents', badge:12},
    {icon:'♡', label:'Health'},
    {icon:'▢', label:'Spaces'},
    {icon:'⎔', label:'Automations', badge:3},
  ];
  return (
    <div style={{background:'rgba(255,255,255,.015)',border:'1px solid var(--line)',borderRadius:14,padding:14,display:'flex',flexDirection:'column',gap:6}}>
      <div style={{display:'flex',alignItems:'center',gap:10,padding:'6px 8px 14px',borderBottom:'1px solid var(--line)',marginBottom:8}}>
        <div style={{width:28,height:28,borderRadius:'50%',background:'linear-gradient(135deg,#444,#222)',border:'1px solid var(--line-2)'}}/>
        <div><div style={{fontSize:13}}>Mara K.</div><div style={{fontSize:11,color:'var(--ink-3)',fontFamily:'var(--font-mono)'}}>Connected · 4 devices</div></div>
      </div>
      {items.map((it, i) => (
        <div key={i} style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'9px 10px',borderRadius:10,background:it.active?'var(--surface-2)':'transparent',color:it.active?'var(--ink)':'var(--ink-2)',fontSize:13,cursor:'default'}}>
          <span style={{display:'flex',gap:10,alignItems:'center'}}><span style={{color:it.active?'var(--accent)':'var(--ink-3)',width:14,textAlign:'center'}}>{it.icon}</span>{it.label}</span>
          {it.badge && <span style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--ink-3)'}}>{it.badge}</span>}
        </div>
      ))}
      <div style={{marginTop:'auto',paddingTop:14,borderTop:'1px solid var(--line)',fontSize:11,color:'var(--ink-3)',fontFamily:'var(--font-mono)',letterSpacing:'.08em'}}>
        VAI OS · v2.0.0
      </div>
    </div>
  );
}

function MainPanel() {
  const widgets = [
    { title:'Focus block', body:'Heads-down 9:30–11:00 · Product review', meta:'in 18 min', tone:'mint' },
    { title:'Leo moved to Thursday', body:'Calendar + Slack updated', meta:'Copilot · 2m ago', tone:'ok' },
    { title:'Readiness', body:'84 · high', meta:'BioSense Band', tone:'accent' },
    { title:'Invoice · Acme Co.', body:'Draft ready, amount reconciled', meta:'Finance agent', tone:'ok' },
    { title:'Travel brief', body:'Paris trip · weather, visa, hotel check-in ready', meta:'in 3 days', tone:'' },
    { title:'Sleep debt', body:'–28 min this week', meta:'trend: improving', tone:'' },
  ];
  return (
    <div style={{display:'flex',flexDirection:'column',gap:12}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
        <div>
          <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--ink-3)',letterSpacing:'.12em',textTransform:'uppercase'}}>Tuesday · April 28</div>
          <div style={{fontSize:22,marginTop:4,letterSpacing:'-.02em'}}>Good morning, Mara.</div>
        </div>
        <div style={{display:'flex',gap:6,alignItems:'center',padding:'6px 10px',borderRadius:999,background:'var(--surface)',border:'1px solid var(--line)',fontSize:12,color:'var(--ink-2)'}}>
          <span style={{width:6,height:6,borderRadius:999,background:'#6EE7B7'}}/>
          3 agents active
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
        {widgets.map((w, i) => (
          <div key={i} style={{padding:'14px 16px',borderRadius:12,border:'1px solid var(--line)',background:'rgba(255,255,255,.02)',display:'flex',flexDirection:'column',gap:4,minHeight:88}}>
            <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--ink-3)',letterSpacing:'.08em',textTransform:'uppercase'}}>{w.title}</div>
            <div style={{fontSize:14,color:'var(--ink)'}}>{w.body}</div>
            <div style={{fontSize:11,fontFamily:'var(--font-mono)',color: w.tone==='accent'?'var(--accent)':'var(--ink-4)',marginTop:'auto'}}>{w.meta}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RightPanel() {
  const [hr, setHr] = useState(64);
  useEffect(() => {
    const id = setInterval(() => setHr(h => Math.max(58, Math.min(72, h + (Math.random()-0.5)*2))), 900);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{display:'flex',flexDirection:'column',gap:12}}>
      <div style={{padding:'14px 16px',borderRadius:12,border:'1px solid var(--line)',background:'rgba(255,255,255,.02)'}}>
        <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--ink-3)',letterSpacing:'.1em',textTransform:'uppercase',marginBottom:10}}>BioSense · Live</div>
        <div style={{display:'flex',alignItems:'baseline',gap:6}}>
          <div style={{fontSize:36,letterSpacing:'-.02em',fontFamily:'var(--font-display)'}}>{Math.round(hr)}</div>
          <div style={{fontSize:12,color:'var(--ink-3)',fontFamily:'var(--font-mono)'}}>bpm</div>
        </div>
        <Pulse />
      </div>
      <div style={{padding:'14px 16px',borderRadius:12,border:'1px solid var(--line)',background:'rgba(255,255,255,.02)'}}>
        <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--ink-3)',letterSpacing:'.1em',textTransform:'uppercase',marginBottom:10}}>Suggestions</div>
        <ul style={{margin:0,padding:0,listStyle:'none',display:'flex',flexDirection:'column',gap:10,fontSize:13,color:'var(--ink-2)'}}>
          <li>Walk 8 min before your 11am call</li>
          <li>Wind-down at 22:30 — trending sleep debt</li>
          <li>Reply: Leo, 2 msgs waiting</li>
        </ul>
      </div>
      <div style={{padding:'14px 16px',borderRadius:12,border:'1px solid var(--line)',background:'rgba(255,255,255,.02)'}}>
        <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--ink-3)',letterSpacing:'.1em',textTransform:'uppercase',marginBottom:10}}>Active agents</div>
        <div style={{display:'flex',flexDirection:'column',gap:6,fontSize:12,fontFamily:'var(--font-mono)',color:'var(--ink-2)'}}>
          <div>· scheduler</div><div>· finance</div><div>· health-copilot</div>
        </div>
      </div>
    </div>
  );
}

function Pulse() {
  return (
    <svg viewBox="0 0 220 40" style={{width:'100%',height:40,marginTop:8}} preserveAspectRatio="none">
      <path d="M0 20 L40 20 L48 8 L56 32 L64 14 L72 22 L100 20 L120 20 L128 10 L136 30 L144 16 L160 20 L220 20"
        fill="none" stroke="var(--accent)" strokeWidth="1.6">
        <animate attributeName="stroke-dasharray" values="0,400;400,0" dur="2.6s" repeatCount="indefinite"/>
      </path>
    </svg>
  );
}

/* ─────────────── Mount ─────────────── */
const copilotRoot = document.getElementById('copilot-demo-body');
if (copilotRoot) ReactDOM.createRoot(copilotRoot).render(<CopilotDemo/>);

const hrRoot = document.getElementById('hr-viz');
if (hrRoot) ReactDOM.createRoot(hrRoot).render(<HRViz/>);

const fluidRoot = document.getElementById('fluid-dashboard');
if (fluidRoot) ReactDOM.createRoot(fluidRoot).render(<FluidDashboard/>);

// Expose HRViz for Health page
Object.assign(window, { HRViz, FluidDashboard, CopilotDemo });
