// popover.jsx — dot+ menu bar popover + all states.
// Relies on globals from core.jsx (loaded first).

// ── sample data ───────────────────────────────────────────────────────────────
const RECENTS = [
  { id:'r1', title:'Anualidad + Web APROCAP', when:'Today · 5:57 PM', dur:'24:08', folder:'APROCAP', spk:[{name:'Verónica',idx:0},{name:'You',idx:1}], status:'done' },
  { id:'r2', title:'Microphone Test and Color Review', when:'Today · 4:03 PM', dur:'00:19', folder:null, spk:[{name:'You',idx:1}], status:'done' },
  { id:'r3', title:'Q3 Launch — Eng sync', when:'Yesterday · 10:02 AM', dur:'42:15', folder:'Q3 Launch', spk:[{name:'Maya',idx:2},{name:'Rodrigo',idx:3},{name:null,idx:0}], status:'done' },
  { id:'r4', title:'Sales discovery — Altagracia', when:'Mon · 2:30 PM', dur:'31:44', folder:'APROCAP', spk:[{name:null,idx:0},{name:null,idx:1}], status:'processing' },
];

const LIVE_LINES = [
  { at:1,  spk:'Verónica', idx:0, text:'Okay — so for the annuity page, the hero should lead with the renewal CTA.' },
  { at:4,  spk:'You',      idx:1, text:'Agreed. Can we pull the APROCAP numbers from last quarter into it?' },
  { at:8,  spk:'Verónica', idx:0, text:'Yes, I have them. I will share the deck right after this.' },
  { at:12, spk:'You',      idx:1, text:'Perfect. Let us also confirm the launch date before we wrap.' },
  { at:16, spk:'Verónica', idx:0, text:'The 14th works on my end. I will hold it.' },
];

// ── helpers ───────────────────────────────────────────────────────────────────
const dens = (t) => t.density === 'Compact'
  ? { rowPad:'8px 10px', gap:8, listGap:2 }
  : { rowPad:'11px 12px', gap:12, listGap:6 };

function SectionLabel({ children, action, onAction }) {
  return (
    <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', padding:'0 2px 8px' }}>
      <span style={{ fontFamily:SANS, fontSize:11, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', color:'var(--c3)' }}>{children}</span>
      {action && <button onClick={onAction} style={{ background:'none', border:'none', cursor:'pointer', fontFamily:SANS, fontSize:12, fontWeight:600, color:'var(--accent)' }}>{action}</button>}
    </div>
  );
}

function SearchField() {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8, height:34, padding:'0 10px', borderRadius:8, background:'var(--s2)' }}>
      <I.search size={16} color="var(--c3)"/>
      <span style={{ fontFamily:SANS, fontSize:13, color:'var(--c3)' }}>Search recordings</span>
      <span style={{ flex:1 }}/>
      <span style={{ display:'flex', gap:3 }}><Key>⌘</Key><Key>K</Key></span>
    </div>
  );
}

// recent recording row
function RecentRow({ r, t, onClick }) {
  const d = dens(t);
  return (
    <button onClick={onClick} style={{
      width:'100%', display:'flex', alignItems:'center', gap:10, background:'transparent', border:'none',
      padding:d.rowPad, borderRadius:8, cursor:'pointer', textAlign:'left', transition:'background .12s',
    }}
      onMouseEnter={(e)=>e.currentTarget.style.background='var(--s2)'}
      onMouseLeave={(e)=>e.currentTarget.style.background='transparent'}
    >
      <span style={{
        width:34, height:34, borderRadius:8, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
        background:'var(--s2)', color: r.status==='processing' ? 'var(--warn)' : 'var(--c2)',
      }}>
        {r.status==='processing' ? <I.waves size={18}/> : <I.doc size={17}/>}
      </span>
      <span style={{ flex:1, minWidth:0 }}>
        <span style={{ display:'block', fontFamily:SANS, fontSize:13.5, fontWeight:600, color:'var(--c1)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.title}</span>
        <span style={{ display:'flex', alignItems:'center', gap:6, marginTop:2, fontFamily:MONO, fontSize:11, color:'var(--c3)' }}>
          <span>{r.when}</span><span style={{ color:'var(--cdis)' }}>·</span><span>{r.dur}</span>
        </span>
      </span>
      {r.status==='processing'
        ? <Tag variant="warning" dot>Processing</Tag>
        : <span style={{ display:'flex', alignItems:'center', flexShrink:0 }}>
            {r.spk.slice(0,3).map((s,i)=><span key={i} style={{ marginLeft:i?-7:0 }}><Avatar name={s.name} idx={s.idx} size={22} ring/></span>)}
          </span>}
    </button>
  );
}

// source selector pill
function SourceChip({ icon, label, active, meter, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex:1, display:'flex', alignItems:'center', gap:8, padding:'9px 10px', borderRadius:8, cursor:'pointer',
      background: active ? 'var(--s2)' : 'transparent',
      border:`1px solid ${active ? 'var(--accent)' : 'var(--border)'}`, transition:'all .15s', minWidth:0,
    }}>
      <span style={{ color: active ? 'var(--accent)' : 'var(--c3)', display:'flex', flexShrink:0 }}>{icon}</span>
      <span style={{ flex:1, textAlign:'left', minWidth:0 }}>
        <span style={{ display:'block', fontFamily:SANS, fontSize:12.5, fontWeight:600, color: active ? 'var(--c1)' : 'var(--c2)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{label}</span>
      </span>
      {meter && <Meter active={active} bars={4} color="var(--accent)" h={14}/>}
    </button>
  );
}

// ── popover shell ──────────────────────────────────────────────────────────────
function PopShell({ width, detached, children, dragHandlers }) {
  return (
    <div style={{
      width, borderRadius:14, overflow:'hidden', position:'relative',
      background:'var(--pop-bg)', border:'1px solid var(--pop-border)', boxShadow:'var(--pop-shadow)',
    }}>
      {detached && (
        <div onMouseDown={dragHandlers && dragHandlers.onMouseDown} style={{
          height:22, display:'flex', alignItems:'center', justifyContent:'center', cursor:'grab',
          borderBottom:'1px solid var(--border-sub)',
        }}>
          <span style={{ color:'var(--c3)', opacity:.6 }}><I.grip size={16}/></span>
        </div>
      )}
      {children}
    </div>
  );
}

// ── HEADER ───────────────────────────────────────────────────────────────────
function PopHeader({ go, openApp, detached, toggleDetach, closePopover, screen }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8, padding:'12px 12px 8px' }}>
      <Monogram size={20}/>
      <span style={{ fontFamily:SANS, fontWeight:800, fontSize:17, letterSpacing:'-0.02em', color:'var(--c1)' }}>dot<span style={{ color:'var(--accent)' }}>+</span></span>
      <span style={{ flex:1 }}/>
      <IconBtn icon={<I.sparkles size={18}/>} title="Ask dot+" active={screen==='ai'} onClick={()=>go('ai')}/>
      <IconBtn icon={<I.detach size={17}/>} title={detached ? 'Re-attach to menu bar' : 'Detach window'} active={detached} onClick={toggleDetach}/>
      <IconBtn icon={<I.gear size={18}/>} title="Settings" active={screen==='settings'} onClick={()=>go('settings')}/>
      <button onClick={openApp} title="Open dot+" style={{ width:28, height:28, borderRadius:'50%', border:'1.5px solid var(--border)', background:'var(--s2)', color:'var(--c1)', fontFamily:SANS, fontWeight:600, fontSize:11.5, cursor:'pointer', flexShrink:0 }}>RA</button>
    </div>
  );
}

