// recording-results.jsx — dot+ Recording Detail, redesigned
// dot+ Base v1.1 dark tokens. No emoji (per project rule); SF-symbol-style line icons.

const DOT = {
  bg:'#0F0F14', s2:'#18181F', s3:'#222229', s4:'#2A2A33',
  c1:'#FFFFFF', c2:'#C8C8D4', c3:'#6B6B78', cdis:'#3A3A44',
  border:'#2E2E38', borderSub:'#222229',
  info:'#276EF1', pos:'#05944F', warn:'#BB7A00', neg:'#E11900',
};
const MONO = "'JetBrains Mono', ui-monospace, monospace";
const SANS = "'Inter', -apple-system, system-ui, sans-serif";

// speaker avatar palette (identity, not state) — consistent chroma via oklch
const SPK_COLORS = ['#276EF1', '#1F9E6E', '#C2603A', '#8A5CD6'];

// ─────────────────────────────────────────── icons (24-grid, 1.5 stroke)
function Icon({ d, size = 20, stroke = 1.6, fill = 'none', color = 'currentColor', children, vb = 24, style }) {
  return (
    <svg width={size} height={size} viewBox={`0 0 ${vb} ${vb}`} fill={fill} stroke={fill==='none'?color:'none'}
      strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={{ display:'block', flexShrink:0, ...style }}>
      {d ? <path d={d}/> : children}
    </svg>
  );
}
const I = {
  x:        (p)=><Icon {...p}><path d="M6 6l12 12M18 6L6 18"/></Icon>,
  share:    (p)=><Icon {...p}><path d="M12 15V4M8 8l4-4 4 4M5 12v6a2 2 0 002 2h10a2 2 0 002-2v-6"/></Icon>,
  play:     (p)=><Icon fill="currentColor" stroke="none" {...p}><path d="M8 5.5v13l11-6.5z"/></Icon>,
  pause:    (p)=><Icon fill="currentColor" stroke="none" {...p}><path d="M7 5h3.2v14H7zM13.8 5H17v14h-3.2z"/></Icon>,
  cal:      (p)=><Icon {...p}><path d="M7 3v3M17 3v3M4 8h16M5 5h14a1 1 0 011 1v13a1 1 0 01-1 1H5a1 1 0 01-1-1V6a1 1 0 011-1z"/></Icon>,
  clock:    (p)=><Icon {...p}><circle cx="12" cy="12" r="8"/><path d="M12 8v4l2.5 2"/></Icon>,
  pin:      (p)=><Icon {...p}><path d="M12 21s7-5.5 7-11a7 7 0 10-14 0c0 5.5 7 11 7 11z"/><circle cx="12" cy="10" r="2.4"/></Icon>,
  folder:   (p)=><Icon {...p}><path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></Icon>,
  tag:      (p)=><Icon {...p}><path d="M3 3h7l11 11-7 7L3 10z"/><circle cx="7.5" cy="7.5" r="1.4" fill="currentColor" stroke="none"/></Icon>,
  people:   (p)=><Icon {...p}><circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0111 0M16 6.5a3 3 0 010 6M16.5 19a5.5 5.5 0 00-1.8-4.1"/></Icon>,
  chev:     (p)=><Icon stroke={2} {...p}><path d="M9 6l6 6-6 6"/></Icon>,
  check:    (p)=><Icon stroke={2.2} {...p}><path d="M5 12.5l4.5 4.5L19 6.5"/></Icon>,
  sparkles: (p)=><Icon fill="currentColor" stroke="none" {...p}><path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6zM18.5 13l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"/></Icon>,
  copy:     (p)=><Icon {...p}><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 00-2-2H6a2 2 0 00-2 2v8a2 2 0 002 2h2"/></Icon>,
  doc:      (p)=><Icon {...p}><path d="M7 3h7l5 5v13a0 0 0 010 0H7a1 1 0 01-1-1V4a1 1 0 011-1z"/><path d="M14 3v5h5"/></Icon>,
  star:     (p)=><Icon fill="currentColor" stroke="none" {...p}><path d="M12 4l2.3 5.2 5.7.5-4.3 3.8 1.3 5.6L12 16.9 7 18.9l1.3-5.6L4 9.7l5.7-.5z"/></Icon>,
  circle:   (p)=><Icon {...p}><circle cx="12" cy="12" r="8"/></Icon>,
  checkfill:(p)=><Icon fill="currentColor" stroke="none" {...p}><path d="M12 2a10 10 0 100 20 10 10 0 000-20zm-1 14.5l-4-4 1.4-1.4 2.6 2.6 5-5L17.4 9z"/></Icon>,
  plus:     (p)=><Icon {...p}><circle cx="12" cy="12" r="8.5"/><path d="M12 8.5v7M8.5 12h7"/></Icon>,
  addperson:(p)=><Icon {...p}><circle cx="9.5" cy="8" r="3"/><path d="M3.5 19a6 6 0 0112 0M18 7v6M15 10h6"/></Icon>,
  pencil:   (p)=><Icon {...p}><path d="M15.5 5.5l3 3M4 20l1-4L16 5a1.5 1.5 0 013 0l0 0a1.5 1.5 0 010 2L8 18z"/></Icon>,
  sliders:  (p)=><Icon {...p}><path d="M4 8h8M16 8h4M4 16h4M12 16h8"/><circle cx="14" cy="8" r="2.3"/><circle cx="10" cy="16" r="2.3"/></Icon>,
  wave:     (p)=><Icon stroke={1.8} {...p}><path d="M4 12h2M9 7v10M14 9v6M19 11v2"/></Icon>,
};

