// screens-b.jsx — Records list, Detail, Export

const SAMPLE_RECORDS = [
  { id: 'r1', date: '9 May 2026', time: '14:32', type: 'symptom',  title: 'Back pain — flared after PT', cond: 'MSK-back',  sev: 7, chain: true },
  { id: 'r2', date: '9 May 2026', time: '09:17', type: 'incident', title: 'Vehicle rollover, MRH-90 sim', cond: 'PTSD',     sev: 8, chain: true },
  { id: 'r3', date: '8 May 2026', time: '16:48', type: 'reporting',title: 'Reporting attempt — MO',     cond: 'tinnitus',  sev: 5, chain: false },
  { id: 'r4', date: '7 May 2026', time: '21:04', type: 'trigger',  title: 'Triggered — fireworks',      cond: 'PTSD',      sev: 6, chain: true },
  { id: 'r5', date: '6 May 2026', time: '11:22', type: 'exposure', title: 'Diesel fumes, vehicle bay',  cond: 'exposure',  sev: 4, chain: false },
  { id: 'r6', date: '5 May 2026', time: '07:55', type: 'symptom',  title: 'Knee pain stepping out',     cond: 'MSK-knee',  sev: 6, chain: false },
  { id: 'r7', date: '3 May 2026', time: '23:18', type: 'symptom',  title: 'Sleep — woke 0210, did not return', cond: 'sleep', sev: 5, chain: true },
];