// brand monogram: square chip with disc + plus tick (from brand lockup)
function Monogram({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display:'block', flexShrink:0 }}>
      <rect x="2" y="2" width="96" height="96" rx="24" fill="var(--ink-s)"/>
      <circle cx="38" cy="64" r="17" fill="var(--ink-c)"/>
      <rect x="62" y="22" width="26" height="6" rx="3" fill="var(--accent)"/>
      <rect x="72" y="12" width="6" height="26" rx="3" fill="var(--accent)"/>
    </svg>
  );
}

// ── HOME ─────────────────────────────────────────────────────────────────────
function HomeView({ t, go, startRec, openApp }) {
  const d = dens(t);
  const focused = t.homeLayout === 'Focused';
  const recAtTop = t.recordButton === 'Top';

  const RecordBlock = (
    <div style={{ padding:'0 12px' }}>
      <Btn variant="record" size="large" shape="pill" full onClick={startRec} style={{ fontSize:16 }}>
        <span style={{ width:11, height:11, borderRadius:'50%', background:'var(--neg)', boxShadow:'0 0 0 3px color-mix(in srgb, var(--neg) 22%, transparent)' }}/>
        Start recording
        <span style={{ flex:1 }}/>
        <span style={{ display:'flex', gap:3, opacity:.7 }}><Key>⌃</Key><Key>⌥</Key><Key>R</Key></span>
      </Btn>
      <div style={{ display:'flex', gap:6, marginTop:8 }}>
        <SourceChip icon={<I.system size={16}/>} label="System audio" active onClick={()=>{}}/>
        <SourceChip icon={<I.mic size={16}/>} label="Microphone" active onClick={()=>{}}/>
      </div>
      <button style={{ marginTop:6, width:'100%', display:'flex', alignItems:'center', justifyContent:'center', gap:6, background:'none', border:'none', cursor:'pointer', color:'var(--c3)', fontFamily:SANS, fontSize:11.5, padding:'2px' }}>
        Auto-detect meeting audio <I.chevDown size={13}/>
      </button>
    </div>
  );

  return (
    <div>
      <PopHeader screen="home" {...t.__hdr} go={go} openApp={openApp} detached={t.__detached} toggleDetach={t.__toggleDetach}/>

      {/* calendar-aware next meeting */}
      <div style={{ padding:'2px 12px 12px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 12px', borderRadius:10, background:'color-mix(in srgb, var(--accent) 12%, transparent)', border:'1px solid color-mix(in srgb, var(--accent) 22%, transparent)' }}>
          <span style={{ color:'var(--accent)', display:'flex' }}><I.cal size={18}/></span>
          <span style={{ flex:1, minWidth:0 }}>
            <span style={{ display:'block', fontFamily:SANS, fontSize:13, fontWeight:600, color:'var(--c1)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Design Review</span>
            <span style={{ display:'block', fontFamily:MONO, fontSize:11, color:'var(--c2)', marginTop:1 }}>in 12 min · Google Meet</span>
          </span>
          <Btn variant="accent" size="small" shape="pill" onClick={startRec}>Record</Btn>
        </div>
      </div>

      {recAtTop && RecordBlock}

      {/* recent list */}
      <div style={{ padding: recAtTop ? '16px 12px 0' : '4px 12px 0' }}>
        <div style={{ marginBottom:8 }}><SearchField/></div>
        <SectionLabel action="See all" onAction={openApp}>{focused ? 'Jump back in' : 'Recent'}</SectionLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:d.listGap, margin:'0 -4px' }}>
          {(focused ? RECENTS.slice(0,2) : RECENTS).map(r => (
            <RecentRow key={r.id} r={r} t={t} onClick={()=>go('detail')}/>
          ))}
        </div>
      </div>

      {!recAtTop && <div style={{ padding:'14px 0 4px' }}>{RecordBlock}</div>}

      {/* footer */}
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'12px', marginTop:6, borderTop:'1px solid var(--border-sub)' }}>
        <button onClick={openApp} style={{ display:'flex', alignItems:'center', gap:7, background:'none', border:'none', cursor:'pointer', color:'var(--c2)', fontFamily:SANS, fontSize:12.5, fontWeight:600 }}>
          <I.arrowOut size={16}/> Open dot+
        </button>
        <span style={{ flex:1 }}/>
        <span style={{ fontFamily:MONO, fontSize:10.5, color:'var(--c3)' }}>14 recordings · 6.2 hrs</span>
      </div>
    </div>
  );
}

