// LPR Platform — Exams, Questionnaires, Alerts, Evolution, Report

// 6. Upload de exames
function ExamsScreen({ T }) {
  const [drag, setDrag] = React.useState(false);
  const [selected, setSelected] = React.useState('u1');
  const sel = EXAM_UPLOADS.find((e) => e.id === selected) || EXAM_UPLOADS[0];
  const statusMap = {
    pending:       { tone: 'neutral', label: 'Pendente' },
    extracted:     { tone: 'info',    label: 'Extraído' },
    lowConfidence: { tone: 'error',   label: 'Baixa confiança' },
    validated:     { tone: 'success', label: 'Validado' },
  };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 16 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Card T={T} title="Upload de exames" subtitle="PDF, imagem ou planilha · OCR + NLP clínico">
          <div onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)} onDrop={(e) => { e.preventDefault(); setDrag(false); }}
            style={{
              border: `2px dashed ${drag ? T.p600 : T.borderStrong}`, borderRadius: 10, padding: 28,
              background: drag ? T.p50 : T.surfaceAlt, textAlign: 'center', transition: 'all .15s',
            }}>
            <Icons.Upload size={26} color={T.p600}/>
            <div style={{ fontFamily: T.fontDisplay, fontSize: 15, fontWeight: 600, color: T.text, marginTop: 10 }}>Arraste arquivos ou clique para enviar</div>
            <div style={{ fontSize: 12, color: T.textMute, marginTop: 4 }}>Suporta PDF, JPG, PNG, CSV, XLSX · até 25 MB</div>
            <Button T={T} kind="primary" size="sm" style={{ marginTop: 12 }} icon={<Icons.Plus/>}>Selecionar arquivos</Button>
          </div>

          <div style={{ marginTop: 14, padding: 12, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8 }}>
            <div style={{ fontSize: 11, color: T.textMute, fontWeight: 500, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 6 }}>Em processamento</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icons.FileText size={16} color={T.p600}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, color: T.text, fontWeight: 500 }}>Composicao_corporal_dexa.pdf</div>
                <Meter T={T} value={68} color={T.p500} height={4} right="68%"/>
              </div>
              <span style={{ fontSize: 11, color: T.textMute }}>extraindo marcadores…</span>
            </div>
          </div>
        </Card>

        <Card T={T} title="Exames enviados" padding={0} subtitle="Mariana Corrêa · LPR-LR-1"
          action={<Button T={T} kind="secondary" size="sm" icon={<Icons.Filter/>}>Todos</Button>}>
          {EXAM_UPLOADS.map((e, i, arr) => (
            <div key={e.id} className="lpr-row" onClick={() => setSelected(e.id)}
              style={{
                display: 'flex', gap: 10, alignItems: 'center', padding: '11px 16px',
                borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0, cursor: 'pointer',
                background: selected === e.id ? T.p50 : 'transparent',
                borderLeft: `3px solid ${selected === e.id ? T.p600 : 'transparent'}`,
              }}>
              <Icons.FileText size={15} color={T.textMute}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: T.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.file}</div>
                <div style={{ fontSize: 11, color: T.textMute, marginTop: 1 }}>{e.lab} · {e.uploadedAt} · {e.size}</div>
              </div>
              <Pill T={T} tone={statusMap[e.status].tone}>{statusMap[e.status].label}</Pill>
              {e.markers > 0 ? <span style={{ fontSize: 11, color: T.textMute }}>{e.markers} marc.</span> : null}
            </div>
          ))}
        </Card>
      </div>

      <Card T={T} padding={0}>
        <div style={{ padding: '14px 18px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icons.FileText size={16} color={T.p600}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: T.text }}>{sel.file}</div>
            <div style={{ fontSize: 11.5, color: T.textMute }}>
              {sel.lab} · {sel.uploadedAt}
              {sel.confidence != null ? <> · Confiança extração: <strong style={{ color: sel.confidence > 0.9 ? T.success : T.warning }}>{Math.round(sel.confidence * 100)}%</strong></> : null}
            </div>
          </div>
          <Pill T={T} tone={statusMap[sel.status].tone}>{statusMap[sel.status].label}</Pill>
          <Button T={T} kind="ghost" size="sm" icon={<Icons.Download/>}>Original</Button>
        </div>

        <div style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>Marcadores identificados ({EXAMS_PANEL.length})</span>
            <div style={{ display: 'flex', gap: 6 }}>
              <Pill T={T} tone="error">{EXAMS_PANEL.filter((e) => e.status === 'high' || e.status === 'low').length} alterados</Pill>
              <Pill T={T} tone="warning">{EXAMS_PANEL.filter((e) => e.status === 'borderline').length} limítrofes</Pill>
            </div>
          </div>

          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: T.fontUI, fontSize: 12.5 }}>
            <thead>
              <tr style={{ background: T.surface, borderBottom: `1px solid ${T.border}` }}>
                {['Marcador', 'Valor', 'Ref. lab.', 'Ref. protocolo', 'Domínio', 'Status', 'Validar'].map((h, i) => (
                  <th key={i} style={{ padding: '8px 10px', textAlign: i === 1 ? 'right' : 'left', fontSize: 10.5, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {EXAMS_PANEL.map((e, i) => {
                const c = e.status === 'high' || e.status === 'low' ? T.error : e.status === 'borderline' ? T.warning : T.success;
                const dom = LPR_DOMAINS.find((d) => d.id === e.domain);
                const Di = dom ? Icons[dom.icon] : Icons.Activity;
                return (
                  <tr key={i} style={{ borderBottom: `1px solid ${T.border}` }}>
                    <td style={{ padding: '9px 10px', color: T.text, fontWeight: 500 }}>{e.name}</td>
                    <td style={{ padding: '9px 10px', textAlign: 'right', fontFamily: T.fontMono, fontVariantNumeric: 'tabular-nums', fontWeight: 600, color: c }}>
                      {e.value} <span style={{ fontSize: 10, color: T.textMute, fontWeight: 400 }}>{e.unit}</span>
                    </td>
                    <td style={{ padding: '9px 10px', color: T.textMute, fontFamily: T.fontMono, fontSize: 11.5 }}>{e.refLab}</td>
                    <td style={{ padding: '9px 10px', color: T.textSoft, fontFamily: T.fontMono, fontSize: 11.5, fontWeight: 600 }}>{e.refProto}</td>
                    <td style={{ padding: '9px 10px' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: T.textSoft }}>
                        <Di size={12} color={T.textMute}/>{dom?.short}
                      </span>
                    </td>
                    <td style={{ padding: '9px 10px' }}>
                      {e.status === 'high' && <Pill T={T} tone="error">↑ Alto</Pill>}
                      {e.status === 'low' && <Pill T={T} tone="error">↓ Baixo</Pill>}
                      {e.status === 'borderline' && <Pill T={T} tone="warning">Limítrofe</Pill>}
                      {e.status === 'normal' && <Pill T={T} tone="success">Normal</Pill>}
                    </td>
                    <td style={{ padding: '9px 10px' }}>
                      <input type="checkbox" defaultChecked={i < 11} style={{ accentColor: T.p600, width: 14, height: 14 }}/>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14, padding: 12, background: T.p50, borderRadius: 8, border: `1px solid ${T.p100}` }}>
            <div style={{ fontSize: 12, color: T.p700 }}>
              <strong>11 marcadores</strong> serão validados e associados aos domínios. Score será recalculado.
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <Button T={T} kind="secondary" size="sm">Editar</Button>
              <Button T={T} kind="primary" size="sm" icon={<Icons.Check/>}>Validar exames e recalcular score</Button>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

// 7. Questionnaires
function QuestionnairesScreen({ T }) {
  const [tab, setTab] = React.useState('pending');
  const pending = QUESTIONNAIRES.filter((q) => q.score == null);
  const answered = QUESTIONNAIRES.filter((q) => q.score != null);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        <KPI T={T} label="Pendentes" value={pending.length} sub="aguardando paciente" icon={<Icons.Clock/>} tone="warning"/>
        <KPI T={T} label="Respondidos" value={answered.length} sub="últimos 30 dias" icon={<Icons.Check/>} tone="success"/>
        <KPI T={T} label="Frequência diária" value="LPR Daily" sub="último: hoje" icon={<Icons.Calendar/>} tone="primary"/>
        <KPI T={T} label="Aderência" value="78%" sub="3 atrasos no ciclo" icon={<Icons.Target/>} tone="neutral"/>
      </div>

      <Card T={T} padding={0}>
        <div style={{ padding: '14px 16px 0' }}>
          <Tabs T={T} active={tab} onChange={setTab} tabs={[
            { id: 'pending', label: 'Pendentes', count: pending.length },
            { id: 'answered', label: 'Respondidos', count: answered.length },
            { id: 'all', label: 'Todos os instrumentos', count: QUESTIONNAIRES.length },
          ]}/>
        </div>

        <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: T.fontUI }}>
          <thead>
            <tr style={{ borderBottom: `1px solid ${T.border}`, background: T.surface }}>
              {['Instrumento', 'Frequência', 'Domínios', 'Última aplicação', 'Score', 'Histórico', ''].map((h, i) => (
                <th key={i} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {QUESTIONNAIRES.map((q, i) => (
              <tr key={q.id} style={{ borderBottom: i < QUESTIONNAIRES.length - 1 ? `1px solid ${T.border}` : 0 }}>
                <td style={{ padding: '12px 16px' }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{q.name}</div>
                  <div style={{ fontSize: 11, color: T.textMute }}>{q.id}</div>
                </td>
                <td style={{ padding: '12px 16px', fontSize: 12.5, color: T.textSoft }}>{q.freq}</td>
                <td style={{ padding: '12px 16px' }}>
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    {q.domains.map((d) => (
                      <Pill key={d} T={T} tone="neutral">{LPR_DOMAINS.find((x) => x.id === d)?.short}</Pill>
                    ))}
                  </div>
                </td>
                <td style={{ padding: '12px 16px', fontSize: 12.5, color: q.score == null ? T.warning : T.textSoft }}>{q.last}</td>
                <td style={{ padding: '12px 16px' }}>
                  {q.score == null ? <Pill T={T} tone="warning" icon={<Icons.Clock size={10}/>}>Pendente</Pill> : (
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                      <span style={{ fontFamily: T.fontDisplay, fontSize: 16, fontWeight: 700, color: T.text, fontVariantNumeric: 'tabular-nums' }}>{q.score}</span>
                      {q.max ? <span style={{ fontSize: 11, color: T.textMute }}>/ {q.max}</span> : null}
                    </div>
                  )}
                </td>
                <td style={{ padding: '12px 16px' }}>
                  {q.score != null ? <Sparkline T={T} values={[q.score * 0.7, q.score * 0.85, q.score * 0.9, q.score * 0.95, q.score]} color={T.p600} fill={T.p100} width={70} height={22}/> : <span style={{ color: T.textFaint, fontSize: 11 }}>—</span>}
                </td>
                <td style={{ padding: '12px 16px', textAlign: 'right' }}>
                  {q.score == null ? <Button T={T} kind="primary" size="sm" icon={<Icons.Send/>}>Enviar</Button> : <Button T={T} kind="ghost" size="sm" iconRight={<Icons.ChevronR/>}>Ver respostas</Button>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// 11. Alerts screen
function AlertsScreen({ T }) {
  const [audience, setAudience] = React.useState('doctor');
  const [sev, setSev] = React.useState('all');
  const all = ALERTS.filter((a) => a.for === audience).filter((a) => sev === 'all' || a.sev === sev);
  const groups = [
    { id: 'high', label: 'Crítico', tone: 'error', items: all.filter((a) => a.sev === 'high') },
    { id: 'medium', label: 'Atenção', tone: 'warning', items: all.filter((a) => a.sev === 'medium') },
    { id: 'low', label: 'Informativo', tone: 'info', items: all.filter((a) => a.sev === 'low') },
  ];
  const kindLabel = { trend: 'Piora de tendência', pattern: 'Padrão emergente', safety: 'Safety Engine', lab: 'Laboratorial', data: 'Dados faltantes' };
  const kindIcon  = { trend: Icons.TrendDn, pattern: Icons.Zap, safety: Icons.Shield, lab: Icons.Activity, data: Icons.AlertCir };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
        <KPI T={T} label="Alertas críticos" value={ALERTS.filter((a) => a.sev === 'high').length} icon={<Icons.AlertTri/>} tone="error"/>
        <KPI T={T} label="Atenção" value={ALERTS.filter((a) => a.sev === 'medium').length} icon={<Icons.AlertCir/>} tone="warning"/>
        <KPI T={T} label="Informativos" value={ALERTS.filter((a) => a.sev === 'low').length} icon={<Icons.Info/>} tone="info"/>
        <KPI T={T} label="Padrões emergentes" value="3" sub="cruzamento interdomínios" icon={<Icons.Zap/>} tone="primary"/>
        <KPI T={T} label="Dados faltantes" value="11" sub="paciente · 7d" icon={<Icons.Database/>} tone="neutral"/>
      </div>

      <Card T={T} padding={0}>
        <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 4, padding: 3, background: T.surfaceAlt, borderRadius: 8 }}>
            {[{ id: 'doctor', label: 'Para o médico' }, { id: 'patient', label: 'Para o paciente' }].map((a) => (
              <button key={a.id} onClick={() => setAudience(a.id)} className="lpr-btn" style={{
                padding: '6px 14px', borderRadius: 6, border: 0, cursor: 'pointer', fontSize: 12, fontWeight: 500,
                background: audience === a.id ? T.bg : 'transparent', color: audience === a.id ? T.text : T.textMute,
                boxShadow: audience === a.id ? '0 1px 2px rgba(0,0,0,0.05)' : 'none',
              }}>{a.label}</button>
            ))}
          </div>
          <div style={{ width: 1, height: 22, background: T.border }}/>
          {[{ id: 'all', label: 'Todas' }, { id: 'high', label: 'Crítico' }, { id: 'medium', label: 'Atenção' }, { id: 'low', label: 'Info' }].map((s) => (
            <button key={s.id} onClick={() => setSev(s.id)} className="lpr-btn" style={{
              padding: '5px 10px', borderRadius: 999, fontSize: 12, fontWeight: 500, cursor: 'pointer',
              border: `1px solid ${sev === s.id ? T.p600 : T.border}`, background: sev === s.id ? T.p50 : T.bg, color: sev === s.id ? T.p700 : T.textSoft,
            }}>{s.label}</button>
          ))}
          <div style={{ flex: 1 }}/>
          <Button T={T} kind="ghost" size="sm" icon={<Icons.Filter/>}>Domínio: todos</Button>
          <Button T={T} kind="ghost" size="sm" icon={<Icons.User/>}>Paciente: todos</Button>
        </div>

        {groups.map((g) => g.items.length === 0 ? null : (
          <div key={g.id}>
            <div style={{ padding: '10px 16px', background: T.surface, borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Pill T={T} tone={g.tone}>{g.label}</Pill>
              <span style={{ fontSize: 11.5, color: T.textMute }}>{g.items.length} {g.items.length === 1 ? 'alerta' : 'alertas'}</span>
            </div>
            {g.items.map((a, i, arr) => {
              const Ki = kindIcon[a.kind] || Icons.Bell;
              return (
                <div key={a.id} className="lpr-row" style={{
                  display: 'flex', gap: 14, padding: '12px 16px',
                  borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0, alignItems: 'flex-start', cursor: 'pointer',
                }}
                  onMouseEnter={(e) => e.currentTarget.style.background = T.surface}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <span style={{
                    width: 32, height: 32, borderRadius: 8,
                    background: a.sev === 'high' ? T.errorBg : a.sev === 'medium' ? T.warningBg : T.infoBg,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <Ki size={15} color={a.sev === 'high' ? T.error : a.sev === 'medium' ? T.warning : T.info}/>
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{a.patient}</span>
                      <Pill T={T} tone="neutral">{kindLabel[a.kind]}</Pill>
                      {a.domain ? <Pill T={T} tone="neutral">{LPR_DOMAINS.find((d) => d.id === a.domain)?.label}</Pill> : null}
                    </div>
                    <div style={{ fontSize: 12.5, color: T.textSoft, marginTop: 4, lineHeight: 1.5 }}>{a.text}</div>
                    <div style={{ fontSize: 11, color: T.textMute, marginTop: 4 }}>{a.when}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <Button T={T} kind="ghost" size="sm">Resolver</Button>
                    <Button T={T} kind="secondary" size="sm" iconRight={<Icons.ChevronR/>}>Abrir paciente</Button>
                  </div>
                </div>
              );
            })}
          </div>
        ))}
      </Card>
    </div>
  );
}

// 12. Evolution / charts
function EvolutionScreen({ T }) {
  const p = MARIANA;
  const [range, setRange] = React.useState('30d');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <span style={{ fontSize: 13, color: T.textMute }}>Período:</span>
        {['7d','30d','90d','6m','1a','tudo'].map((r) => (
          <button key={r} onClick={() => setRange(r)} className="lpr-btn" style={{
            padding: '5px 12px', fontSize: 12, fontWeight: 500, borderRadius: 6, cursor: 'pointer',
            border: `1px solid ${range === r ? T.p600 : T.border}`,
            background: range === r ? T.p50 : T.bg, color: range === r ? T.p700 : T.textSoft,
          }}>{r}</button>
        ))}
        <div style={{ flex: 1 }}/>
        <Button T={T} kind="secondary" size="sm" icon={<Icons.Download/>}>Exportar dados</Button>
      </div>

      {/* Hero global */}
      <Card T={T} title="Score global LPR" subtitle="Evolução longitudinal · marcos clínicos sobrepostos">
        <ScoreChart T={T} values={[42,44,41,46,49,52,55,54,56,58]} height={260} events={[
          { i: 1, label: 'Início LPR' },
          { i: 4, label: 'Reset Circadiano' },
          { i: 7, label: 'Bloqueio GLP-1' },
        ]}/>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {LPR_DOMAINS.map((d) => {
          const dom = p.domains[d.id];
          const sc = STATUS_COLOR(T)[dom.semaphore];
          const Di = Icons[d.icon];
          return (
            <Card key={d.id} T={T} padding={14}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <Di size={14} color={sc.fg}/>
                <span style={{ fontSize: 12, fontWeight: 600, color: T.text, flex: 1 }}>{d.label}</span>
                <Trend value={dom.delta} T={T}/>
              </div>
              <Sparkline T={T} values={dom.lastTrend} color={sc.fg} fill={sc.bg} width={200} height={48} strokeWidth={1.7}/>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: T.textMute, marginTop: 4 }}>
                <span>{dom.lastTrend[0]}</span>
                <span style={{ fontFamily: T.fontMono, fontWeight: 700, color: sc.fg, fontSize: 13 }}>{dom.score}</span>
              </div>
            </Card>
          );
        })}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
        <CrossPlot T={T} title="Sono × Energia" subtitle="rMSSD vs energia subjetiva (30d)" xLabel="Horas de sono" yLabel="Energia (0-10)" colorA={T.info} colorB={T.warning}
          series={[
            { name: 'Sono', vals: [5.2,5.5,4.8,6.1,5.8,5.4,6.3,5.9,6.5,7.0,6.2,5.5,6.8,7.2], scale: [4,9] },
            { name: 'Energia', vals: [4,5,3,5,5,4,6,5,6,7,6,5,7,7], scale: [0,10] },
          ]}/>
        <CrossPlot T={T} title="Estresse × HRV" subtitle="PSS-10 (semanal) vs rMSSD" xLabel="Estresse" yLabel="HRV (ms)" colorA={T.error} colorB={T.success}
          series={[
            { name: 'Estresse', vals: [22,24,20,18,21,17,19,16,18,15,14], scale: [10, 32] },
            { name: 'HRV', vals: [22,24,26,28,27,30,29,32,31,34,35], scale: [15, 40] },
          ]}/>
        <CrossPlot T={T} title="Peso × Adesão" subtitle="kg vs % adesão" xLabel="Peso (kg)" yLabel="Adesão %" colorA={T.warning} colorB={T.p600}
          series={[
            { name: 'Peso', vals: [78.5,78.4,78.7,78.2,78.0,77.9,77.6,77.7,77.4,77.2,77.0], scale: [76, 80] },
            { name: 'Adesão', vals: [42,48,52,50,55,58,62,60,65,72,76], scale: [0, 100] },
          ]}/>
        <CrossPlot T={T} title="Passos × Energia" subtitle="média diária semanal" xLabel="Passos (k)" yLabel="Energia" colorA={T.p600} colorB={T.warning}
          series={[
            { name: 'Passos', vals: [3.2,3.5,4.0,4.2,4.6,4.8,5.1,5.3,5.6,5.9], scale: [3, 7] },
            { name: 'Energia', vals: [4.5,4.8,5.0,5.2,5.4,5.7,5.9,6.0,6.2,6.4], scale: [3, 8] },
          ]}/>
      </div>

      {/* Timeline of clinical events */}
      <Card T={T} title="Linha do tempo clínica" subtitle="Exames, decisões, intervenções e marcos">
        <div style={{ position: 'relative', paddingLeft: 28 }}>
          <div style={{ position: 'absolute', left: 8, top: 6, bottom: 6, width: 2, background: T.border }}/>
          {[
            { date: '15/04', kind: 'exam', label: 'Painel completo enviado', desc: '14 marcadores extraídos · 3 alterados', color: T.info },
            { date: '15/04', kind: 'decision', label: 'Decisão Safety: Allow Reset Circadiano', desc: 'Driver primário identificado', color: T.success },
            { date: '18/04', kind: 'decision', label: 'Decisão Safety: Postpone Jejum 16:8', desc: 'Cortisol AM elevado + sono instável', color: T.warning },
            { date: '24/04', kind: 'intervention', label: 'Modificação treino de força', desc: 'Volume reduzido, foco técnica', color: T.warning },
            { date: '01/05', kind: 'decision', label: 'Decisão Safety: BLOCK GLP-1', desc: 'Adesão crítica + comportamento instável', color: T.error },
            { date: '02/05', kind: 'milestone', label: 'Score global atinge 58', desc: '+16 pts em 60 dias · maior driver: circadiano', color: T.p600 },
          ].map((ev, i) => (
            <div key={i} style={{ position: 'relative', paddingBottom: 14 }}>
              <span style={{
                position: 'absolute', left: -24, top: 4, width: 12, height: 12, borderRadius: '50%',
                background: ev.color, border: `2px solid ${T.bg}`, boxShadow: `0 0 0 2px ${ev.color}33`,
              }}/>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{ fontSize: 11.5, color: T.textMute, fontVariantNumeric: 'tabular-nums', width: 38 }}>{ev.date}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{ev.label}</span>
              </div>
              <div style={{ fontSize: 12, color: T.textMute, paddingLeft: 46 }}>{ev.desc}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function CrossPlot({ T, title, subtitle, series, xLabel, yLabel, colorA, colorB }) {
  const w = 480, h = 160;
  const n = series[0].vals.length;
  const dx = w / (n - 1);
  const lineFor = (s, color) => {
    const [lo, hi] = s.scale;
    const pts = s.vals.map((v, i) => [i * dx, h - 18 - ((v - lo) / (hi - lo)) * (h - 30)]);
    return { d: pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0]},${p[1]}`).join(' '), pts, color };
  };
  const a = lineFor(series[0], colorA);
  const b = lineFor(series[1], colorB);
  return (
    <Card T={T} title={title} subtitle={subtitle}
      action={
        <div style={{ display: 'flex', gap: 10, fontSize: 11 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: T.textSoft }}><span style={{ width: 10, height: 2, background: colorA, borderRadius: 1 }}/>{series[0].name}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: T.textSoft }}><span style={{ width: 10, height: 2, background: colorB, borderRadius: 1 }}/>{series[1].name}</span>
        </div>
      }>
      <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} style={{ display: 'block' }}>
        {[0.25, 0.5, 0.75].map((g) => (
          <line key={g} x1="0" x2={w} y1={h - 18 - g * (h - 30)} y2={h - 18 - g * (h - 30)} stroke={T.border} strokeDasharray="2 4"/>
        ))}
        <path d={a.d} fill="none" stroke={a.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d={b.d} fill="none" stroke={b.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="3 3"/>
        {a.pts.map((p, i) => <circle key={'a' + i} cx={p[0]} cy={p[1]} r="2.5" fill={colorA}/>)}
        {b.pts.map((p, i) => <circle key={'b' + i} cx={p[0]} cy={p[1]} r="2.5" fill={colorB}/>)}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: T.textMute, marginTop: 2 }}>
        <span>{xLabel}</span><span>{yLabel}</span>
      </div>
    </Card>
  );
}

// 13. Report
function ReportScreen({ T }) {
  const p = MARIANA;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 16 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Card T={T} title="Gerar relatório">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { id: 'initial', label: 'Relatório inicial', desc: 'Linha de base + plano' },
              { id: 'evolution', label: 'Relatório de evolução', desc: 'Comparativo + tendências', active: true },
              { id: 'consult', label: 'Resumo de consulta', desc: 'Para próxima visita' },
              { id: 'discharge', label: 'Encerramento de ciclo', desc: 'Marcos e próximos passos' },
            ].map((r) => (
              <button key={r.id} className="lpr-btn" style={{
                display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', textAlign: 'left',
                border: `1px solid ${r.active ? T.p600 : T.border}`, borderRadius: 8, cursor: 'pointer',
                background: r.active ? T.p50 : T.bg, color: T.text, width: '100%',
                boxShadow: r.active ? `0 0 0 3px ${T.p100}` : 'none',
              }}>
                <Icons.FileText size={14} color={r.active ? T.p700 : T.textMute} style={{ marginTop: 2 }}/>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: r.active ? T.p700 : T.text }}>{r.label}</div>
                  <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 1 }}>{r.desc}</div>
                </div>
              </button>
            ))}
          </div>
        </Card>

        <Card T={T} title="Conteúdo do relatório">
          {[
            ['8 domínios — semáforo + score', true],
            ['Padrão emergente identificado', true],
            ['Exames analisados (14)', true],
            ['Questionários aplicados (8)', true],
            ['Dados faltantes', true],
            ['Alertas relevantes', true],
            ['Decisões do Safety Engine', true],
            ['Intervenções ativas', true],
            ['Plano para próximo ciclo', true],
            ['Anexar gráficos longitudinais', false],
            ['Anexar exames originais (PDF)', false],
          ].map(([label, on], i) => (
            <label key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', fontSize: 12.5, color: T.text, cursor: 'pointer' }}>
              <input type="checkbox" defaultChecked={on} style={{ accentColor: T.p600, width: 14, height: 14 }}/>
              <span>{label}</span>
            </label>
          ))}
        </Card>

        <div style={{ display: 'flex', gap: 8 }}>
          <Button T={T} kind="primary" size="md" full icon={<Icons.Download/>}>Exportar PDF</Button>
          <Button T={T} kind="secondary" size="md" icon={<Icons.Send/>}>Enviar</Button>
        </div>
      </div>

      {/* Preview */}
      <Card T={T} padding={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '10px 14px', background: T.surface, borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 12, color: T.textMute }}>Pré-visualização A4</span>
          <div style={{ flex: 1 }}/>
          <span style={{ fontSize: 11, color: T.textMute }}>Página 1 de 6 · LPR-EVO-MC-04219</span>
        </div>
        <div style={{ padding: 32, background: '#fff', color: '#1f2937', fontFamily: T.fontUI, minHeight: 760 }}>
          {/* Header */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', borderBottom: `2px solid #0d9488`, paddingBottom: 14 }}>
            <div>
              <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, letterSpacing: -0.4, color: '#1f2937' }}>L<span style={{ color: '#0d9488' }}>P</span>R</span>
                <span style={{ fontSize: 11, fontWeight: 500, letterSpacing: 0.4, color: '#6b7280', textTransform: 'uppercase' }}>Platform</span>
              </div>
              <div style={{ fontSize: 11, color: '#6b7280', marginTop: 4 }}>Longevium Clínica Médica · CNES 7849-2</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: '#6b7280' }}>Relatório de evolução</div>
              <div style={{ fontSize: 12, fontWeight: 600, color: '#1f2937', marginTop: 2 }}>03 de maio de 2026</div>
            </div>
          </div>

          <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, fontSize: 12 }}>
            <div>
              <div style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, letterSpacing: 0.2, textTransform: 'uppercase' }}>Paciente</div>
              <div style={{ fontSize: 16, fontWeight: 700, color: '#1f2937', marginTop: 2 }}>{p.name}</div>
              <div style={{ color: '#4b5563', marginTop: 1 }}>{p.age} anos · {p.sex} · {p.mrn}</div>
            </div>
            <div>
              <div style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, letterSpacing: 0.2, textTransform: 'uppercase' }}>Protocolo</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#1f2937', marginTop: 2 }}>{p.protocol}</div>
              <div style={{ color: '#4b5563', marginTop: 1 }}>{p.protocolShort} · {p.cycle}</div>
            </div>
          </div>

          <div style={{ marginTop: 22, padding: 14, background: '#f0fdfa', border: '1px solid #ccfbf1', borderRadius: 8 }}>
            <div style={{ fontSize: 10.5, color: '#0f766e', fontWeight: 600, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 4 }}>Síntese clínica</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#134e4a', lineHeight: 1.4 }}>
              Score global LPR <strong>58</strong> (+16 pts em 60d). Padrão emergente: <strong>desregulação circadiana como driver metabólico</strong>. Recomendação: continuar Fase 1 (Reset Circadiano) antes de qualquer intervenção metabólica.
            </div>
          </div>

          <div style={{ marginTop: 22 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: '#1f2937', marginBottom: 8, letterSpacing: -0.1 }}>1. Resumo dos 8 domínios</div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
              <thead>
                <tr style={{ background: '#f9fafb' }}>
                  <th style={{ textAlign: 'left', padding: '6px 8px', color: '#6b7280', fontWeight: 600, fontSize: 10 }}>DOMÍNIO</th>
                  <th style={{ textAlign: 'left', padding: '6px 8px', color: '#6b7280', fontWeight: 600, fontSize: 10 }}>SCORE</th>
                  <th style={{ textAlign: 'left', padding: '6px 8px', color: '#6b7280', fontWeight: 600, fontSize: 10 }}>SEMÁFORO</th>
                  <th style={{ textAlign: 'left', padding: '6px 8px', color: '#6b7280', fontWeight: 600, fontSize: 10 }}>VAR. SEM.</th>
                  <th style={{ textAlign: 'left', padding: '6px 8px', color: '#6b7280', fontWeight: 600, fontSize: 10 }}>DRIVER PRINCIPAL</th>
                </tr>
              </thead>
              <tbody>
                {LPR_DOMAINS.map((d) => {
                  const dom = p.domains[d.id];
                  const c = dom.semaphore === 'red' ? '#ef4444' : dom.semaphore === 'yellow' ? '#f59e0b' : '#10b981';
                  return (
                    <tr key={d.id} style={{ borderBottom: '1px solid #e5e7eb' }}>
                      <td style={{ padding: '7px 8px', color: '#1f2937', fontWeight: 500 }}>{d.label}</td>
                      <td style={{ padding: '7px 8px', fontFamily: T.fontMono, fontWeight: 600, color: c }}>{dom.score}</td>
                      <td style={{ padding: '7px 8px' }}><span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: '50%', background: c }}/></td>
                      <td style={{ padding: '7px 8px', color: dom.delta >= 0 ? '#10b981' : '#ef4444', fontWeight: 600 }}>{dom.delta >= 0 ? '+' : ''}{dom.delta}</td>
                      <td style={{ padding: '7px 8px', color: '#4b5563' }}>{dom.drivers[0]}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div style={{ marginTop: 22 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: '#1f2937', marginBottom: 8, letterSpacing: -0.1 }}>2. Decisões do Safety Engine — ciclo atual</div>
            {SAFETY_HISTORY.map((d, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, fontSize: 11.5, padding: '6px 0', borderBottom: i < SAFETY_HISTORY.length - 1 ? '1px solid #e5e7eb' : 0 }}>
                <span style={{ fontFamily: T.fontMono, color: '#6b7280', width: 60 }}>{d.date}</span>
                <span style={{ width: 90, fontWeight: 600, color: d.decision === 'Block' ? '#ef4444' : d.decision === 'Modify' || d.decision === 'Postpone' ? '#f59e0b' : '#10b981' }}>{d.decision.toUpperCase()}</span>
                <span style={{ flex: 1, color: '#1f2937' }}>{d.intervention} — <span style={{ color: '#6b7280' }}>{d.reason}</span></span>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 22, fontSize: 11, color: '#6b7280', borderTop: '1px solid #e5e7eb', paddingTop: 10, display: 'flex', justifyContent: 'space-between' }}>
            <span>Dr. Helena Marques · CRM 142.387 · helena.marques@longevium.com.br</span>
            <span>LPR Platform v1.4.2 · Documento assinado digitalmente</span>
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { ExamsScreen, QuestionnairesScreen, AlertsScreen, EvolutionScreen, ReportScreen, CrossPlot });
