// template-store.jsx — dot+ Template Store (browse + detail sheet)
// Matches the shipped Recording Detail brand: dark, mono metadata, radius-12 cards,
// circle nav buttons, white used sparingly. No emoji (project rule); SF-symbol line icons.

const TS = {
  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 TS_MONO = "'JetBrains Mono', ui-monospace, monospace";
const TS_SANS = "'Inter', -apple-system, system-ui, sans-serif";

// ─────────────────────────────────────────── icons (24-grid, 1.5 stroke)
function TIcon({ size = 22, stroke = 1.6, fill = 'none', color = 'currentColor', children, style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill}
      stroke={fill === 'none' ? color : 'none'} strokeWidth={stroke}
      strokeLinecap="round" strokeLinejoin="round"
      style={{ display: 'block', flexShrink: 0, ...style }}>
      {children}
    </svg>
  );
}
const TI = {
  search:  (p) => <TIcon {...p}><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></TIcon>,
  plus:    (p) => <TIcon {...p}><path d="M12 5v14M5 12h14"/></TIcon>,
  check:   (p) => <TIcon stroke={2.2} {...p}><path d="M5 12.5l4.5 4.5L19 6.5"/></TIcon>,
  checkfill:(p)=> <TIcon 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"/></TIcon>,
  chev:    (p) => <TIcon stroke={2} {...p}><path d="M9 6l6 6-6 6"/></TIcon>,
  back:    (p) => <TIcon stroke={2} {...p}><path d="M15 6l-6 6 6 6"/></TIcon>,
  x:       (p) => <TIcon stroke={2} {...p}><path d="M6 6l12 12M18 6L6 18"/></TIcon>,
  saved:   (p) => <TIcon {...p}><path d="M6 3h12a1 1 0 011 1v17l-7-4-7 4V4a1 1 0 011-1z"/></TIcon>,
  sparkle: (p) => <TIcon 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.6z"/></TIcon>,
  // template glyphs
  sales:   (p) => <TIcon {...p}><path d="M4 20h16M7 20v-6M12 20V9M17 20v-9M6 9l5-4 3 2 5-4"/></TIcon>,
  medical: (p) => <TIcon {...p}><path d="M3 12h4l2 5 4-12 2 7h6"/></TIcon>,
  eng:     (p) => <TIcon {...p}><path d="M12 3l9 16H3z"/><path d="M12 10v4"/><circle cx="12" cy="16.5" r="0.6" fill="currentColor" stroke="none"/></TIcon>,
  people:  (p) => <TIcon {...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"/></TIcon>,
  edu:     (p) => <TIcon {...p}><path d="M12 4L2 9l10 5 8-4v6"/><path d="M6 11.5V16c0 1.1 2.7 3 6 3s6-1.9 6-3v-4.5"/></TIcon>,
  legal:   (p) => <TIcon {...p}><path d="M12 3v18M6 21h12M5 7h14M8 7l-4 7a3 3 0 006 0zM16 7l-4 7a3 3 0 006 0z"/></TIcon>,
  research:(p) => <TIcon {...p}><circle cx="10.5" cy="10.5" r="6.5"/><path d="M15.5 15.5L20 20M8 10.5h5M10.5 8v5"/></TIcon>,
};

// ─────────────────────────────────────────── data
const CATS = [
  { id:'all', label:'All' }, { id:'sales', label:'Sales' }, { id:'medical', label:'Medical' },
  { id:'eng', label:'Engineering' }, { id:'personal', label:'Personal' },
  { id:'research', label:'Research' }, { id:'edu', label:'Education' }, { id:'legal', label:'Legal' },
];

const TEMPLATES = [
  { id:'sales_discovery_bant', cat:'sales', icon:TI.sales, title:'Sales Discovery',
    desc:'Extract BANT criteria from a prospect call.', tags:['bant','qualifying','crm'],
    fields:['Budget','Authority','Need','Timeline','Next steps'] },
  { id:'medical_soap', cat:'medical', icon:TI.medical, title:'Medical SOAP Note',
    desc:'Structure a patient visit into S / O / A / P.', tags:['clinical','soap','ehr'],
    fields:['Subjective','Objective','Assessment','Plan'] },
  { id:'incident_triage', cat:'eng', icon:TI.eng, title:'Incident Triage',
    desc:'Turn an incident call into a timeline and actions.', tags:['on-call','sev','postmortem'],
    fields:['Impact','Timeline','Root cause','Action items'] },
  { id:'one_on_one', cat:'personal', icon:TI.people, title:'1:1 Sync',
    desc:'Capture talking points, blockers, and follow-ups.', tags:['manager','follow-up'],
    fields:['Wins','Blockers','Feedback','Follow-ups'] },
  { id:'user_interview', cat:'research', icon:TI.research, title:'User Interview',
    desc:'Distill research calls into insights and quotes.', tags:['ux','quotes','insights'],
    fields:['Goals','Pain points','Key quotes','Opportunities'] },
  { id:'lecture_notes', cat:'edu', icon:TI.edu, title:'Lecture Notes',
    desc:'Summarize a lecture into concepts and study Qs.', tags:['study','concepts'],
    fields:['Key concepts','Definitions','Examples','Study questions'] },
  { id:'standup', cat:'eng', icon:TI.eng, title:'Daily Standup',
    desc:'Yesterday / today / blockers per speaker.', tags:['scrum','async'],
    fields:['Yesterday','Today','Blockers'] },
  { id:'deposition', cat:'legal', icon:TI.legal, title:'Deposition Summary',
    desc:'Condense testimony into facts and citations.', tags:['litigation','citations'],
    fields:['Parties','Key testimony','Exhibits','Follow-up'] },
];

// ─────────────────────────────────────────── atoms
function CircleBtn({ icon, onClick }) {
  return (
    <button onClick={onClick} style={{
      width:40, height:40, borderRadius:'50%', flexShrink:0,
      background:TS.s2, border:`1px solid ${TS.border}`, cursor:'default',
      display:'flex', alignItems:'center', justifyContent:'center', color:TS.c2,
    }}>{icon}</button>
  );
}

function Pill({ active, children, onClick }) {
  return (
    <button onClick={onClick} style={{
      height:32, padding:'0 14px', borderRadius:999, border:'none', cursor:'default', flexShrink:0,
      background: active ? TS.c1 : TS.s3, color: active ? '#000' : TS.c2,
      fontFamily:TS_SANS, fontSize:13, fontWeight:600, letterSpacing:'-0.01em',
      transition:'background .15s, color .15s',
    }}>{children}</button>
  );
}

function Tag({ children, onClick, active }) {
  return (
    <span onClick={onClick} style={{
      display:'inline-flex', alignItems:'center', height:20, padding:'0 7px', borderRadius:4, cursor:'default',
      background: active ? 'rgba(39,110,241,0.16)' : TS.s3, color: active ? TS.info : TS.c2,
      fontFamily:TS_MONO, fontSize:10.5, lineHeight:1, whiteSpace:'nowrap',
    }}>{onClick && <span style={{ opacity:.6, marginRight:1 }}>#</span>}{children}</span>
  );
}

function IconTile({ icon, size = 40, r = 10, tint }) {
  return (
    <div style={{ width:size, height:size, borderRadius:r, flexShrink:0, background:tint||TS.s3,
      display:'flex', alignItems:'center', justifyContent:'center' }}>
      {icon({ size:size*0.5, stroke:1.7, color:TS.c1 })}
    </div>
  );
}

// small, restrained add control (top-right of card) — not a white block
function AddDot({ added, onClick }) {
  return (
    <button onClick={onClick} style={{
      width:30, height:30, borderRadius:'50%', border: added?'none':`1px solid ${TS.border}`,
      background: added ? 'rgba(5,148,79,0.16)' : 'transparent', cursor:'default', flexShrink:0,
      display:'flex', alignItems:'center', justifyContent:'center', transition:'.15s',
    }}>
      {added ? TI.check({ size:16, stroke:2.4, color:TS.pos }) : TI.plus({ size:16, stroke:2, color:TS.c2 })}
    </button>
  );
}

// ─────────────────────────────────────────── list row (text-first, no per-row icon)
function TemplateRow({ t, added, onAdd, onOpen, onTag, activeTag, last }) {
  return (
    <div onClick={onOpen} style={{
      display:'flex', alignItems:'center', gap:12, padding:'13px 15px', cursor:'default',
      borderBottom: last ? 'none' : `1px solid ${TS.borderSub}`,
    }}>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', alignItems:'center', gap:7, minWidth:0 }}>
          <span style={{ fontFamily:TS_SANS, fontSize:15, fontWeight:600, color: added?TS.c2:TS.c1,
            letterSpacing:'-0.01em', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{t.title}</span>
          {added && <span style={{ color:TS.pos, display:'flex', flexShrink:0 }}>{TI.checkfill({ size:15 })}</span>}
        </div>
        <div style={{ fontFamily:TS_SANS, fontSize:12.5, lineHeight:1.4, color:TS.c3, marginTop:3,
          whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{t.desc}</div>
        <div style={{ display:'flex', gap:5, marginTop:8 }}>
          {t.tags.slice(0,3).map(tg => (
            <Tag key={tg} active={tg===activeTag} onClick={(e)=>{ e.stopPropagation(); onTag(tg); }}>{tg}</Tag>
          ))}
        </div>
      </div>
      <AddDot added={added} onClick={(e)=>{ e.stopPropagation(); onAdd(); }} />
    </div>
  );
}

// grouped section: mono header + inset card of rows
function Group({ label, count, children }) {
  return (
    <div style={{ marginBottom:20 }}>
      <div style={{ display:'flex', alignItems:'baseline', gap:8, padding:'0 4px 8px',
        fontFamily:TS_MONO, fontSize:10.5, letterSpacing:'0.14em', textTransform:'uppercase', color:TS.c3 }}>
        <span>{label}</span>
        <span style={{ color:TS.cdis }}>{count}</span>
      </div>
      <div style={{ background:TS.s2, borderRadius:12, overflow:'hidden' }}>{children}</div>
    </div>
  );
}

// ─────────────────────────────────────────── detail sheet (mirrors app Sheet)
function DetailSheet({ t, added, onAdd, onClose }) {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => { const id = setTimeout(()=>setShow(true), 20); return ()=>clearTimeout(id); }, []);
  const catLabel = (CATS.find(c=>c.id===t.cat)||{}).label || t.cat;
  const close = () => { setShow(false); setTimeout(onClose, 260); };
  return (
    <div style={{ position:'absolute', inset:0, zIndex:100, display:'flex', flexDirection:'column', justifyContent:'flex-end' }}>
      <div onClick={close} style={{ position:'absolute', inset:0, background:'rgba(5,5,10,0.6)',
        opacity: show?1:0, transition:'opacity .26s' }}/>
      <div style={{
        position:'relative', background:TS.bg, borderTopLeftRadius:16, borderTopRightRadius:16,
        borderTop:`1px solid ${TS.border}`, maxHeight:'90%', display:'flex', flexDirection:'column', overflow:'hidden',
        transform: show ? 'translateY(0)' : 'translateY(100%)', transition:'transform .3s cubic-bezier(.32,.72,0,1)',
        boxShadow:'0 -12px 40px rgba(0,0,0,0.5)',
      }}>
        {/* handle + close header (matches app Sheet) */}
        <div style={{ padding:'10px 0 6px', display:'flex', justifyContent:'center' }}>
          <div style={{ width:36, height:5, borderRadius:3, background:TS.s4 }}/>
        </div>
        <div style={{ display:'flex', alignItems:'center', padding:'4px 16px 12px', borderBottom:`1px solid ${TS.borderSub}` }}>
          <span style={{ fontFamily:TS_SANS, fontSize:17, fontWeight:700, color:TS.c1 }}>Template</span>
          <span style={{ flex:1 }}/>
          <button onClick={close} style={{ width:30, height:30, borderRadius:'50%', border:`1px solid ${TS.border}`,
            background:'transparent', color:TS.c2, display:'flex', alignItems:'center', justifyContent:'center', cursor:'default' }}>
            {TI.x({ size:15, stroke:2 })}
          </button>
        </div>

        <div style={{ overflowY:'auto', padding:'16px 16px 28px', flex:1 }}>
          <div style={{ display:'flex', gap:13, alignItems:'flex-start', marginBottom:14 }}>
            <IconTile icon={t.icon} size={48} r={12}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontFamily:TS_SANS, fontSize:20, fontWeight:700, color:TS.c1, letterSpacing:'-0.02em' }}>{t.title}</div>
              <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:6, fontFamily:TS_MONO, fontSize:11, color:TS.c3 }}>
                <span style={{ display:'inline-flex', alignItems:'center', height:20, padding:'0 8px', borderRadius:4,
                  background:'rgba(39,110,241,0.16)', color:TS.info, lineHeight:1 }}>{catLabel}</span>
                <span style={{ width:3, height:3, borderRadius:'50%', background:TS.cdis }}/>
                <span>{t.id}</span>
              </div>
            </div>
          </div>

          <div style={{ fontFamily:TS_SANS, fontSize:15, lineHeight:1.5, color:TS.c2, marginBottom:14 }}>{t.desc}</div>

          <div style={{ display:'flex', gap:6, flexWrap:'wrap', marginBottom:22 }}>
            {t.tags.map(tg => <Tag key={tg}>{tg}</Tag>)}
          </div>

          {/* share output preview */}
          <div style={{ fontFamily:TS_MONO, fontSize:10, letterSpacing:'0.14em', textTransform:'uppercase',
            color:TS.c3, marginBottom:10 }}>What you'll share</div>
          <div style={{ background:TS.s2, borderRadius:12, padding:16, marginBottom:24 }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
              {TI.sparkle({ size:15, color:TS.info })}
              <span style={{ fontFamily:TS_SANS, fontSize:13, fontWeight:600, color:TS.c2 }}>{t.title} — Summary</span>
            </div>
            <div style={{ display:'flex', flexDirection:'column' }}>
              {t.fields.map((f, i) => (
                <div key={f} style={{ padding:'11px 0', borderTop: i? `1px solid ${TS.borderSub}`:'none' }}>
                  <div style={{ fontFamily:TS_SANS, fontSize:11, fontWeight:600, letterSpacing:'0.03em',
                    textTransform:'uppercase', color:TS.c3, marginBottom:7 }}>{f}</div>
                  <div style={{ height:6, borderRadius:3, background:TS.s3, width:'92%', marginBottom:5 }}/>
                  <div style={{ height:6, borderRadius:3, background:TS.s3, width: i%2? '58%':'74%' }}/>
                </div>
              ))}
            </div>
          </div>

          {/* primary action — the one place white is earned */}
          <button onClick={onAdd} style={{
            width:'100%', height:48, borderRadius:8, cursor:'default',
            border: added?`1px solid ${TS.border}`:'none',
            background: added ? 'transparent' : TS.c1, color: added ? TS.c1 : '#000',
            fontFamily:TS_SANS, fontSize:15, fontWeight:600, display:'flex',
            alignItems:'center', justifyContent:'center', gap:8,
          }}>
            {added ? TI.checkfill({ size:19, color:TS.pos }) : TI.plus({ size:18, stroke:2.1, color:'#000' })}
            {added ? 'Added to your templates' : 'Add Template'}
          </button>
          {added && (
            <div style={{ textAlign:'center', marginTop:12, fontFamily:TS_SANS, fontSize:13, color:TS.c3 }}>
              Available when you set up or finish a recording.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────── screen
function TemplateStore() {
  const [cat, setCat] = React.useState('all');
  const [added, setAdded] = React.useState({ user_interview:true });
  const [openId, setOpenId] = React.useState(null);
  const [q, setQ] = React.useState('');
  const [activeTag, setActiveTag] = React.useState(null);

  const toggle = (id) => setAdded(a => ({ ...a, [id]: !a[id] }));
  const onTag = (tg) => setActiveTag(cur => cur===tg ? null : tg);
  const list = TEMPLATES.filter(t =>
    (cat==='all'||t.cat===cat) &&
    (!activeTag || t.tags.includes(activeTag)) &&
    (!q || (t.title+t.desc+t.tags.join(' ')).toLowerCase().includes(q.toLowerCase())));
  // pinned "Your templates" shortcut (default browse only), then a section per category
  const showMine = cat==='all' && !q && !activeTag && addedCount() > 0;
  function addedCount(){ return Object.values(added).filter(Boolean).length; }
  const catGroups = (cat==='all' ? CATS.filter(c=>c.id!=='all') : CATS.filter(c=>c.id===cat))
    .map(c => ({ id:c.id, label:c.label, items:list.filter(t=>t.cat===c.id) }))
    .filter(g => g.items.length > 0);
  const groups = [
    ...(showMine ? [{ id:'__mine', label:'Your templates', items: TEMPLATES.filter(t=>added[t.id]) }] : []),
    ...catGroups,
  ];
  const openT = TEMPLATES.find(t => t.id===openId);
  const nAdded = addedCount();

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:TS.bg, position:'relative', overflow:'hidden' }}>
      {/* fixed circle-button bar (matches Recording Detail) */}
      <div style={{ padding:'54px 16px 8px', flexShrink:0 }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <CircleBtn icon={TI.back({ size:20, color:TS.c2 })} />
          <CircleBtn icon={TI.saved({ size:18, color:nAdded?TS.c1:TS.c2 })} />
        </div>
      </div>

      {/* scroll region */}
      <div style={{ flex:1, minHeight:0, overflowY:'auto' }} className="ts-scroll">
        {/* large title — scrolls away */}
        <div style={{ padding:'4px 16px 0' }}>
          <div style={{ fontFamily:TS_SANS, fontSize:28, fontWeight:700, color:TS.c1, letterSpacing:'-0.02em', lineHeight:1.1 }}>Templates</div>
          <div style={{ fontFamily:TS_MONO, fontSize:11, color:TS.c3, marginTop:5 }}>{nAdded} added · {TEMPLATES.length} in store</div>
        </div>

        {/* sticky search + pills */}
        <div style={{ position:'sticky', top:0, zIndex:5, background:TS.bg, paddingTop:14 }}>
          <div style={{ padding:'0 16px' }}>
            <div style={{ display:'flex', alignItems:'center', gap:10, height:44,
              background:TS.s2, borderRadius:12, padding:'0 14px' }}>
              {TI.search({ size:18, color:TS.c3 })}
              <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Search templates"
                style={{ flex:1, background:'transparent', border:'none', outline:'none',
                  fontFamily:TS_SANS, fontSize:15, color:TS.c1 }}/>
            </div>
          </div>
          <div style={{ display:'flex', gap:8, overflowX:'auto', padding:'12px 16px 4px' }} className="ts-scroll">
            {CATS.map(c => (
              <Pill key={c.id} active={cat===c.id} onClick={()=>setCat(c.id)}>{c.label}</Pill>
            ))}
          </div>
          {activeTag && (
            <div style={{ display:'flex', alignItems:'center', gap:9, padding:'10px 16px 4px' }}>
              <span style={{ fontFamily:TS_MONO, fontSize:10, letterSpacing:'0.12em', textTransform:'uppercase', color:TS.c3 }}>Filtered by</span>
              <button onClick={()=>setActiveTag(null)} style={{ display:'inline-flex', alignItems:'center', gap:6,
                height:26, padding:'0 8px 0 10px', borderRadius:6, border:'none', cursor:'default',
                background:'rgba(39,110,241,0.16)', color:TS.info, fontFamily:TS_MONO, fontSize:11 }}>
                #{activeTag}{TI.x({ size:13, stroke:2.6, color:TS.info })}
              </button>
            </div>
          )}
          <div style={{ height:8 }}/>
        </div>

        {/* list */}
        <div style={{ padding:'6px 16px 24px' }}>
          {groups.length === 0 ? (
            <div style={{ textAlign:'center', color:TS.c3, fontFamily:TS_SANS, fontSize:14, marginTop:48 }}>
              {activeTag ? <>Nothing tagged <span style={{color:TS.c2}}>#{activeTag}</span>{cat!=='all'?' here':''}.</> : <>No templates match “{q}”.</>}
            </div>
          ) : (
            groups.map(g => (
              <Group key={g.id} label={g.label} count={g.items.length}>
                {g.items.map((t, i) => (
                  <TemplateRow key={t.id} t={t} added={!!added[t.id]} last={i===g.items.length-1}
                    onAdd={()=>toggle(t.id)} onOpen={()=>setOpenId(t.id)} onTag={onTag} activeTag={activeTag}/>
                ))}
              </Group>
            ))
          )}
        </div>
      </div>

      {openT && (
        <DetailSheet t={openT} added={!!added[openT.id]}
          onAdd={()=>toggle(openT.id)} onClose={()=>setOpenId(null)}/>
      )}
    </div>
  );
}

function App() {
  return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:'40px 20px' }}>
      <IOSDevice dark={true} width={402} height={874}>
        <TemplateStore/>
      </IOSDevice>
    </div>
  );
}

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