// ── RECORDING ─────────────────────────────────────────────────────────────────
function RecordingView({ t, elapsed, stopRec, go, detached, toggleDetach }) {
  const wave = t.recordingStyle === 'Waveform';
  const lines = LIVE_LINES.filter(l => l.at <= elapsed);
  const streamRef = React.useRef(null);
  React.useEffect(() => { if (streamRef.current) streamRef.current.scrollTop = streamRef.current.scrollHeight; }, [lines.length]);

  const [min, setMin] = React.useState(false);
  const [showSources, setShowSources] = React.useState(false);

  // compact recording bar (minimized) — timer + live level + controls only
  if (min) {
    return (
      <div style={{ padding:'12px 13px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:11 }}>
          <span style={{ position:'relative', width:9, height:9, flexShrink:0 }}>
            <span style={{ position:'absolute', inset:0, borderRadius:'50%', background:'var(--neg)' }}/>
            <span style={{ position:'absolute', inset:0, borderRadius:'50%', background:'var(--neg)', animation:'dotpulse 1.4s ease-out infinite' }}/>
          </span>
          <span style={{ fontFamily:MONO, fontSize:17, fontWeight:500, color:'var(--c1)', fontVariantNumeric:'tabular-nums', letterSpacing:'-0.01em' }}>{mm(elapsed)}</span>
          <Meter active bars={4} color="var(--c2)" h={14}/>
          <span style={{ flex:1 }}/>
          <IconBtn icon={<I.pause size={17}/>} size={30} title="Pause"/>
          <Btn variant="record" size="small" shape="pill" onClick={stopRec} style={{ background:'var(--neg)', color:'#fff' }}><I.stop size={14}/> Stop</Btn>
          <IconBtn icon={<I.detach size={15}/>} size={30} active={detached} title={detached ? 'Re-attach to menu bar' : 'Float window'} onClick={toggleDetach}/>
          <IconBtn icon={<I.expand size={16}/>} size={30} title="Expand" onClick={()=>setMin(false)}/>
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding:'14px 14px 14px' }}>
      <div style={{ display:'flex', alignItems:'center', gap:10 }}>
        <span style={{ position:'relative', width:10, height:10 }}>
          <span style={{ position:'absolute', inset:0, borderRadius:'50%', background:'var(--neg)' }}/>
          <span style={{ position:'absolute', inset:0, borderRadius:'50%', background:'var(--neg)', animation:'dotpulse 1.4s ease-out infinite' }}/>
        </span>
        <span style={{ fontFamily:SANS, fontSize:12, fontWeight:700, letterSpacing:'.12em', textTransform:'uppercase', color:'var(--neg)' }}>Recording</span>
        <span style={{ flex:1 }}/>
        <span style={{ fontFamily:MONO, fontSize:22, fontWeight:500, color:'var(--c1)', letterSpacing:'-0.01em', fontVariantNumeric:'tabular-nums' }}>{mm(elapsed)}</span>
        <IconBtn icon={<I.detach size={16}/>} size={30} active={detached} title={detached ? 'Re-attach to menu bar' : 'Float window'} onClick={toggleDetach}/>
        <IconBtn icon={<I.minimize size={16}/>} size={30} title="Minimize" onClick={()=>setMin(true)}/>
      </div>

      {/* capture status — slim by default, per-source meters on demand */}
      <div style={{ marginTop:14, borderRadius:10, background:'var(--s1)', border:'1px solid var(--border-sub)', overflow:'hidden' }}>
        <button onClick={()=>setShowSources(s=>!s)} style={{ width:'100%', display:'flex', alignItems:'center', gap:10, padding:'9px 11px', background:'transparent', border:'none', cursor:'pointer', textAlign:'left' }}>
          <span style={{ display:'flex', gap:5, color:'var(--c2)', flexShrink:0 }}><I.system size={15}/><I.mic size={15}/></span>
          <span style={{ flex:1, fontFamily:SANS, fontSize:12.5, fontWeight:600, color:'var(--c1)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>System audio + Microphone</span>
          {wave ? <WaveLine active/> : <Meter active bars={4} color="var(--c2)" h={13}/>}
          <I.chevDown size={15} color="var(--c3)" style={{ transform: showSources?'rotate(180deg)':'none', transition:'transform .15s', flexShrink:0 }}/>
        </button>
        {showSources && (
          <div style={{ display:'flex', gap:8, padding:'2px 11px 11px' }}>
            {[['System audio', <I.system size={16}/>], ['Microphone', <I.mic size={16}/>]].map(([label, ic], i) => (
              <div key={i} style={{ flex:1, display:'flex', alignItems:'center', gap:9, padding:'10px 11px', borderRadius:10, background:'var(--s2)', minWidth:0 }}>
                <span style={{ color:'var(--c2)', display:'flex' }}>{ic}</span>
                <span style={{ flex:1, fontFamily:SANS, fontSize:12, fontWeight:600, color:'var(--c2)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth:0 }}>{label}</span>
                {wave ? <WaveLine active/> : <Meter active bars={5} color="var(--c1)" h={16}/>}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* recording to */}
      <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:12, fontFamily:SANS, fontSize:12, color:'var(--c3)' }}>
        <I.folder size={15} color="var(--c3)"/>
        <span>Saving to</span>
        <span style={{ color:'var(--c1)', fontWeight:600 }}>APROCAP</span>
        <button style={{ background:'none', border:'none', cursor:'pointer', color:'var(--accent)', fontFamily:SANS, fontSize:12, fontWeight:600 }}>Change</button>
      </div>

      {/* live transcript */}
      <div style={{ marginTop:14, borderRadius:12, background:'var(--s1)', border:'1px solid var(--border-sub)', overflow:'hidden' }}>
        <div style={{ display:'flex', alignItems:'center', gap:7, padding:'10px 12px 8px' }}>
          <I.sparkles size={14} color="var(--accent)"/>
          <span style={{ fontFamily:SANS, fontSize:11, fontWeight:600, letterSpacing:'.06em', textTransform:'uppercase', color:'var(--c2)' }}>Live transcript</span>
          <span style={{ flex:1 }}/>
          <Tag variant="info" dot>Beta</Tag>
        </div>
        <div ref={streamRef} style={{ maxHeight:124, overflowY:'auto', padding:'0 12px 12px', display:'flex', flexDirection:'column', gap:10 }}>
          {lines.length === 0 && <span style={{ fontFamily:SANS, fontSize:13, color:'var(--c3)', padding:'4px 0' }}>Listening…</span>}
          {lines.map((l, i) => (
            <div key={i} style={{ display:'flex', gap:8, animation:'linein .3s ease' }}>
              <Avatar name={l.spk} idx={l.idx} size={22}/>
              <span style={{ flex:1 }}>
                <span style={{ display:'block', fontFamily:SANS, fontSize:11.5, fontWeight:600, color:SPK[l.idx%4], marginBottom:1 }}>{l.spk}</span>
                <span style={{ display:'block', fontFamily:SANS, fontSize:13, lineHeight:'19px', color:'var(--c1)' }}>{l.text}</span>
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* controls */}
      <div style={{ display:'flex', gap:8, marginTop:14 }}>
        <Btn variant="ghost" size="default" style={{ flex:'0 0 auto', width:46 }} title="Pause"><I.pause size={18}/></Btn>
        <Btn variant="ghost" size="default" style={{ flex:'0 0 auto' }}><I.pin size={17}/> Marker</Btn>
        <Btn variant="record" size="default" shape="pill" onClick={stopRec} style={{ flex:1, background:'var(--neg)', color:'#fff' }}>
          <I.stop size={16}/> Stop &amp; save
        </Btn>
      </div>
    </div>
  );
}

function WaveLine({ active }) {
  const [s, setS] = React.useState(0);
  React.useEffect(() => { if (!active) return; const id = setInterval(()=>setS(x=>x+1), 110); return ()=>clearInterval(id); }, [active]);
  const pts = Array.from({ length: 22 }).map((_, i) => {
    const v = 8 + Math.abs(Math.sin((s + i*0.8)*0.7)) * (i%3===0?8:5);
    return `${i*2.4},${16 - v} ${i*2.4},${16 + v}`;
  });
  return (
    <svg width={54} height={32} viewBox="0 0 54 32" style={{ flexShrink:0 }}>
      {pts.map((p, i) => <line key={i} x1={p.split(' ')[0].split(',')[0]} y1={p.split(' ')[0].split(',')[1]} x2={p.split(' ')[1].split(',')[0]} y2={p.split(' ')[1].split(',')[1]} stroke="var(--c1)" strokeWidth="1.6" strokeLinecap="round"/>)}
    </svg>
  );
}

// ── PROCESSING ─────────────────────────────────────────────────────────────────
function ProcessingView({ go }) {
  const steps = [
    { label:'Transcribing audio', state:'done' },
    { label:'Identifying speakers', state:'active' },
    { label:'Summarizing & extracting steps', state:'pending' },
  ];
  return (
    <div style={{ padding:'18px 16px 16px' }}>
      <div style={{ display:'flex', alignItems:'center', gap:12 }}>
        <Spinner/>
        <span style={{ minWidth:0 }}>
          <span style={{ display:'block', fontFamily:SANS, fontSize:14, fontWeight:700, color:'var(--c1)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Anualidad + Web APROCAP</span>
          <span style={{ display:'block', fontFamily:MONO, fontSize:11, color:'var(--c3)', marginTop:2 }}>24:08 · processing on-device</span>
        </span>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:2, marginTop:18 }}>
        {steps.map((s, i) => (
          <div key={i} style={{ display:'flex', alignItems:'center', gap:11, padding:'9px 2px' }}>
            <span style={{ flexShrink:0, display:'flex' }}>
              {s.state==='done' ? <I.checkfill size={20} color="var(--pos)"/>
                : s.state==='active' ? <Spinner size={20} thin/>
                : <I.circle size={20} color="var(--cdis)"/>}
            </span>
            <span style={{ fontFamily:SANS, fontSize:13.5, fontWeight: s.state==='active'?600:500, color: s.state==='pending'?'var(--c3)':'var(--c1)' }}>{s.label}</span>
          </div>
        ))}
      </div>
      <div style={{ marginTop:8, height:4, borderRadius:2, background:'var(--s2)', overflow:'hidden' }}>
        <div style={{ width:'62%', height:'100%', background:'var(--accent)', borderRadius:2, transition:'width .4s' }}/>
      </div>
      <p style={{ fontFamily:SANS, fontSize:12, color:'var(--c3)', lineHeight:'17px', margin:'14px 0 0' }}>
        You can close this — dot+ keeps working in the menu bar and will notify you when the summary is ready.
      </p>
      <Btn variant="secondary" size="small" shape="pill" full onClick={()=>go('detail')} style={{ marginTop:14 }}>Preview when ready</Btn>
    </div>
  );
}

function Spinner({ size = 30, thin }) {
  return <span style={{ width:size, height:size, borderRadius:'50%', border:`${thin?2:2.5}px solid var(--s3)`, borderTopColor:'var(--accent)', display:'inline-block', animation:'spin .8s linear infinite', flexShrink:0 }}/>;
}

// ── DETAIL (compact) ─────────────────────────────────────────────────────────
function DetailView({ t, go, openApp }) {
  const [tab, setTab] = React.useState('Summary');
  const tabs = ['Summary','Transcript','Key Points','Next Steps'];
  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:6, padding:'12px 12px 4px' }}>
        <IconBtn icon={<I.chev size={18} style={{ transform:'rotate(180deg)' }}/>} onClick={()=>go('home')} title="Back"/>
        <span style={{ flex:1 }}/>
        <IconBtn icon={<I.copy size={17}/>} title="Copy summary"/>
        <IconBtn icon={<I.share size={17}/>} title="Share"/>
        <IconBtn icon={<I.arrowOut size={17}/>} title="Open in dot+" onClick={openApp}/>
      </div>
      <div style={{ padding:'0 16px' }}>
        <h2 style={{ margin:'2px 0 6px', fontFamily:SANS, fontSize:18, fontWeight:700, lineHeight:'23px', letterSpacing:'-0.01em', color:'var(--c1)' }}>Anualidad + Web APROCAP</h2>
        <div style={{ display:'flex', alignItems:'center', gap:7, fontFamily:MONO, fontSize:11, color:'var(--c2)', flexWrap:'wrap' }}>
          <span style={{ display:'inline-flex', alignItems:'center', gap:4 }}><I.cal size={13} color="var(--c3)"/> Jun 26 · 5:57 PM</span>
          <span style={{ color:'var(--cdis)' }}>·</span>
          <span style={{ display:'inline-flex', alignItems:'center', gap:4 }}><I.clock size={13} color="var(--c3)"/> 24:08</span>
          <span style={{ color:'var(--cdis)' }}>·</span>
          <span style={{ display:'inline-flex', alignItems:'center', gap:4, minWidth:0 }}><I.pin size={13} color="var(--c3)"/> Higüey</span>
        </div>
      </div>

      {/* mini player */}
      <div style={{ padding:'12px 16px 0' }}><MiniPlayer/></div>

      {/* speakers + project chips */}
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'12px 16px 0' }}>
        <span style={{ display:'flex', alignItems:'center' }}>
          {[{name:'Verónica',idx:0},{name:'You',idx:1}].map((s,i)=><span key={i} style={{ marginLeft:i?-8:0 }}><Avatar name={s.name} idx={s.idx} size={24} ring/></span>)}
        </span>
        <span style={{ fontFamily:SANS, fontSize:12.5, color:'var(--c2)' }}>Named</span>
        <span style={{ flex:1 }}/>
        <Tag dot><span style={{ display:'inline-flex', alignItems:'center', gap:5 }}><I.folder size={12}/>APROCAP</span></Tag>
      </div>

      {/* tabs */}
      <div style={{ display:'flex', gap:16, padding:'14px 16px 0', borderBottom:'1px solid var(--border-sub)', overflowX:'auto' }}>
        {tabs.map(tb => {
          const on = tab===tb;
          return <button key={tb} onClick={()=>setTab(tb)} style={{ background:'none', border:'none', cursor:'pointer', padding:'0 0 10px', position:'relative', whiteSpace:'nowrap', fontFamily:SANS, fontSize:13, fontWeight:on?600:500, color:on?'var(--c1)':'var(--c3)' }}>{tb}{on && <span style={{ position:'absolute', left:0, right:0, bottom:-1, height:2, borderRadius:2, background:'var(--c1)' }}/>}</button>;
        })}
      </div>

      <div style={{ padding:'14px 16px 16px', maxHeight:230, overflowY:'auto' }}>
        {tab==='Summary' && (
          <div style={{ borderRadius:12, background:'var(--s1)', padding:13 }}>
            <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:9 }}>
              <I.sparkles size={15} color="var(--accent)"/>
              <span style={{ fontFamily:SANS, fontSize:12, fontWeight:600, color:'var(--c2)' }}>AI Summary</span>
            </div>
            <p style={{ margin:0, fontFamily:SANS, fontSize:13.5, lineHeight:'21px', color:'var(--c1)' }}>Verónica and the team aligned the APROCAP annuity page around a renewal-first hero, agreed to pull last quarter's figures into it, and confirmed a launch hold for the 14th.</p>
          </div>
        )}
        {tab==='Transcript' && (
          <div style={{ display:'flex', flexDirection:'column', gap:13 }}>
            {LIVE_LINES.map((l,i)=>(
              <div key={i} style={{ display:'flex', gap:9 }}>
                <Avatar name={l.spk} idx={l.idx} size={24}/>
                <span style={{ flex:1 }}>
                  <span style={{ display:'block', fontFamily:SANS, fontSize:12, fontWeight:600, color:SPK[l.idx%4], marginBottom:2 }}>{l.spk}</span>
                  <span style={{ display:'block', fontFamily:SANS, fontSize:13.5, lineHeight:'20px', color:'var(--c1)' }}>{l.text}</span>
                </span>
              </div>
            ))}
          </div>
        )}
        {tab==='Key Points' && (
          <div style={{ display:'flex', flexDirection:'column', gap:7 }}>
            {['Renewal CTA leads the annuity hero.','Pull last quarter APROCAP figures into the page.','Launch date held for the 14th.'].map((p,i)=>(
              <div key={i} style={{ display:'flex', gap:10, alignItems:'flex-start', background:'var(--s1)', borderRadius:10, padding:'11px 12px' }}>
                <I.star size={13} color="var(--warn)" style={{ marginTop:3 }}/>
                <span style={{ fontFamily:SANS, fontSize:13.5, lineHeight:'20px', color:'var(--c1)' }}>{p}</span>
              </div>
            ))}
          </div>
        )}
        {tab==='Next Steps' && (
          <div style={{ display:'flex', flexDirection:'column', gap:7 }}>
            {[['Share Q3 figures deck','Verónica',false],['Hold launch date — the 14th','You',true],['Draft renewal hero copy','You',false]].map(([txt,who,done],i)=>(
              <div key={i} style={{ display:'flex', gap:10, alignItems:'center', background:'var(--s1)', borderRadius:10, padding:'11px 12px' }}>
                <span style={{ display:'flex', color: done?'var(--pos)':'var(--c3)' }}>{done?<I.checkfill size={20}/>:<I.circle size={20}/>}</span>
                <span style={{ flex:1 }}>
                  <span style={{ display:'block', fontFamily:SANS, fontSize:13.5, fontWeight:600, color: done?'var(--c3)':'var(--c1)', textDecoration:done?'line-through':'none' }}>{txt}</span>
                  <span style={{ display:'block', fontFamily:MONO, fontSize:11, color:'var(--c3)', marginTop:1 }}>@{who}</span>
                </span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function MiniPlayer() {
  const [playing, setPlaying] = React.useState(false);
  const [pct, setPct] = React.useState(18);
  React.useEffect(() => { if (!playing) return; const id = setInterval(()=>setPct(p=>p>=100?(setPlaying(false),100):p+1.2), 200); return ()=>clearInterval(id); }, [playing]);
  return (
    <div style={{ display:'flex', alignItems:'center', gap:12, background:'var(--s1)', borderRadius:10, padding:'9px 11px' }}>
      <button onClick={()=>setPlaying(p=>!p)} style={{ width:34, height:34, borderRadius:'50%', border:'none', background:'var(--s3)', color:'var(--c1)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}>{playing?<I.pause size={16}/>:<I.play size={16} style={{ marginLeft:2 }}/>}</button>
      <div style={{ flex:1 }}>
        <div style={{ height:4, borderRadius:2, background:'var(--s3)', position:'relative', overflow:'hidden' }}><div style={{ position:'absolute', inset:0, width:`${pct}%`, background:'var(--c1)' }}/></div>
        <div style={{ display:'flex', justifyContent:'space-between', marginTop:6, fontFamily:MONO, fontSize:10.5, color:'var(--c3)' }}><span>{mm(pct/100*1448)}</span><span>24:08</span></div>
      </div>
    </div>
  );
}

// ── AI ASK ─────────────────────────────────────────────────────────────────────
function AiView({ t, go }) {
  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'12px 12px 8px' }}>
        <IconBtn icon={<I.chev size={18} style={{ transform:'rotate(180deg)' }}/>} onClick={()=>go('home')} title="Back"/>
        <I.sparkles size={18} color="var(--accent)"/>
        <span style={{ fontFamily:SANS, fontWeight:700, fontSize:15, color:'var(--c1)' }}>Ask dot+</span>
        <span style={{ flex:1 }}/>
        <span style={{ fontFamily:MONO, fontSize:10.5, color:'var(--c3)' }}>14 recordings</span>
      </div>
      <div style={{ padding:'4px 14px 0', display:'flex', flexDirection:'column', gap:12, maxHeight:300, overflowY:'auto' }}>
        <div style={{ alignSelf:'flex-end', maxWidth:'82%', background:'var(--s2)', borderRadius:'12px 12px 4px 12px', padding:'9px 12px', fontFamily:SANS, fontSize:13.5, lineHeight:'19px', color:'var(--c1)' }}>What did we decide about the APROCAP launch date?</div>
        <div style={{ alignSelf:'flex-start', maxWidth:'90%' }}>
          <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:6, color:'var(--accent)' }}><I.sparkles size={14}/><span style={{ fontFamily:SANS, fontSize:11, fontWeight:600, letterSpacing:'.04em' }}>dot+</span></div>
          <div style={{ fontFamily:SANS, fontSize:13.5, lineHeight:'20px', color:'var(--c1)' }}>You held the launch for <b>the 14th</b>. Verónica confirmed it works on her end and said she'd hold the date.</div>
          <button onClick={()=>go('detail')} style={{ display:'flex', alignItems:'center', gap:8, marginTop:9, width:'100%', background:'var(--s1)', border:'1px solid var(--border-sub)', borderRadius:10, padding:'9px 11px', cursor:'pointer', textAlign:'left' }}>
            <I.doc size={16} color="var(--c3)"/>
            <span style={{ flex:1, minWidth:0 }}>
              <span style={{ display:'block', fontFamily:SANS, fontSize:12.5, fontWeight:600, color:'var(--c1)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Anualidad + Web APROCAP</span>
              <span style={{ display:'block', fontFamily:MONO, fontSize:10.5, color:'var(--c3)' }}>16:24 · cited</span>
            </span>
            <I.chev size={15} color="var(--c3)"/>
          </button>
        </div>
      </div>
      <div style={{ display:'flex', gap:6, padding:'12px 14px 6px', flexWrap:'wrap' }}>
        {['Open next steps','Summarize this week','Who joined?'].map(s=>(
          <button key={s} style={{ background:'var(--s2)', border:'none', borderRadius:999, padding:'6px 11px', cursor:'pointer', fontFamily:SANS, fontSize:12, color:'var(--c2)' }}>{s}</button>
        ))}
      </div>
      <div style={{ padding:'4px 14px 14px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, height:40, padding:'0 6px 0 12px', borderRadius:999, background:'var(--s2)', border:'1px solid var(--border)' }}>
          <span style={{ flex:1, fontFamily:SANS, fontSize:13, color:'var(--c3)' }}>Ask across your recordings…</span>
          <button style={{ width:30, height:30, borderRadius:'50%', border:'none', background:'var(--accent)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}><I.send size={16} style={{ marginLeft:-1 }}/></button>
        </div>
      </div>
    </div>
  );
}

// ── SETTINGS (mini) ──────────────────────────────────────────────────────────
function MiniSettings({ t, go, openApp }) {
  const [v, setV] = React.useState({ login:true, timer:true, sys:true, both:true, auto:true });
  const tog = (k) => setV(s=>({ ...s, [k]:!s[k] }));
  const Row = ({ label, sub, k, right }) => (
    <div style={{ display:'flex', alignItems:'center', gap:12, padding:'11px 0' }}>
      <span style={{ flex:1, minWidth:0 }}>
        <span style={{ display:'block', fontFamily:SANS, fontSize:13.5, fontWeight:500, color:'var(--c1)' }}>{label}</span>
        {sub && <span style={{ display:'block', fontFamily:SANS, fontSize:11.5, color:'var(--c3)', marginTop:1 }}>{sub}</span>}
      </span>
      {right || <Toggle on={v[k]} onClick={()=>tog(k)}/>}
    </div>
  );
  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'12px 12px 4px' }}>
        <IconBtn icon={<I.chev size={18} style={{ transform:'rotate(180deg)' }}/>} onClick={()=>go('home')} title="Back"/>
        <span style={{ fontFamily:SANS, fontWeight:700, fontSize:15, color:'var(--c1)' }}>Settings</span>
      </div>
      <div style={{ padding:'4px 16px 0' }}>
        <SectionLabel>General</SectionLabel>
        <div style={{ borderTop:'1px solid var(--border-sub)' }}>
          <Row label="Launch dot+ at login" k="login"/>
          <div style={{ borderTop:'1px solid var(--border-sub)' }}/>
          <Row label="Show timer in menu bar" sub="While recording" k="timer"/>
          <div style={{ borderTop:'1px solid var(--border-sub)' }}/>
          <Row label="Global record hotkey" right={<span style={{ display:'flex', gap:3 }}><Key>⌃</Key><Key>⌥</Key><Key>R</Key></span>}/>
        </div>
        <div style={{ height:10 }}/>
        <SectionLabel>Capture</SectionLabel>
        <div style={{ borderTop:'1px solid var(--border-sub)' }}>
          <Row label="Capture system audio" sub="Zoom, Meet, Teams calls" k="sys"/>
          <div style={{ borderTop:'1px solid var(--border-sub)' }}/>
          <Row label="Record mic + system together" k="both"/>
          <div style={{ borderTop:'1px solid var(--border-sub)' }}/>
          <Row label="Auto-record calendar meetings" sub="Asks before each meeting" k="auto"/>
        </div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'14px 16px', marginTop:8, borderTop:'1px solid var(--border-sub)' }}>
        <button onClick={openApp} style={{ display:'flex', alignItems:'center', gap:7, background:'none', border:'none', cursor:'pointer', color:'var(--c2)', fontFamily:SANS, fontSize:12.5, fontWeight:600 }}><I.gear size={16}/> All settings</button>
        <span style={{ flex:1 }}/>
        <button style={{ background:'none', border:'none', cursor:'pointer', color:'var(--c3)', fontFamily:SANS, fontSize:12.5 }}>Quit dot+</button>
      </div>
    </div>
  );
}

function Toggle({ on, onClick }) {
  return (
    <button onClick={onClick} style={{ position:'relative', width:42, height:24, borderRadius:999, border:'none', cursor:'pointer', background: on?'var(--ink-s)':'var(--border)', transition:'background .15s', flexShrink:0 }}>
      <span style={{ position:'absolute', top:2, left:2, width:20, height:20, borderRadius:'50%', background:'var(--s0)', boxShadow:'0 1px 2px rgba(0,0,0,.3)', transform: on?'translateX(18px)':'translateX(0)', transition:'transform .15s' }}/>
    </button>
  );
}

// ── ONBOARDING / PERMISSIONS ───────────────────────────────────────────────────
function Onboarding({ go }) {
  const perms = [
    { icon:<I.mic size={20}/>, label:'Microphone', sub:'Record your voice and in-person meetings', state:'granted' },
    { icon:<I.system size={20}/>, label:'System Audio & Screen', sub:'Capture audio from calls on your Mac', state:'grant' },
    { icon:<I.cal size={20}/>, label:'Calendar', sub:'Know your next meeting, auto-record', state:'grant' },
    { icon:<I.cmd size={20}/>, label:'Accessibility', sub:'Enable the global record hotkey', state:'optional' },
  ];
  return (
    <div style={{ padding:'18px 16px 16px' }}>
      <Monogram size={30}/>
      <h2 style={{ margin:'12px 0 4px', fontFamily:SANS, fontSize:19, fontWeight:700, letterSpacing:'-0.01em', color:'var(--c1)' }}>Welcome to dot+</h2>
      <p style={{ margin:0, fontFamily:SANS, fontSize:13, lineHeight:'19px', color:'var(--c3)' }}>Grant a few permissions and dot+ will live in your menu bar — one click to capture any meeting.</p>
      <div style={{ display:'flex', flexDirection:'column', gap:8, marginTop:16 }}>
        {perms.map((p,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:11, padding:'11px 12px', borderRadius:12, background:'var(--s1)', border:'1px solid var(--border-sub)' }}>
            <span style={{ width:36, height:36, borderRadius:9, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center', background:'var(--s2)', color: p.state==='granted'?'var(--pos)':'var(--c2)' }}>{p.icon}</span>
            <span style={{ flex:1, minWidth:0 }}>
              <span style={{ display:'block', fontFamily:SANS, fontSize:13.5, fontWeight:600, color:'var(--c1)' }}>{p.label}</span>
              <span style={{ display:'block', fontFamily:SANS, fontSize:11.5, color:'var(--c3)', marginTop:1 }}>{p.sub}</span>
            </span>
            {p.state==='granted'
              ? <span style={{ display:'flex', alignItems:'center', gap:5, color:'var(--pos)', fontFamily:SANS, fontSize:12, fontWeight:600 }}><I.check size={16}/> On</span>
              : <Btn variant={p.state==='optional'?'ghost':'secondary'} size="small" shape="pill">{p.state==='optional'?'Later':'Grant'}</Btn>}
          </div>
        ))}
      </div>
      <Btn variant="record" size="large" shape="pill" full onClick={()=>go('home')} style={{ marginTop:16 }}>Continue</Btn>
    </div>
  );
}

// ── ROUTER ─────────────────────────────────────────────────────────────────────
function Popover({ t, screen, go, elapsed, startRec, stopRec, openApp, detached, toggleDetach, width, dragHandlers }) {
  // pass header context to HomeView via t shim
  const tt = { ...t, __detached:detached, __toggleDetach:toggleDetach };
  return (
    <PopShell width={width} detached={detached} dragHandlers={dragHandlers}>
      {/* non-home screens get a header inside their own view; home renders full header */}
      {screen==='home' && <HomeView t={tt} go={go} startRec={startRec} openApp={openApp}/>}
      {screen==='recording' && <RecordingView t={t} elapsed={elapsed} stopRec={stopRec} go={go} detached={detached} toggleDetach={toggleDetach}/>}
      {screen==='processing' && <ProcessingView go={go}/>}
      {screen==='detail' && <DetailView t={t} go={go} openApp={openApp}/>}
      {screen==='ai' && <AiView t={t} go={go}/>}
      {screen==='settings' && <MiniSettings t={t} go={go} openApp={openApp}/>}
      {screen==='onboarding' && <Onboarding go={go}/>}
    </PopShell>
  );
}

Object.assign(window, { Popover, Monogram, RECENTS, LIVE_LINES });