const fmtInitial = (n) => n.trim().charAt(0).toUpperCase();

// collapsed-summary atoms
function SummaryChip({ icon, text, set, dot }) {
  return (
    <span style={{ display:'flex', alignItems:'center', gap:6, minWidth:0, flex:'0 1 auto' }}>
      <span style={{ color: set?DOT.c3:DOT.cdis, display:'flex', flexShrink:0 }}>{icon}</span>
      {dot && <span style={{ width:7, height:7, borderRadius:2, background:dot, flexShrink:0 }}/>}
      <span style={{ fontFamily:SANS, fontSize:14, fontWeight:500, color: set?DOT.c1:DOT.c3,
        whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth:0 }}>{text}</span>
    </span>
  );
}
const SumDot = () => <span style={{ width:3, height:3, borderRadius:'50%', background:DOT.cdis, flexShrink:0 }}/>;

// ─────────────────────────────────────────── shared atoms
function Avatar({ name, idx, size = 32, mono, ring }) {
  const color = mono ? DOT.s4 : SPK_COLORS[idx % SPK_COLORS.length];
  const named = !!name;
  return (
    <div style={{
      width:size, height:size, borderRadius:'50%', flexShrink:0,
      background: named ? color : 'transparent',
      border: named ? 'none' : `1.5px dashed ${DOT.border}`,
      boxShadow: ring ? `0 0 0 2px ${DOT.bg}` : 'none',
      display:'flex', alignItems:'center', justifyContent:'center',
      color: mono ? DOT.c2 : '#fff', fontFamily:SANS, fontWeight:600,
      fontSize: size*0.42, letterSpacing:'-0.01em',
    }}>
      {named ? fmtInitial(name) : <span style={{color:DOT.c3, fontSize:size*0.5, fontWeight:500}}>?</span>}
    </div>
  );
}

