// LPR Platform — Patient overview, Domains, Exams, Questionnaires, Alerts, Evolution

// ─────────────────────────────────────────────────────────────
// 4. Patient overview (Mariana)
// ─────────────────────────────────────────────────────────────
function PatientOverviewScreen({ T, onNavigate }) {
  const p = MARIANA;
  const [tab, setTab] = React.useState('overview');
  const sem = STATUS_COLOR(T)[p.semaphore];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* Patient header card */}
      <Card T={T} padding={20}>
        <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start' }}>
          <Avatar name={p.name} T={T} size={56}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <span style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.4 }}>{p.name}</span>
              <span style={{ fontSize: 13, color: T.textMute }}>{p.age} anos · {p.sex === 'F' ? 'Feminino' : 'Masculino'} · {p.mrn}</span>
              <Pill T={T} tone="primary" icon={<Icons.GitBranch size={11}/>}>{p.protocolShort}</Pill>
              <Pill T={T} tone="warning">{p.phase}</Pill>
              <Pill T={T} tone="error" icon={<Icons.ShieldX size={11}/>}>Safety: GLP-1 bloqueado</Pill>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 6, fontSize: 12, color: T.textMute }}>
              <span>Início: {p.startedAt}</span>
              <span>·</span>
              <span>{p.cycle}</span>
              <span>·</span>
              <span>Último check-in: {p.lastCheckinFull}</span>
              <span>·</span>
              <span>Médico: {p.doctor}</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button T={T} kind="ghost" size="sm" icon={<Icons.Mail/>}>Mensagem</Button>
            <Button T={T} kind="secondary" size="sm" icon={<Icons.FileText/>} onClick={() => onNavigate && onNavigate('report')}>Gerar relatório</Button>
            <Button T={T} kind="primary" size="sm" icon={<Icons.Edit/>}>Anotar consulta</Button>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ marginTop: 16 }}>
          <Tabs T={T} active={tab} onChange={setTab} tabs={[
            { id: 'overview', label: 'Visão geral' },
            { id: 'domains', label: 'Domínios', count: 8 },
            { id: 'exams', label: 'Exames', count: 14 },
            { id: 'q', label: 'Questionários', count: 10 },
            { id: 'safety', label: 'Safety Engine', count: 4 },
            { id: 'evol', label: 'Evolução' },
            { id: 'plan', label: 'Plano clínico' },
            { id: 'history', label: 'Histórico' },
          ]}/>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16 }}>
        {/* Left column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Score + classification */}
          <Card T={T} padding={20}>
            <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 24, alignItems: 'center' }}>
              <ScoreRing T={T} value={p.scoreGlobal} delta={p.scoreGlobalDelta} max={100} status={p.semaphore}/>
              <div>
                <div style={{ fontSize: 11, color: T.textMute, fontWeight: 500, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 4 }}>
                  Padrão emergente identificado
                </div>
                <div style={{ fontFamily: T.fontDisplay, fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.2, lineHeight: 1.3 }}>
                  {p.classification.pattern}
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 14, paddingTop: 14, borderTop: `1px solid ${T.border}` }}>
                  <ClassificationCell T={T} role="Leader" domain={p.classification.leader} tone="warning" desc="Driver primário"/>
                  <ClassificationCell T={T} role="Amplifier" domain={p.classification.amplifier} tone="error" desc="Amplifica risco"/>
                  <ClassificationCell T={T} role="Saboteur" domain={p.classification.saboteur} tone="error" desc="Bloqueia progresso"/>
                </div>
              </div>
            </div>
          </Card>

          {/* 8-domain semaforos */}
          <Card T={T} title="Semáforo dos 8 domínios" subtitle="Score atual · variação semana" padding={0}
            action={
              <div style={{ display: 'flex', gap: 6 }}>
                <Pill T={T} tone="success">{Object.values(p.domains).filter((d) => d.semaphore === 'green').length} verde</Pill>
                <Pill T={T} tone="warning">{Object.values(p.domains).filter((d) => d.semaphore === 'yellow').length} amarelo</Pill>
                <Pill T={T} tone="error">{Object.values(p.domains).filter((d) => d.semaphore === 'red').length} vermelho</Pill>
              </div>
            }>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, padding: 12 }}>
              {LPR_DOMAINS.map((d, i) => {
                const dom = p.domains[d.id];
                const Ic = Icons[d.icon];
                const sc = STATUS_COLOR(T)[dom.semaphore];
                return (
                  <div key={d.id} style={{
                    padding: 12, borderRadius: 8, cursor: 'pointer',
                    background: 'transparent', position: 'relative',
                  }}
                    onClick={() => onNavigate && onNavigate('domains')}
                    onMouseEnter={(e) => e.currentTarget.style.background = T.surfaceAlt}
                    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                      <span style={{
                        width: 28, height: 28, borderRadius: 8, background: sc.bg,
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      }}><Ic size={14} color={sc.fg}/></span>
                      <span style={{ fontSize: 12, fontWeight: 600, color: T.text }}>{d.label}</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                      <span style={{
                        fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, letterSpacing: -0.4,
                        color: sc.fg, fontVariantNumeric: 'tabular-nums',
                      }}>{dom.score}</span>
                      <Trend value={dom.delta} T={T}/>
                    </div>
                    <Sparkline T={T} values={dom.lastTrend} color={sc.fg} fill={sc.bg} width={140} height={24} strokeWidth={1.5}/>
                  </div>
                );
              })}
            </div>
          </Card>

          {/* Score evolution */}
          <Card T={T} title="Evolução do score global LPR" subtitle="Últimas 10 semanas"
            action={
              <div style={{ display: 'flex', gap: 6 }}>
                {['7d','30d','90d','6m','1a'].map((t, i) => (
                  <button key={t} className="lpr-btn" style={{
                    padding: '4px 10px', fontSize: 11.5, borderRadius: 6, cursor: 'pointer',
                    border: `1px solid ${i === 1 ? T.p600 : T.border}`,
                    background: i === 1 ? T.p50 : T.bg, color: i === 1 ? T.p700 : T.textSoft, fontWeight: 500,
                  }}>{t}</button>
                ))}
              </div>
            }>
            <ScoreChart T={T} values={p.scoreTrend} events={[
              { i: 2, label: 'Reset Circadiano' },
              { i: 6, label: 'Bloqueio GLP-1' },
            ]}/>
          </Card>
        </div>

        {/* Right column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Next action */}
          <Card T={T} padding={0} style={{ overflow: 'hidden' }}>
            <div style={{ padding: '14px 16px 12px', background: T.p50, borderBottom: `1px solid ${T.p100}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icons.Target size={14} color={T.p700}/>
                <span style={{ fontSize: 11, fontWeight: 600, color: T.p700, letterSpacing: 0.2, textTransform: 'uppercase' }}>Próxima ação sugerida pelo sistema</span>
              </div>
              <div style={{ fontFamily: T.fontDisplay, fontSize: 16, fontWeight: 600, color: T.text, marginTop: 6, letterSpacing: -0.2 }}>
                {p.nextAction.title}
              </div>
              <div style={{ fontSize: 12.5, color: T.textSoft, marginTop: 4, lineHeight: 1.5 }}>
                {p.nextAction.rationale}
              </div>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 8 }}>
                <Icons.ShieldX size={11} color={T.error} style={{ marginRight: 4 }}/> Bloqueado pelo Safety Engine
              </div>
              {p.nextAction.blocks.map((b, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', fontSize: 12.5, color: T.text }}>
                  <Icons.X size={12} color={T.error}/> <span style={{ fontWeight: 500 }}>{b.name}</span>
                </div>
              ))}
              <div style={{ height: 12 }}/>
              <div style={{ fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 8 }}>
                <Icons.Check size={11} color={T.success} style={{ marginRight: 4 }}/> Plano ativo
              </div>
              {p.nextAction.activates.map((a, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '6px 0', fontSize: 12.5, color: T.textSoft }}>
                  <Icons.Check size={12} color={T.success} style={{ marginTop: 2, flexShrink: 0 }}/> <span>{a}</span>
                </div>
              ))}
              <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                <Button T={T} kind="primary" size="sm" full icon={<Icons.Shield/>} onClick={() => onNavigate && onNavigate('safety')}>Abrir Safety Engine</Button>
              </div>
            </div>
          </Card>

          {/* Recent alerts */}
          <Card T={T} title="Alertas recentes" subtitle="Últimos 3 dias"
            action={<Button T={T} kind="ghost" size="sm" iconRight={<Icons.ChevronR/>} onClick={() => onNavigate && onNavigate('alerts')}>Ver todos</Button>}
            padding={0}>
            {ALERTS.filter((a) => a.patient === p.name && a.for === 'doctor').slice(0, 4).map((a, i, arr) => (
              <div key={a.id} style={{ display: 'flex', gap: 10, padding: '10px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0 }}>
                <Dot T={T} status={a.sev === 'high' ? 'red' : a.sev === 'medium' ? 'yellow' : 'gray'} size={8}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, color: T.text, lineHeight: 1.4 }}>{a.text}</div>
                  <div style={{ fontSize: 11, color: T.textMute, marginTop: 2 }}>{a.when}</div>
                </div>
              </div>
            ))}
          </Card>

          {/* Missing data */}
          <Card T={T} title="Dados faltantes" subtitle="Cobertura: 78% dos marcadores requeridos">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { name: 'PSS-10 (Estresse)', kind: 'questionário', overdue: '14d' },
                { name: 'Composição corporal DEXA', kind: 'exame', overdue: 'pendente validação' },
                { name: 'Calprotectina fecal', kind: 'exame plus', overdue: 'não solicitado' },
                { name: 'Actigrafia 7 dias', kind: 'wearable', overdue: 'sincronização' },
              ].map((m, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
                  background: T.surfaceAlt, borderRadius: 6,
                }}>
                  <Icons.AlertCir size={14} color={T.warning}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 500, color: T.text }}>{m.name}</div>
                    <div style={{ fontSize: 11, color: T.textMute, textTransform: 'capitalize' }}>{m.kind} · {m.overdue}</div>
                  </div>
                  <Button T={T} kind="ghost" size="sm">Solicitar</Button>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function ScoreRing({ T, value, max, delta, status }) {
  const sc = STATUS_COLOR(T)[status];
  const r = 56, c = 2 * Math.PI * r;
  const off = c - (value / max) * c;
  return (
    <div style={{ position: 'relative', width: 140, height: 140, alignSelf: 'center', justifySelf: 'center' }}>
      <svg width="140" height="140" viewBox="0 0 140 140">
        <circle cx="70" cy="70" r={r} fill="none" stroke={T.surfaceAlt} strokeWidth="10"/>
        <circle cx="70" cy="70" r={r} fill="none" stroke={sc.fg} strokeWidth="10" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={off} transform="rotate(-90 70 70)"/>
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ fontSize: 10.5, color: T.textMute, fontWeight: 500, letterSpacing: 0.2, textTransform: 'uppercase' }}>Score LPR</span>
        <span style={{ fontFamily: T.fontDisplay, fontSize: 38, fontWeight: 700, color: T.text, letterSpacing: -1, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
        <span style={{ fontSize: 11, color: T.textMute, marginTop: 1 }}>de {max}</span>
        <div style={{ marginTop: 4 }}><Trend value={delta} T={T} suffix=" sem"/></div>
      </div>
    </div>
  );
}

function ClassificationCell({ T, role, domain, tone, desc }) {
  const d = LPR_DOMAINS.find((x) => x.id === domain);
  const Ic = d ? Icons[d.icon] : Icons.Activity;
  return (
    <div>
      <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 600, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 4 }}>{role}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Ic size={14} color={tone === 'error' ? T.error : T.warning}/>
        <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{d?.label}</span>
      </div>
      <div style={{ fontSize: 11, color: T.textMute, marginTop: 2 }}>{desc}</div>
    </div>
  );
}

function ScoreChart({ T, values, height = 200, events = [] }) {
  const w = 600, h = height;
  const min = 0, max = 100;
  const dx = w / (values.length - 1);
  const pts = values.map((v, i) => [i * dx, h - 30 - ((v - min) / (max - min)) * (h - 50)]);
  const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0]},${p[1]}`).join(' ');
  const area = `${d} L${w},${h - 30} L0,${h - 30} Z`;
  return (
    <div style={{ position: 'relative', width: '100%' }}>
      <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" style={{ display: 'block' }}>
        {/* Threshold bands */}
        <rect x="0" y={h - 30 - (33 / 100) * (h - 50)} width={w} height={(33 / 100) * (h - 50)} fill={T.errorBg} opacity="0.35"/>
        <rect x="0" y={h - 30 - (66 / 100) * (h - 50)} width={w} height={(33 / 100) * (h - 50)} fill={T.warningBg} opacity="0.35"/>
        <rect x="0" y={h - 30 - (100 / 100) * (h - 50)} width={w} height={(34 / 100) * (h - 50)} fill={T.successBg} opacity="0.35"/>

        {/* Grid lines */}
        {[0, 25, 50, 75, 100].map((g) => (
          <g key={g}>
            <line x1="0" x2={w} y1={h - 30 - (g / 100) * (h - 50)} y2={h - 30 - (g / 100) * (h - 50)} stroke={T.border} strokeDasharray="3 3"/>
            <text x="6" y={h - 30 - (g / 100) * (h - 50) - 3} fontSize="9" fill={T.textMute}>{g}</text>
          </g>
        ))}

        {/* Area + line */}
        <path d={area} fill={T.p100} opacity="0.5"/>
        <path d={d} fill="none" stroke={T.p600} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round"/>

        {/* Dots */}
        {pts.map((p, i) => (
          <circle key={i} cx={p[0]} cy={p[1]} r="3" fill={T.bg} stroke={T.p600} strokeWidth="2"/>
        ))}

        {/* Event markers */}
        {events.map((e, i) => (
          <g key={i}>
            <line x1={pts[e.i][0]} x2={pts[e.i][0]} y1={10} y2={h - 30} stroke={T.warning} strokeDasharray="2 3"/>
            <rect x={pts[e.i][0] + 4} y={10 + i * 18} width={(e.label.length * 5.5) + 12} height={16} rx="3" fill={T.warningBg} stroke={T.warningBorder}/>
            <text x={pts[e.i][0] + 10} y={22 + i * 18} fontSize="9" fill={T.warning} fontWeight="600">{e.label}</text>
          </g>
        ))}

        {/* Week labels */}
        {values.map((v, i) => (
          <text key={i} x={i * dx} y={h - 12} fontSize="9.5" fill={T.textMute} textAnchor={i === 0 ? 'start' : i === values.length - 1 ? 'end' : 'middle'}>S{i + 1}</text>
        ))}
      </svg>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 5. Domains screen
// ─────────────────────────────────────────────────────────────
function DomainsScreen({ T, onNavigate }) {
  const p = MARIANA;
  const [selected, setSelected] = React.useState('circadian');
  const dom = p.domains[selected];
  const meta = LPR_DOMAINS.find((d) => d.id === selected);
  const sc = STATUS_COLOR(T)[dom.semaphore];
  const Ic = Icons[meta.icon];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 16 }}>
      {/* Left rail — domain list */}
      <Card T={T} padding={0} style={{ height: 'fit-content', position: 'sticky', top: 0 }}>
        <div style={{ padding: '14px 14px 8px' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>8 domínios LPR</div>
          <div style={{ fontSize: 11, color: T.textMute, marginTop: 2 }}>{p.name}</div>
        </div>
        <div style={{ borderTop: `1px solid ${T.border}` }}>
          {LPR_DOMAINS.map((d) => {
            const dd = p.domains[d.id];
            const dsc = STATUS_COLOR(T)[dd.semaphore];
            const on = selected === d.id;
            const Di = Icons[d.icon];
            return (
              <button key={d.id} className="lpr-btn" onClick={() => setSelected(d.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '11px 14px',
                  border: 0, background: on ? T.p50 : 'transparent', cursor: 'pointer', textAlign: 'left',
                  borderLeft: `3px solid ${on ? T.p600 : 'transparent'}`,
                }}>
                <span style={{ width: 28, height: 28, background: dsc.bg, borderRadius: 6, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Di size={13} color={dsc.fg}/>
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: on ? 600 : 500, color: on ? T.p700 : T.text }}>{d.label}</div>
                  <div style={{ fontSize: 11, color: T.textMute, display: 'flex', alignItems: 'center', gap: 5 }}>
                    Score {dd.score} <Trend value={dd.delta} T={T}/>
                  </div>
                </div>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: dsc.fg }}/>
              </button>
            );
          })}
        </div>
      </Card>

      {/* Right — selected domain detail */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Card T={T} padding={20}>
          <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
            <span style={{
              width: 60, height: 60, borderRadius: 12, background: sc.bg,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <Ic size={28} color={sc.fg}/>
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 11, color: T.textMute, fontWeight: 500, letterSpacing: 0.2, textTransform: 'uppercase' }}>Domínio</span>
                <Pill T={T} tone={dom.semaphore === 'red' ? 'error' : dom.semaphore === 'yellow' ? 'warning' : 'success'}>
                  {sc.label}
                </Pill>
              </div>
              <div style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.4, marginTop: 2 }}>
                {meta.label}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: T.textMute, fontWeight: 500, letterSpacing: 0.2, textTransform: 'uppercase' }}>Score atual</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
                <span style={{ fontFamily: T.fontDisplay, fontSize: 36, fontWeight: 700, color: sc.fg, letterSpacing: -0.8, fontVariantNumeric: 'tabular-nums' }}>{dom.score}</span>
                <span style={{ fontSize: 13, color: T.textMute }}>/ 100</span>
                <Trend value={dom.delta} T={T} suffix=" sem"/>
              </div>
            </div>
          </div>

          {/* Trend tabs */}
          <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {[{ d: '7d', t: dom.lastTrend.slice(-3), delta: '+2' },
              { d: '30d', t: dom.lastTrend, delta: `${dom.delta >= 0 ? '+' : ''}${dom.delta}` },
              { d: '90d', t: [25, 28, 31, 30, 32, 36, 38], delta: '+13' }].map((tr, i) => (
              <div key={i} style={{ padding: 12, background: T.surface, borderRadius: 8, border: `1px solid ${T.border}` }}>
                <div style={{ fontSize: 11, color: T.textMute, fontWeight: 500, textTransform: 'uppercase' }}>Tendência {tr.d}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
                  <Sparkline T={T} values={tr.t} color={sc.fg} fill={sc.bg} width={100} height={28} strokeWidth={1.6}/>
                  <span style={{ fontSize: 13, fontWeight: 600, color: tr.delta.startsWith('-') ? T.error : T.success }}>{tr.delta}</span>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          {/* Drivers */}
          <Card T={T} title="Principais drivers do score" subtitle="O que está puxando esse domínio">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {dom.drivers.map((d, i) => {
                const weights = [38, 32, 18, 12];
                return (
                  <div key={i}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                      <span style={{ fontSize: 12.5, color: T.text, fontWeight: 500 }}>{d}</span>
                      <span style={{ fontSize: 11, color: T.textMute, fontVariantNumeric: 'tabular-nums' }}>{weights[i] || 8}%</span>
                    </div>
                    <Meter T={T} value={weights[i] || 8} max={50} color={sc.fg}/>
                  </div>
                );
              })}
            </div>
          </Card>

          {/* Available + missing data */}
          <Card T={T} title="Dados disponíveis & faltantes" padding={0}>
            <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.border}` }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 600, color: T.text }}>Cobertura do domínio</span>
                <span style={{ fontSize: 12, fontWeight: 600, color: T.success, fontVariantNumeric: 'tabular-nums' }}>76%</span>
              </div>
              <Meter T={T} value={76} color={T.success}/>
            </div>
            <div style={{ padding: '10px 16px' }}>
              {(selected === 'circadian' ? [
                { name: 'Actigrafia 7d', ok: true },
                { name: 'PSQI mensal', ok: true },
                { name: 'Hora de início do sono', ok: true },
                { name: 'CGM noturno', ok: true },
                { name: 'Polissonografia', ok: false },
                { name: 'Cortisol AM/PM', ok: false },
              ] : [
                { name: 'CGM 14d', ok: true }, { name: 'HbA1c', ok: true }, { name: 'Insulina jejum', ok: true },
                { name: 'Composição corporal', ok: false },
              ]).map((m, i, arr) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0',
                  borderBottom: i < arr.length - 1 ? `1px dashed ${T.border}` : 0,
                }}>
                  {m.ok ? <Icons.Check size={13} color={T.success}/> : <Icons.AlertCir size={13} color={T.warning}/>}
                  <span style={{ fontSize: 12, color: m.ok ? T.text : T.textMute, flex: 1 }}>{m.name}</span>
                  {m.ok ? <Pill T={T} tone="success">Coletado</Pill> : <Pill T={T} tone="warning">Faltante</Pill>}
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* Related items */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
          <Card T={T} title="Exames relacionados" padding={0}>
            {EXAMS_PANEL.filter((e) => e.domain === selected || (selected === 'circadian' && false)).slice(0, 5).map((e, i, arr) => (
              <div key={i} style={{ padding: '10px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0, display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color: T.text }}>{e.name}</div>
                  <div style={{ fontSize: 11, color: T.textMute }}>Ref. protocolo: {e.refProto} {e.unit}</div>
                </div>
                <span style={{ fontFamily: T.fontMono, fontSize: 12.5, fontWeight: 600, color: e.status === 'normal' ? T.success : e.status === 'borderline' ? T.warning : T.error }}>
                  {e.value} <span style={{ fontSize: 10, color: T.textMute, fontWeight: 500 }}>{e.unit}</span>
                </span>
              </div>
            ))}
            {selected === 'circadian' ? <div style={{ padding: '14px 16px', fontSize: 12, color: T.textMute, textAlign: 'center' }}>Sem exames laboratoriais associados — domínio rastreado por wearables e questionários.</div> : null}
          </Card>

          <Card T={T} title="Questionários relacionados" padding={0}>
            {QUESTIONNAIRES.filter((q) => q.domains.includes(selected)).map((q, i, arr) => (
              <div key={q.id} style={{ padding: '10px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span style={{ fontSize: 12.5, fontWeight: 500, color: T.text }}>{q.name}</span>
                  <Pill T={T} tone={q.score == null ? 'warning' : 'neutral'}>{q.freq}</Pill>
                </div>
                <div style={{ fontSize: 11, color: T.textMute, marginTop: 2 }}>
                  {q.score != null ? <>Último: {q.score}{q.max ? ` / ${q.max}` : ''} · {q.last}</> : 'Pendente'}
                </div>
              </div>
            ))}
          </Card>

          <Card T={T} title="Métricas monitoradas" padding={0}>
            {[
              { name: 'Início do sono', value: '01:32', goal: '< 23:30', bad: true },
              { name: 'Duração do sono', value: '6h 12m', goal: '7–9h', bad: true },
              { name: 'Eficiência do sono', value: '78%', goal: '> 85%', bad: true },
              { name: 'HRV (rMSSD)', value: '28ms', goal: '> 35ms', bad: true },
              { name: 'Jet lag social', value: '2h08', goal: '< 1h', bad: true },
            ].map((m, i, arr) => (
              <div key={i} style={{ padding: '10px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0, display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, color: T.text, fontWeight: 500 }}>{m.name}</div>
                  <div style={{ fontSize: 11, color: T.textMute }}>Meta: {m.goal}</div>
                </div>
                <span style={{
                  fontFamily: T.fontMono, fontSize: 12.5, fontWeight: 600,
                  color: m.bad ? T.error : T.success, fontVariantNumeric: 'tabular-nums',
                }}>{m.value}</span>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PatientOverviewScreen, DomainsScreen, ScoreRing, ScoreChart, ClassificationCell });