// ─── 4. RECORDS LIST ────────────────────────────────────────────────
function RecordsScreen({ go }) {
  const [filter, setFilter] = React.useState('All');
  const filters = ['All', 'Symptoms', 'Incidents', 'Exposures', 'Reports', 'Triggers'];
  const map = { Symptoms: 'symptom', Incidents: 'incident', Exposures: 'exposure', Reports: 'reporting', Triggers: 'trigger' };
  const visible = filter === 'All' ? SAMPLE_RECORDS : SAMPLE_RECORDS.filter(r => r.type === map[filter]);

  // group by date
  const groups = {};
  visible.forEach(r => { (groups[r.date] = groups[r.date] || []).push(r); });

  return (
    <div className="app-bg" style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', position: 'relative' }}>
      {/* large title */}
      <div style={{ paddingTop: 56, paddingLeft: 24, paddingRight: 24, paddingBottom: 8 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.18, textTransform: 'uppercase' }}>
          47 records · 12 conditions
        </div>
        <div style={{ fontSize: 28, fontWeight: 600, color: 'var(--navy)', letterSpacing: -0.5, marginTop: 4 }}>
          Records
        </div>
      </div>

      {/* search */}
      <div style={{ padding: '8px 20px 12px' }}>
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--hairline)',
          borderRadius: 12, padding: '10px 12px',
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 14, color: 'var(--slate-70)',
        }}>
          <IconSearch size={16} color="var(--slate)" />
          <span>Search records, conditions, witnesses…</span>
        </div>
      </div>

      {/* filters */}
      <div className="no-sb" style={{ overflowX: 'auto', padding: '0 20px 12px' }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {filters.map(f => {
            const sel = filter === f;
            return (
              <button key={f} onClick={() => setFilter(f)} className="press" style={{
                border: `1px solid ${sel ? 'var(--navy)' : 'var(--hairline-strong)'}`,
                background: sel ? 'var(--navy)' : 'transparent',
                color: sel ? 'var(--paper)' : 'var(--navy)',
                borderRadius: 999, padding: '6px 13px',
                fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap',
                cursor: 'pointer', fontFamily: 'var(--sans)',
              }}>{f}</button>
            );
          })}
        </div>
      </div>

      {/* list */}
      <div className="no-sb" style={{ flex: 1, overflowY: 'auto', padding: '0 20px 16px' }}>
        {Object.entries(groups).map(([date, rows]) => (
          <div key={date} style={{ marginBottom: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 4px 8px' }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.05, textTransform: 'uppercase' }}>{date}</span>
              <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
              <span className="mono" style={{ fontSize: 10, color: 'var(--slate-50)' }}>{rows.length}</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {rows.map(r => (
                <button key={r.id} onClick={() => go('detail')} className="paper-card press" style={{
                  padding: '11px 13px', textAlign: 'left', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', gap: 11, border: '1px solid var(--hairline)',
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 8,
                    background: 'var(--paper)', border: '1px solid var(--hairline)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <TypeGlyph type={r.type} size={15} color="var(--navy)" />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="mono tabnums" style={{ fontSize: 10, color: 'var(--slate)' }}>
                      {r.time} · sev <span style={{ color: 'var(--navy)', fontWeight: 600 }}>{r.sev}</span>/10
                    </div>
                    <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--navy)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {r.title}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                    {r.chain && (
                      <span title="part of pattern" style={{
                        width: 22, height: 22, borderRadius: 11, background: 'var(--teal-12)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <IconLink size={12} color="var(--teal)" />
                      </span>
                    )}
                    <span className="mono" style={{ fontSize: 9.5, color: 'var(--slate)', background: 'var(--paper)', border: '1px solid var(--hairline)', padding: '2px 6px', borderRadius: 4 }}>
                      {r.cond}
                    </span>
                  </div>
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <TabBar active="records" onNav={go} />
      <Anno top={172} right={20} side="tr">filter pills · navy = selected</Anno>
    </div>
  );
}

// ─── 5. RECORD DETAIL ───────────────────────────────────────────────
function DetailScreen({ go }) {
  const [chainOpen, setChainOpen] = React.useState(false);
  const [playing, setPlaying] = React.useState(false);

  return (
    <div className="app-bg" style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', position: 'relative' }}>
      <TopBar
        left={<IconBtn onClick={() => go('records')}><IconChevL size={18} /></IconBtn>}
        right={<IconBtn><IconShareDot size={16} /></IconBtn>}
        title="Record · 9 May, 14:32"
        subtitle="r-2026-05-09-1432-a4f"
      />

      <div className="no-sb" style={{ flex: 1, overflow: 'auto', padding: '4px 20px 24px' }}>
        {/* header strip */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--slate)', background: 'var(--surface)', border: '1px solid var(--hairline)', padding: '4px 8px', borderRadius: 4 }}>
            symptom
          </span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--teal)', background: 'var(--teal-12)', border: '1px solid var(--teal)', padding: '4px 8px', borderRadius: 4 }}>
            MSK-back · 7/10
          </span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--slate)', background: 'var(--surface)', border: '1px solid var(--hairline)', padding: '4px 8px', borderRadius: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
            <IconLocation size={11} color="var(--slate)"/> off
          </span>
        </div>

        {/* audio player */}
        <div style={{
          background: 'var(--navy)', borderRadius: 16, padding: '18px 18px',
          marginBottom: 16, color: '#F5F1E8',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button onClick={() => setPlaying(!playing)} className="press" style={{
              width: 48, height: 48, borderRadius: 24, border: 'none',
              background: 'var(--teal)', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              {playing ? <IconPause size={18} color="#F5F1E8" /> : <IconPlay size={18} color="#F5F1E8" />}
            </button>
            <div style={{ flex: 1 }}>
              <Waveform bars={32} color="rgba(245,241,232,0.4)" height={32} playing={playing} seed={3}/>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
                <span className="mono tabnums" style={{ fontSize: 10, color: 'rgba(245,241,232,0.7)' }}>00:34</span>
                <span className="mono tabnums" style={{ fontSize: 10, color: 'rgba(245,241,232,0.7)' }}>01:24</span>
              </div>
            </div>
          </div>
        </div>

        {/* transcript */}
        <div style={{ marginBottom: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.05, textTransform: 'uppercase' }}>
              Transcript · v2 (edited)
            </span>
            <button className="press" style={{ border: 'none', background: 'transparent', fontSize: 12, color: 'var(--teal)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4 }}>
              <IconEdit size={12} color="var(--teal)" /> Edit
            </button>
          </div>
          <div style={{ fontSize: 14, color: 'var(--navy)', lineHeight: 1.55, textWrap: 'pretty' }}>
            Loading stores at Holsworthy this morning, lifting a 25kg crate onto the rack. Felt it go in the lower back, right side. Pain came on quickly, sharp, then settling to a dull ache. About a 7. Same spot as the 2019 incident. Did not report it on the spot — finished the shift.
          </div>
        </div>

        {/* metadata block */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--hairline)',
          borderRadius: 12, padding: '14px 16px', marginBottom: 16,
        }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.05, textTransform: 'uppercase', marginBottom: 10 }}>
            Metadata
          </div>
          {[
            ['note type',     'symptom'],
            ['condition',     'MSK-back'],
            ['severity',      '7 / 10'],
            ['reported to',   'no-one'],
            ['medical attn.', 'not yet'],
            ['witnesses',     'CPL-A · CPL-B (coded)'],
            ['linked',        '3 records · MSK-back chain'],
          ].map(([k, v], i, arr) => (
            <div key={k} style={{
              display: 'flex', justifyContent: 'space-between', padding: '6px 0',
              borderBottom: i === arr.length - 1 ? 'none' : '1px solid var(--hairline)',
            }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--slate)' }}>{k}</span>
              <span className="mono tabnums" style={{ fontSize: 11, color: 'var(--navy)', fontWeight: 500 }}>{v}</span>
            </div>
          ))}
        </div>

        {/* chain of custody — folded */}
        <div style={{
          background: 'var(--paper)', border: '1px solid var(--hairline-strong)',
          borderRadius: 12, overflow: 'hidden',
        }}>
          <button onClick={() => setChainOpen(!chainOpen)} className="press" style={{
            width: '100%', padding: '14px 16px', border: 'none', background: 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', cursor: 'pointer',
          }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <IconLink size={14} color="var(--teal)" />
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--navy)', letterSpacing: -0.1 }}>Chain of custody</span>
            </span>
            <span style={{ transform: chainOpen ? 'rotate(180deg)' : 'none', transition: 'transform 200ms' }}>
              <IconChevD size={14} color="var(--slate)" />
            </span>
          </button>
          {chainOpen && (
            <div className="mono" style={{
              padding: '4px 16px 16px', fontSize: 10.5, color: 'var(--navy)',
              lineHeight: 1.7, letterSpacing: 0.02,
            }}>
              <div>captured-at  2026-05-09T14:32:14+10:00</div>
              <div style={{ wordBreak: 'break-all' }}>sha-256      a4f9c2…7e1b8d4f02c1ab9d5e3f64a9c2b71f8</div>
              <div>device       iPhone 16 · iOS 26.1.1</div>
              <div>device-fp    7c:42:9a:b1 (rotated, anonymous)</div>
              <div>au-region    syd-1 · stored 14:32:18</div>
              <div style={{ marginTop: 10, color: 'var(--slate)' }}>edit history</div>
              <div>· v1 14:32:18 — original</div>
              <div>· v2 16:08:42 — transcript correction (3 chars)</div>
            </div>
          )}
        </div>
      </div>
      <Anno top={350} right={22} side="tr">teal play · monospace timer</Anno>
      <Anno bottom={120} left={22} side="bl">forensic page · zero adornment</Anno>
    </div>
  );
}

// ─── 6. EXPORT COMPOSER ─────────────────────────────────────────────
function ExportScreen({ go }) {
  const [shape, setShape] = React.useState('cornelius');
  const [selectedIds, setSelectedIds] = React.useState(new Set(['r1','r2','r4','r6','r7']));
  const toggle = (id) => {
    const s = new Set(selectedIds);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelectedIds(s);
  };
  const count = selectedIds.size;

  return (
    <div className="app-bg" style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', position: 'relative' }}>
      <div style={{ paddingTop: 56, paddingLeft: 24, paddingRight: 24, paddingBottom: 4 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.18, textTransform: 'uppercase' }}>
          Export · brief
        </div>
        <div style={{ fontSize: 28, fontWeight: 600, color: 'var(--navy)', letterSpacing: -0.5, marginTop: 4 }}>
          New export
        </div>
      </div>

      <div className="no-sb" style={{ flex: 1, overflow: 'auto', padding: '12px 20px 16px' }}>
        {/* shape selector */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 18 }}>
          {[
            { id: 'cornelius', name: 'Cornelius pack', sub: 'For your treating doctor' },
            { id: 'advocate',  name: 'Advocate brief', sub: 'For ESORT or paid advocate' },
          ].map(s => {
            const sel = shape === s.id;
            return (
              <button key={s.id} onClick={() => setShape(s.id)} className="press" style={{
                border: `1.5px solid ${sel ? 'var(--teal)' : 'var(--hairline-strong)'}`,
                background: sel ? 'var(--teal-12)' : 'var(--surface)',
                borderRadius: 12, padding: '13px 13px',
                cursor: 'pointer', textAlign: 'left',
                display: 'flex', flexDirection: 'column', gap: 4,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <IconDoc size={15} color={sel ? 'var(--teal)' : 'var(--slate)'} />
                  <span style={{ fontSize: 13, fontWeight: 600, color: sel ? 'var(--teal)' : 'var(--navy)', letterSpacing: -0.1 }}>{s.name}</span>
                </div>
                <span style={{ fontSize: 11, color: 'var(--slate)', lineHeight: 1.35 }}>{s.sub}</span>
              </button>
            );
          })}
        </div>

        {/* filters */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--hairline)',
          borderRadius: 12, padding: '12px 14px', marginBottom: 14,
        }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.05, textTransform: 'uppercase', marginBottom: 10 }}>Filters</div>
          {[
            ['date range', 'Mar 2026 — May 2026'],
            ['conditions', 'MSK-back · PTSD · sleep'],
            ['severity ≥', '4'],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: '1px solid var(--hairline)' }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--slate)' }}>{k}</span>
              <span style={{ fontSize: 12, color: 'var(--navy)', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 5 }}>
                {v} <IconChevR size={12} color="var(--slate)" />
              </span>
            </div>
          ))}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0 0' }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--slate)' }}>matching</span>
            <span className="mono tabnums" style={{ fontSize: 12, color: 'var(--navy)', fontWeight: 600 }}>{count} of 47 selected</span>
          </div>
        </div>

        {/* consistency check */}
        <div style={{
          background: 'var(--paper)', border: '1px solid var(--navy)',
          borderRadius: 12, padding: '12px 14px', marginBottom: 14,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <IconWarn size={14} color="var(--navy)" />
            <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--navy)', letterSpacing: -0.1 }}>Consistency check · 1 issue</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--slate)', lineHeight: 1.5 }}>
            Onset date for MSK-back differs between r-2024-08-12 (“Aug 2019”) and r-2025-03-04 (“early 2020”).
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
            <button className="press" style={{ flex: 1, border: '1px solid var(--navy)', background: 'transparent', borderRadius: 8, padding: '7px 10px', fontSize: 12, color: 'var(--navy)', fontWeight: 500, cursor: 'pointer' }}>Review</button>
            <button className="press" style={{ flex: 1, border: '1px solid var(--hairline-strong)', background: 'transparent', borderRadius: 8, padding: '7px 10px', fontSize: 12, color: 'var(--slate)', fontWeight: 500, cursor: 'pointer' }}>Acknowledge</button>
          </div>
        </div>

        {/* records checklist */}
        <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.05, textTransform: 'uppercase', padding: '4px 4px 8px' }}>
          Records · {count} included
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {SAMPLE_RECORDS.map(r => {
            const sel = selectedIds.has(r.id);
            return (
              <button key={r.id} onClick={() => toggle(r.id)} className="press" style={{
                border: `1px solid ${sel ? 'var(--teal)' : 'var(--hairline)'}`,
                background: sel ? 'var(--teal-08)' : 'var(--surface)',
                borderRadius: 10, padding: '10px 12px',
                display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', textAlign: 'left',
              }}>
                <div style={{
                  width: 18, height: 18, borderRadius: 4,
                  border: `1.5px solid ${sel ? 'var(--teal)' : 'var(--navy-25)'}`,
                  background: sel ? 'var(--teal)' : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  {sel && <IconCheck size={12} color="#F5F1E8" />}
                </div>
                <TypeGlyph type={r.type} size={14} color="var(--slate)" />
                <span className="mono" style={{ fontSize: 10, color: 'var(--slate)', flexShrink: 0 }}>{r.date.split(' ').slice(0,2).join(' ')}</span>
                <span style={{ flex: 1, fontSize: 12, color: 'var(--navy)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.title}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--slate)' }}>{r.cond}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Generate button */}
      <div style={{ padding: '12px 20px 12px', borderTop: '1px solid var(--hairline)', background: 'rgba(245,241,232,0.92)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)' }}>
        <button onClick={() => go('home')} className="press" style={{
          width: '100%', height: 50, borderRadius: 14,
          background: 'var(--teal)', color: '#F5F1E8',
          border: 'none', fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <IconExport size={16} color="#F5F1E8" /> Generate · {count} records
        </button>
      </div>
      <TabBar active="export" onNav={go} />
      <Anno top={310} right={22} side="tr">navy border = warning · no red</Anno>
    </div>
  );
}

// ─── Settings (light, just for completeness) ─────────────────────────
function SettingsScreen({ go }) {
  return (
    <div className="app-bg" style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      <div style={{ paddingTop: 56, paddingLeft: 24, paddingRight: 24, paddingBottom: 8 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.18, textTransform: 'uppercase' }}>
          Settings
        </div>
        <div style={{ fontSize: 28, fontWeight: 600, color: 'var(--navy)', letterSpacing: -0.5, marginTop: 4 }}>
          Settings
        </div>
      </div>
      <div className="no-sb" style={{ flex: 1, overflow: 'auto', padding: '8px 20px 16px' }}>
        {[
          { head: 'Storage', items: [['Australian region', 'syd-1'], ['Local cache', '142 MB'], ['Hashing', 'SHA-256 on-device']]},
          { head: 'Capture', items: [['Location stamp', 'Off'], ['Record gesture', 'Press and hold'], ['Auto-transcribe', 'On']]},
          { head: 'Account', items: [['Recovery key', '··· ···· ···· printed'], ['Biometric unlock', 'Face ID']]},
        ].map(g => (
          <div key={g.head} style={{ marginBottom: 18 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--slate)', letterSpacing: 0.05, textTransform: 'uppercase', padding: '4px 4px 8px' }}>{g.head}</div>
            <div style={{ background: 'var(--surface)', border: '1px solid var(--hairline)', borderRadius: 12, overflow: 'hidden' }}>
              {g.items.map(([k, v], i, arr) => (
                <div key={k} style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '13px 14px',
                  borderBottom: i === arr.length - 1 ? 'none' : '1px solid var(--hairline)',
                }}>
                  <span style={{ fontSize: 14, color: 'var(--navy)' }}>{k}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--slate)' }}>{v}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <TabBar active="settings" onNav={go} />
    </div>
  );
}

Object.assign(window, { RecordsScreen, DetailScreen, ExportScreen, SettingsScreen, SAMPLE_RECORDS });