// ─────────────────────────────────────────── audio player
function Player() {
  const [playing, setPlaying] = React.useState(false);
  const [t, setT] = React.useState(0);
  const total = 19;
  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setT(p => { if (p >= total) { setPlaying(false); return total; } return p + 0.25; }), 250);
    return () => clearInterval(id);
  }, [playing]);
  const mmss = (s) => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(Math.floor(s%60)).padStart(2,'0')}`;
  const pct = (t/total)*100;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:14, background:DOT.s2, borderRadius:12, padding:'12px 14px' }}>
      <button onClick={()=>{ if(t>=total) setT(0); setPlaying(p=>!p); }} style={{
        width:44, height:44, borderRadius:'50%', border:'none', background:DOT.s3, color:DOT.c1,
        display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0,
      }}>
        {playing ? <I.pause size={20}/> : <I.play size={20} style={{marginLeft:2}}/>}
      </button>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ height:4, borderRadius:2, background:DOT.s3, position:'relative', overflow:'hidden' }}>
          <div style={{ position:'absolute', inset:0, width:`${pct}%`, background:DOT.c1, borderRadius:2 }}/>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', marginTop:8, fontFamily:MONO, fontSize:11, color:DOT.c3 }}>
          <span>{mmss(t)}</span><span>{mmss(total)}</span>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────── organize disclosure row
function OrgRow({ icon, label, children, onClick, last }) {
  return (
    <button onClick={onClick} style={{
      width:'100%', display:'flex', alignItems:'center', gap:12, background:'transparent', border:'none',
      padding:'14px 14px', cursor:'pointer', textAlign:'left', position:'relative',
      borderBottom: last ? 'none' : `1px solid ${DOT.borderSub}`,
    }}>
      <span style={{ color:DOT.c3, display:'flex' }}>{icon}</span>
      <span style={{ color:DOT.c2, fontFamily:SANS, fontSize:15, fontWeight:500, flexShrink:0 }}>{label}</span>
      <span style={{ flex:1, display:'flex', justifyContent:'flex-end', alignItems:'center', gap:8, minWidth:0 }}>
        {children}
      </span>
      <I.chev size={16} color={DOT.c3} style={{opacity:.7}}/>
    </button>
  );
}

// ─────────────────────────────────────────── tabs
function Tabs({ active, onChange }) {
  const tabs = ['Summary','Transcript','Key Points','Next Steps'];
  return (
    <div style={{ display:'flex', gap:20, borderBottom:`1px solid ${DOT.borderSub}`, padding:'0 16px' }}>
      {tabs.map(tb => {
        const on = active === tb;
        return (
          <button key={tb} onClick={()=>onChange(tb)} style={{
            background:'none', border:'none', cursor:'pointer', padding:'0 0 12px', position:'relative',
            fontFamily:SANS, fontSize:15, fontWeight:on?600:500, color:on?DOT.c1:DOT.c3,
          }}>
            {tb}
            {on && <span style={{ position:'absolute', left:0, right:0, bottom:-1, height:2, background:DOT.c1, borderRadius:2 }}/>}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────── tab content
function Card({ children, pad = 16 }) {
  return <div style={{ background:DOT.s2, borderRadius:12, padding:pad }}>{children}</div>;
}
function CardHead({ icon, label, color }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
      <span style={{ color: color||DOT.c3, display:'flex' }}>{icon}</span>
      <span style={{ fontFamily:SANS, fontSize:13, fontWeight:600, color:DOT.c2 }}>{label}</span>
      <span style={{ flex:1 }}/>
      <I.copy size={18} color={DOT.c3}/>
    </div>
  );
}

function SummaryTab({ meeting }) {
  return (
    <Card>
      <CardHead icon={<I.sparkles size={16}/>} label="AI Summary" color={DOT.info}/>
      <p style={{ margin:0, fontFamily:SANS, fontSize:15, lineHeight:'24px', color:DOT.c1 }}>
        The speaker is conducting a microphone test, checking the recording process, and contemplating whether to change colors, indicating dissatisfaction with the current ones.
      </p>
    </Card>
  );
}
function TranscriptTab({ speakers, segments }) {
  return (
    <Card>
      <CardHead icon={<I.doc size={16}/>} label="Full Transcript"/>
      <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
        {segments.map((s,i) => {
          const spk = speakers.find(x=>x.id===s.spk);
          return (
            <div key={i} style={{ display:'flex', gap:10 }}>
              <Avatar name={spk.name} idx={spk.idx} size={26} />
              <div style={{ flex:1 }}>
                <div style={{ fontFamily:SANS, fontSize:13, fontWeight:600, color: spk.name ? SPK_COLORS[spk.idx%4] : DOT.c2, marginBottom:2 }}>
                  {spk.name || spk.label}
                </div>
                <div style={{ fontFamily:SANS, fontSize:15, lineHeight:'22px', color:DOT.c1 }}>{s.text}</div>
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}
function KeyPointsTab() {
  const pts = ['Microphone and recording pipeline confirmed working.','Current color palette feels off and may be revised.','Decision on new colors deferred to a follow-up review.'];
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
      {pts.map((p,i)=>(
        <div key={i} style={{ background:DOT.s2, borderRadius:12, padding:14, display:'flex', gap:12, alignItems:'flex-start' }}>
          <span style={{ color:DOT.warn, marginTop:2 }}><I.star size={13}/></span>
          <span style={{ fontFamily:SANS, fontSize:15, lineHeight:'22px', color:DOT.c1 }}>{p}</span>
        </div>
      ))}
    </div>
  );
}
function NextStepsTab() {
  const [items, setItems] = React.useState([
    { t:'Pick a revised color palette', o:'Verónica', done:false },
    { t:'Re-run a longer recording test', o:'You', done:true },
  ]);
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
      {items.map((it,i)=>(
        <button key={i} onClick={()=>setItems(a=>a.map((x,j)=>j===i?{...x,done:!x.done}:x))} style={{
          background:DOT.s2, border:'none', borderRadius:12, padding:14, display:'flex', gap:12, alignItems:'center',
          cursor:'pointer', textAlign:'left', width:'100%',
        }}>
          <span style={{ color: it.done?DOT.pos:DOT.c3, display:'flex' }}>{it.done?<I.checkfill size={22}/>:<I.circle size={22}/>}</span>
          <span style={{ flex:1 }}>
            <span style={{ display:'block', fontFamily:SANS, fontSize:15, fontWeight:600, color: it.done?DOT.c3:DOT.c1, textDecoration: it.done?'line-through':'none' }}>{it.t}</span>
            <span style={{ display:'block', fontFamily:MONO, fontSize:11, color:DOT.c3, marginTop:2 }}>@{it.o}</span>
          </span>
        </button>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────── bottom sheet shell
function Sheet({ open, title, onClose, children, height }) {
  return (
    <div style={{ position:'absolute', inset:0, zIndex:40, pointerEvents: open?'auto':'none' }}>
      <div onClick={onClose} style={{ position:'absolute', inset:0, background:'rgba(5,5,10,0.6)', opacity: open?1:0, transition:'opacity .28s ease' }}/>
      <div style={{
        position:'absolute', left:0, right:0, bottom:0, background:DOT.bg,
        borderTopLeftRadius:16, borderTopRightRadius:16, borderTop:`1px solid ${DOT.border}`,
        transform: open?'translateY(0)':'translateY(100%)', transition:'transform .3s cubic-bezier(.32,.72,0,1)',
        maxHeight:'88%', height, display:'flex', flexDirection:'column', overflow:'hidden',
        boxShadow:'0 -12px 40px rgba(0,0,0,0.5)',
      }}>
        <div style={{ padding:'10px 0 6px', display:'flex', justifyContent:'center' }}>
          <div style={{ width:36, height:5, borderRadius:3, background:DOT.s4 }}/>
        </div>
        <div style={{ display:'flex', alignItems:'center', padding:'4px 16px 12px', borderBottom:`1px solid ${DOT.borderSub}` }}>
          <span style={{ fontFamily:SANS, fontSize:17, fontWeight:700, color:DOT.c1 }}>{title}</span>
          <span style={{ flex:1 }}/>
          <button onClick={onClose} style={{ width:30, height:30, borderRadius:'50%', border:`1px solid ${DOT.border}`, background:'transparent', color:DOT.c2, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
            <I.x size={15}/>
          </button>
        </div>
        <div style={{ overflowY:'auto', padding:'8px 16px 28px', flex:1 }}>{children}</div>
      </div>
    </div>
  );
}

function PickRow({ icon, iconBg, title, sub, selected, onClick, last }) {
  return (
    <button onClick={onClick} style={{
      width:'100%', display:'flex', alignItems:'center', gap:12, background:'transparent', border:'none',
      padding:'13px 4px', cursor:'pointer', textAlign:'left',
      borderBottom: last?'none':`1px solid ${DOT.borderSub}`,
    }}>
      {icon && <span style={{ width:34, height:34, borderRadius:8, background:iconBg||DOT.s3, display:'flex', alignItems:'center', justifyContent:'center', color:DOT.c1, flexShrink:0 }}>{icon}</span>}
      <span style={{ flex:1, minWidth:0 }}>
        <span style={{ display:'block', fontFamily:SANS, fontSize:15, fontWeight:500, color:DOT.c1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{title}</span>
        {sub && <span style={{ display:'block', fontFamily:SANS, fontSize:12, color:DOT.c3, marginTop:1 }}>{sub}</span>}
      </span>
      {selected && <span style={{ color:DOT.info }}><I.checkfill size={20}/></span>}
    </button>
  );
}
function SectionLabel({ children }) {
  return <div style={{ fontFamily:SANS, fontSize:11, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', color:DOT.c3, padding:'18px 4px 8px' }}>{children}</div>;
}

// ─────────────────────────────────────────── ORIGINAL (before) header
function CarouselBefore({ meeting }) {
  const pill = (icon, text, action) => (
    <div style={{
      display:'inline-flex', alignItems:'center', gap:6, flexShrink:0,
      padding:'8px 12px', borderRadius:8, whiteSpace:'nowrap',
      background: action?DOT.s3:DOT.s2, color: action?DOT.c1:DOT.c2,
      fontFamily:MONO, fontSize:12,
    }}>{icon}{text}</div>
  );
  return (
    <div style={{ display:'flex', gap:12, overflowX:'auto', padding:'0 16px 4px', WebkitOverflowScrolling:'touch' }}>
      {pill(<I.cal size={14}/>, 'Jun 26, 2026 at 4:03 PM')}
      {pill(<I.clock size={14}/>, '00:18')}
      {pill(<I.people size={14}/>, '2 Speakers')}
      {pill(<I.folder size={14} color={DOT.c3}/>, <span style={{color:DOT.c3}}>Add to Project</span>, true)}
      {pill(<I.tag size={14} color={DOT.c3}/>, <span style={{color:DOT.c3}}>Set Category</span>, true)}
      {pill(<I.pin size={14}/>, 'Verónica', true)}
    </div>
  );
}

// ─────────────────────────────────────────── main screen
function RecordingScreen({ t }) {
  const before = t.view === 'Before';
  const mono = t.speakerColor === 'Mono';

  const FOLDERS = [
    { id:'aprocap', name:'APROCAP', sub:'Client work · 12', color:'#276EF1', icon:<I.folder size={18}/> },
    { id:'q3', name:'Q3 Launch', sub:'8 recordings', color:'#1F9E6E', icon:<I.folder size={18}/> },
    { id:'personal', name:'Personal', sub:'3 recordings', color:'#C2603A', icon:<I.folder size={18}/> },
  ];
  const CONTACTS = [
    { id:'vero', name:'Verónica Salas', sub:'Xhinola · Design Lead' },
    { id:'rod', name:'Rodrigo Arvizu', sub:'Xhinola · Engineering' },
    { id:'maya', name:'Maya Chen', sub:'Product' },
  ];
  const CATS = [
    { persona:'General Purpose', icon:<I.doc size={16}/>, items:[{id:'gen', name:'General Meeting', icon:<I.doc size={18}/>}] },
    { persona:'Developer / Tech', icon:<I.wave size={16}/>, items:[
      {id:'standup', name:'Standup', icon:<I.clock size={18}/>},
      {id:'bug', name:'Bug Report', icon:<I.tag size={18}/>},
      {id:'feature', name:'New Feature', icon:<I.sparkles size={18}/>},
    ]},
    { persona:'Creative / Other', icon:<I.star size={16}/>, items:[{id:'casual', name:'Casual Chat', icon:<I.star size={18}/>}] },
  ];

  const [tab, setTab] = React.useState('Summary');
  const [folder, setFolder] = React.useState('aprocap');
  const [catId, setCatId] = React.useState(null);
  const [speakers, setSpeakers] = React.useState([
    { id:'s1', idx:0, label:'Speaker 1', name: t.named?'Verónica':null },
    { id:'s2', idx:1, label:'Speaker 2', name: t.named?'You':null },
  ]);
  React.useEffect(()=>{ // react to "named speakers" tweak
    setSpeakers([
      { id:'s1', idx:0, label:'Speaker 1', name: t.named?'Verónica':null },
      { id:'s2', idx:1, label:'Speaker 2', name: t.named?'You':null },
    ]);
  }, [t.named]);

  const segments = [
    { spk:'s1', text:'Okay, testing one two — is this picking up? Looks like the levels are good.' },
    { spk:'s2', text:'Yeah it sounds clean. Recording is running.' },
    { spk:'s1', text:"I'm not sure about these colors though. They feel a little off to me." },
  ];

  const [sheet, setSheet] = React.useState(null); // 'folder' | 'category' | 'speakers' | 'assign'
  const [assignId, setAssignId] = React.useState(null);
  const [orgOpen, setOrgOpen] = React.useState(false); // organize: collapsed summary vs edit rows

  const cat = CATS.flatMap(c=>c.items).find(c=>c.id===catId);
  const fol = FOLDERS.find(f=>f.id===folder);
  const namedCount = speakers.filter(s=>s.name).length;

  return (
    <div style={{ position:'relative', height:'100%', background:DOT.bg, overflow:'hidden' }}>
      {/* scroll area */}
      <div style={{ height:'100%', overflowY:'auto', paddingTop:54, paddingBottom:30 }}>
        {/* nav */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 16px 6px' }}>
          <button style={btn}><I.x size={16} color={DOT.c2}/></button>
          <button style={btn}><I.share size={16} color={DOT.c2}/></button>
        </div>

        {/* title */}
        <h1 style={{ margin:'2px 16px 10px', fontFamily:SANS, fontSize:22, fontWeight:700, lineHeight:'28px', color:DOT.c1, letterSpacing:'-0.01em' }}>
          Anualidad + Web APROCAP
        </h1>

        {before ? (
          <div style={{ marginBottom:16 }}><CarouselBefore/></div>
        ) : (
          /* quiet metadata line — facts, not buttons */
          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'0 16px 16px', minWidth:0 }}>
            <span style={metaTxt}><I.cal size={13} color={DOT.c3}/> Jun 26, 2026 · 5:57 PM</span>
            <span style={{color:DOT.cdis}}>·</span>
            <span style={metaTxt}><I.clock size={13} color={DOT.c3}/> 0:02</span>
            <span style={{color:DOT.cdis}}>·</span>
            <span style={{ ...metaTxt, minWidth:0, flex:'0 1 auto' }}>
              <I.pin size={13} color={DOT.c3}/>
              <span style={{ whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Higüey, La Altagracia</span>
            </span>
          </div>
        )}

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

        {/* organize — collapsed summary (default) or expanded edit rows */}
        {!before && (
          <div style={{ padding:'0 16px 20px' }}>
            {!orgOpen ? (
              <button onClick={()=>setOrgOpen(true)} style={{
                width:'100%', display:'flex', alignItems:'center', gap:10, background:DOT.s2, border:'none',
                borderRadius:12, padding:'13px 12px 13px 14px', cursor:'pointer', textAlign:'left',
              }}>
                {/* truncating zone: folder + category */}
                <div style={{ flex:1, minWidth:0, display:'flex', alignItems:'center', gap:9, overflow:'hidden' }}>
                  <SummaryChip icon={<I.folder size={15}/>} set={!!fol}
                    dot={fol&&fol.color} text={fol?fol.name:'Project'}/>
                  <SumDot/>
                  <SummaryChip icon={<I.tag size={15}/>} set={!!cat} text={cat?cat.name:'Category'}/>
                </div>
                {/* fixed zone: avatars + expand affordance, never clip */}
                <span style={{ display:'flex', alignItems:'center', flexShrink:0 }}>
                  {speakers.map((s,i)=>(
                    <span key={s.id} style={{ marginLeft:i?-7:0 }}>
                      <Avatar name={s.name} idx={s.idx} size={24} mono={mono} ring/>
                    </span>
                  ))}
                  {namedCount>0 && (
                    <span style={{ marginLeft:8, fontFamily:SANS, fontSize:13, fontWeight:500, color:DOT.c2, whiteSpace:'nowrap' }}>
                      {namedCount===speakers.length ? 'Named' : `${namedCount} named`}
                    </span>
                  )}
                </span>
                <span style={{ width:30, height:30, borderRadius:8, background:DOT.s3, color:DOT.c2, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <I.sliders size={17}/>
                </span>
              </button>
            ) : (
              <div>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 2px 8px' }}>
                  <span style={{ fontFamily:SANS, fontSize:11, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', color:DOT.c3 }}>Details</span>
                  <button onClick={()=>setOrgOpen(false)} style={{
                    display:'flex', alignItems:'center', gap:5, background:'transparent', border:'none', cursor:'pointer',
                    color:DOT.info, fontFamily:SANS, fontSize:13, fontWeight:600,
                  }}>Done <I.chev size={14} style={{transform:'rotate(-90deg)'}}/></button>
                </div>
                <div style={{ background:DOT.s2, borderRadius:12, overflow:'hidden' }}>
                  <OrgRow icon={<I.folder size={19}/>} label="Project" onClick={()=>setSheet('folder')}>
                    {fol
                      ? <span style={valTxt}><span style={{width:8,height:8,borderRadius:2,background:fol.color}}/>{fol.name}</span>
                      : <span style={{...valTxt, color:DOT.c3}}>None</span>}
                  </OrgRow>
                  <OrgRow icon={<I.tag size={19}/>} label="Category" onClick={()=>setSheet('category')}>
                    {cat
                      ? <span style={valTxt}>{cat.name}</span>
                      : <span style={{...valTxt, color:DOT.c3}}>None</span>}
                  </OrgRow>
                  <OrgRow icon={<I.people size={19}/>} label="Speakers" onClick={()=>setSheet('speakers')} last>
                    <span style={{ display:'flex', alignItems:'center' }}>
                      {speakers.map((s,i)=>(
                        <span key={s.id} style={{ marginLeft: i?-8:0 }}>
                          <Avatar name={s.name} idx={s.idx} size={26} mono={mono} ring/>
                        </span>
                      ))}
                      <span style={{ ...valTxt, marginLeft:10, color: namedCount?DOT.c2:DOT.c3 }}>
                        {namedCount===speakers.length ? 'Named' : namedCount? `${namedCount} named` : 'Tap to name'}
                      </span>
                    </span>
                  </OrgRow>
                </div>
              </div>
            )}
          </div>
        )}

        {/* tabs */}
        <div style={{ marginBottom:16 }}><Tabs active={tab} onChange={setTab}/></div>

        {/* content */}
        <div style={{ padding:'0 16px' }}>
          {tab==='Summary'    && <SummaryTab/>}
          {tab==='Transcript' && <TranscriptTab speakers={speakers} segments={segments}/>}
          {tab==='Key Points' && <KeyPointsTab/>}
          {tab==='Next Steps' && <NextStepsTab/>}
        </div>
      </div>

      {/* ── sheets ── */}
      <Sheet open={sheet==='folder'} title="Add to Project" onClose={()=>setSheet(null)}>
        <PickRow title="None" selected={!folder} onClick={()=>{setFolder(null); setSheet(null);}}/>
        <SectionLabel>Your projects</SectionLabel>
        {FOLDERS.map((f,i)=>(
          <PickRow key={f.id} icon={f.icon} iconBg={f.color} title={f.name} sub={f.sub}
            selected={folder===f.id} onClick={()=>{setFolder(f.id); setSheet(null);}} last={i===FOLDERS.length-1}/>
        ))}
      </Sheet>

      <Sheet open={sheet==='category'} title="Set Category" onClose={()=>setSheet(null)}>
        <PickRow title="None" selected={!catId} onClick={()=>{setCatId(null); setSheet(null);}}/>
        {CATS.map(group=>(
          <div key={group.persona}>
            <SectionLabel>{group.persona}</SectionLabel>
            {group.items.map((c,i)=>(
              <PickRow key={c.id} icon={c.icon} title={c.name}
                selected={catId===c.id} onClick={()=>{setCatId(c.id); setSheet(null);}} last={i===group.items.length-1}/>
            ))}
          </div>
        ))}
      </Sheet>

      <Sheet open={sheet==='speakers'} title="Speakers" onClose={()=>setSheet(null)}>
        <p style={{ margin:'4px 4px 6px', fontFamily:SANS, fontSize:13, color:DOT.c3, lineHeight:'18px' }}>
          {namedCount} of {speakers.length} identified. Tap a speaker to link them to a contact — names update across the transcript.
        </p>
        {speakers.map((s)=>{
          const sample = segments.find(g=>g.spk===s.id);
          return (
            <button key={s.id} onClick={()=>{ setAssignId(s.id); setSheet('assign'); }} style={{
              width:'100%', display:'flex', alignItems:'center', gap:12, background:DOT.s2, border:'none',
              borderRadius:12, padding:14, marginTop:10, cursor:'pointer', textAlign:'left',
            }}>
              <Avatar name={s.name} idx={s.idx} size={40} mono={mono}/>
              <span style={{ flex:1, minWidth:0 }}>
                <span style={{ display:'flex', alignItems:'center', gap:7 }}>
                  <span style={{ fontFamily:SANS, fontSize:15, fontWeight:600, color:DOT.c1 }}>{s.name||s.label}</span>
                  {!s.name && <span style={{ fontFamily:SANS, fontSize:11, fontWeight:600, color:DOT.info, background:'rgba(39,110,241,0.16)', padding:'2px 7px', borderRadius:5 }}>Unnamed</span>}
                </span>
                {sample && <span style={{ display:'block', fontFamily:SANS, fontSize:13, color:DOT.c3, marginTop:3, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>“{sample.text}”</span>}
              </span>
              <span style={{ color:DOT.info, display:'flex', alignItems:'center', gap:4, fontFamily:SANS, fontSize:13, fontWeight:600, flexShrink:0 }}>
                {s.name ? <I.pencil size={17}/> : <>Assign <I.chev size={15}/></>}
              </span>
            </button>
          );
        })}
      </Sheet>

      <Sheet open={sheet==='assign'} title={`Who is ${speakers.find(s=>s.id===assignId)?.name || speakers.find(s=>s.id===assignId)?.label || ''}?`} onClose={()=>setSheet('speakers')}>
        <PickRow icon={<I.addperson size={18}/>} iconBg="rgba(39,110,241,0.18)" title="Import from Contacts" onClick={()=>setSheet('speakers')}/>
        <PickRow icon={<I.plus size={18}/>} iconBg="rgba(39,110,241,0.18)" title="Create new contact" onClick={()=>setSheet('speakers')} last/>
        <SectionLabel>Saved contacts</SectionLabel>
        {CONTACTS.map((c,i)=>(
          <PickRow key={c.id}
            icon={<span style={{fontFamily:SANS,fontWeight:600,color:'#fff'}}>{fmtInitial(c.name)}</span>}
            iconBg={SPK_COLORS[i%4]} title={c.name} sub={c.sub} last={i===CONTACTS.length-1}
            onClick={()=>{
              setSpeakers(arr=>arr.map(s=>s.id===assignId?{...s, name:c.name.split(' ')[0]}:s));
              setSheet('speakers');
            }}/>
        ))}
      </Sheet>
    </div>
  );
}

const btn = { width:36, height:36, borderRadius:'50%', border:`1px solid ${DOT.border}`, background:'transparent', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' };
const metaTxt = { display:'inline-flex', alignItems:'center', gap:5, fontFamily:MONO, fontSize:12, color:DOT.c2, whiteSpace:'nowrap', flexShrink:0 };
const valTxt = { display:'inline-flex', alignItems:'center', gap:7, fontFamily:SANS, fontSize:15, fontWeight:500, color:DOT.c1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', maxWidth:170 };

// ─────────────────────────────────────────── app + tweaks
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "view": "After",
  "speakerColor": "Color",
  "named": false
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:'24px' }}>
      <IOSDevice dark width={390} height={844}>
        <RecordingScreen t={t}/>
      </IOSDevice>
      <TweaksPanel>
        <TweakSection label="Compare"/>
        <TweakRadio label="Header" value={t.view} options={['Before','After']} onChange={v=>setTweak('view', v)}/>
        <TweakSection label="Speakers"/>
        <TweakRadio label="Avatars" value={t.speakerColor} options={['Color','Mono']} onChange={v=>setTweak('speakerColor', v)}/>
        <TweakToggle label="Preview named" value={t.named} onChange={v=>setTweak('named', v)}/>
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
