// LPR Platform — Safety Engine, Patient mobile (Daily, Home), Protocol config, Rules builder

// 10. Safety Engine screen
function SafetyEngineScreen({ T }) {
  const [decision, setDecision] = React.useState('block');
  const [overrideOpen, setOverrideOpen] = React.useState(false);
  const [justification, setJustification] = React.useState('');
  const decisionMap = {
    allow:    { tone: 'success', label: 'Allow',    fg: T.success, bg: T.successBg, border: T.successBorder, desc: 'Intervenção autorizada' },
    caution:  { tone: 'warning', label: 'Caution',  fg: T.warning, bg: T.warningBg, border: T.warningBorder, desc: 'Cautela — monitorar de perto' },
    modify:   { tone: 'warning', label: 'Modify',   fg: T.warning, bg: T.warningBg, border: T.warningBorder, desc: 'Adaptar protocolo' },
    postpone: { tone: 'warning', label: 'Postpone', fg: T.warning, bg: T.warningBg, border: T.warningBorder, desc: 'Postergar intervenção' },
    block:    { tone: 'error',   label: 'Block',    fg: T.error,   bg: T.errorBg,   border: T.errorBorder,   desc: 'Contraindicado temporariamente' },
    review:   { tone: 'info',    label: 'Require Medical Review', fg: T.info, bg: T.infoBg, border: T.infoBorder, desc: 'Exige revisão médica' },
  };
  const d = decisionMap[decision];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Hero */}
        <Card T={T} padding={0} style={{ overflow: 'hidden', borderTop: `4px solid ${d.fg}` }}>
          <div style={{ padding: '20px 22px', display: 'flex', gap: 18, alignItems: 'flex-start' }}>
            <span style={{
              width: 56, height: 56, borderRadius: 14, background: d.bg, border: `1px solid ${d.border}`,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              {decision === 'block' ? <Icons.ShieldX size={28} color={d.fg}/> : decision === 'allow' ? <Icons.ShieldChk size={28} color={d.fg}/> : <Icons.Shield size={28} color={d.fg}/>}
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 11, color: T.textMute, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>Intervenção proposta</span>
                <Pill T={T} tone="neutral">Mariana Corrêa · LPR-LR-1</Pill>
              </div>
              <div style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.4, marginTop: 4 }}>
                GLP-1 (semaglutida 0.25mg)
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 8, flexWrap: 'wrap' }}>
                <div style={{
                  padding: '8px 14px', borderRadius: 8, background: d.bg, border: `1px solid ${d.border}`,
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: d.fg }}/>
                  <span style={{ fontSize: 13, fontWeight: 700, color: d.fg, letterSpacing: 0.2 }}>{d.label.toUpperCase()}</span>
                  <span style={{ fontSize: 12, color: T.textSoft }}>· {d.desc}</span>
                </div>
                <span style={{ fontSize: 11.5, color: T.textMute }}>Decidido em 01/05/2026 · 11:42 · Sistema</span>
              </div>
            </div>
          </div>

          {/* Status semáforo strip */}
          <div style={{ padding: '14px 22px', borderTop: `1px solid ${T.border}`, background: T.surface }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 8 }}>Status de segurança por dimensão</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
              {[
                { label: 'Adesão', state: 'red', val: '58%' },
                { label: 'Massa magra', state: 'yellow', val: '-0.4 kg/mês' },
                { label: 'Sono', state: 'red', val: 'PSQI 11' },
                { label: 'Cortisol AM', state: 'yellow', val: '22 µg/dL' },
                { label: 'HbA1c', state: 'green', val: '5.6%' },
                { label: 'Função renal', state: 'green', val: 'eGFR 92' },
                { label: 'Suporte nutricional', state: 'gray', val: 'sem dados' },
                { label: 'Comportamental', state: 'red', val: 'crítico' },
              ].map((s, i) => {
                const c = STATUS_COLOR(T)[s.state];
                return (
                  <div key={i} style={{ padding: 10, background: T.bg, borderRadius: 6, border: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: '50%', background: c.fg, boxShadow: `0 0 0 3px ${c.bg}` }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 11, color: T.textMute }}>{s.label}</div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: T.text, fontVariantNumeric: 'tabular-nums' }}>{s.val}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </Card>

        {/* Why this decision */}
        <Card T={T} title="Motivo da decisão" subtitle="Regras acionadas + conflitos detectados">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 8 }}>Regras acionadas (2)</div>
              {[{ id: 'R-014', label: 'Bloquear GLP-1 se adesão crítica', sev: 'high' },
                { id: 'R-022', label: 'Revisão médica obrigatória — comportamento crítico', sev: 'high' }].map((r) => (
                <div key={r.id} style={{
                  padding: '8px 10px', borderRadius: 6, background: T.errorBg, border: `1px solid ${T.errorBorder}`,
                  marginBottom: 6, display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <span style={{ fontFamily: T.fontMono, fontSize: 11, fontWeight: 700, color: T.error, padding: '2px 6px', background: T.bg, borderRadius: 4 }}>{r.id}</span>
                  <span style={{ fontSize: 12.5, color: T.text, flex: 1 }}>{r.label}</span>
                </div>
              ))}
            </div>
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 8 }}>Conflitos interdomínios (3)</div>
              {[
                'Adesão (red) × Intervenção farmacológica',
                'Comportamental (red) × Mudança alimentar imposta',
                'Massa magra ↓ × Restrição calórica esperada com GLP-1',
              ].map((c, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, padding: '6px 0', fontSize: 12.5, color: T.textSoft, borderBottom: i < 2 ? `1px dashed ${T.border}` : 0 }}>
                  <Icons.AlertTri size={13} color={T.warning} style={{ marginTop: 2, flexShrink: 0 }}/>
                  <span>{c}</span>
                </div>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 16, padding: 14, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 6 }}>Próxima ação sugerida</div>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: T.text, marginBottom: 4 }}>Estabilizar comportamento + circadiano antes de reavaliar GLP-1</div>
            <div style={{ fontSize: 12.5, color: T.textSoft, lineHeight: 1.5 }}>
              Continuar Fase 1 (Reset Circadiano) por 14 dias. Reavaliar com adesão ≥ 75% por 4 semanas consecutivas e PSQI &lt; 8. Estimativa: <strong style={{ color: T.text }}>4–6 semanas</strong>.
            </div>
          </div>
        </Card>

        {/* Missing data */}
        <Card T={T} title="Dados faltantes para esta decisão" subtitle="2 itens não disponíveis no momento da avaliação">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {[
              { name: 'Composição corporal (DEXA)', kind: 'Exame plus', impact: 'Não pode quantificar massa magra basal' },
              { name: 'GAD-7 atualizado', kind: 'Questionário', impact: 'Componente ansiedade do escore comportamental' },
            ].map((m, i) => (
              <div key={i} style={{ padding: 12, background: T.warningBg, border: `1px solid ${T.warningBorder}`, borderRadius: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: T.warning }}>
                  <Icons.AlertCir size={13}/> {m.name}
                </div>
                <div style={{ fontSize: 11.5, color: T.textSoft, marginTop: 4 }}>{m.kind}</div>
                <div style={{ fontSize: 11.5, color: T.textSoft, marginTop: 4 }}>Impacto: {m.impact}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Right column — actions + history */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Card T={T} title="Ação médica">
          <div style={{ fontSize: 11.5, color: T.textMute, marginBottom: 10 }}>O médico pode confirmar a decisão do sistema, adaptar a intervenção, postergar ou aplicar override clínico.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Button T={T} kind="primary" size="md" full icon={<Icons.Check/>}>Aprovar decisão do sistema</Button>
            <Button T={T} kind="secondary" size="md" full icon={<Icons.Edit/>}>Adaptar intervenção</Button>
            <Button T={T} kind="secondary" size="md" full icon={<Icons.Clock/>}>Postergar avaliação</Button>
            <Button T={T} kind="warning" size="md" full icon={<Icons.AlertTri/>} onClick={() => setOverrideOpen(!overrideOpen)}>
              Override médico
            </Button>
          </div>

          {overrideOpen ? (
            <div style={{
              marginTop: 12, padding: 14, background: T.warningBg, border: `1px solid ${T.warningBorder}`, borderRadius: 8,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: T.warning, marginBottom: 6, letterSpacing: 0.2, textTransform: 'uppercase' }}>
                <Icons.AlertTri size={13}/> Override médico — campo obrigatório
              </div>
              <div style={{ fontSize: 11.5, color: T.textSoft, marginBottom: 8, lineHeight: 1.5 }}>
                Ao executar override, você assume responsabilidade clínica pela intervenção contra a recomendação do sistema. Esta decisão será registrada na auditoria.
              </div>
              <textarea value={justification} onChange={(e) => setJustification(e.target.value)}
                placeholder="Justificativa clínica obrigatória — descreva por que o benefício supera o risco identificado"
                style={{
                  width: '100%', minHeight: 80, fontFamily: T.fontUI, fontSize: 12.5, color: T.text,
                  padding: 10, borderRadius: 6, border: `1px solid ${T.warningBorder}`, background: T.bg,
                  resize: 'vertical', outline: 'none', boxSizing: 'border-box',
                }}/>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
                <label style={{ fontSize: 11.5, color: T.textSoft, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <input type="checkbox" style={{ accentColor: T.p600 }}/>
                  Notificar comitê clínico
                </label>
                <Button T={T} kind="danger" size="sm" disabled={justification.length < 20} icon={<Icons.AlertTri/>}>Confirmar override</Button>
              </div>
            </div>
          ) : null}
        </Card>

        <Card T={T} title="Mensagens">
          <div style={{ padding: 10, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 6, marginBottom: 8 }}>
            <div style={{ fontSize: 11, color: T.textMute, fontWeight: 600, marginBottom: 4 }}>Para o médico</div>
            <div style={{ fontSize: 12.5, color: T.textSoft, lineHeight: 1.5 }}>
              Adesão semanal abaixo de 60% combinada com escore comportamental crítico. GLP-1 traz alto risco de descontinuação precoce e perda de massa magra. Recomendamos estabilizar comportamento por ≥4 semanas.
            </div>
          </div>
          <div style={{ padding: 10, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 6 }}>
            <div style={{ fontSize: 11, color: T.textMute, fontWeight: 600, marginBottom: 4 }}>Para o paciente</div>
            <div style={{ fontSize: 12.5, color: T.textSoft, lineHeight: 1.5 }}>
              Antes de avançar para medicamento, vamos estabilizar seu sono e rotina. Isso aumenta sua chance de sucesso e protege sua massa magra.
            </div>
          </div>
        </Card>

        <Card T={T} title="Histórico de decisões" subtitle="Mariana Corrêa — Ciclo atual" padding={0}>
          {SAFETY_HISTORY.map((h, i) => {
            const dec = decisionMap[h.decision.toLowerCase()] || decisionMap.allow;
            return (
              <div key={h.id} style={{ padding: '11px 16px', borderBottom: i < SAFETY_HISTORY.length - 1 ? `1px solid ${T.border}` : 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: T.fontMono, fontSize: 11, color: T.textMute }}>{h.date}</span>
                  <Pill T={T} tone={dec.tone}>{dec.label}</Pill>
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: T.text, marginTop: 4 }}>{h.intervention}</div>
                <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 2 }}>{h.reason} · {h.rules.join(', ')}</div>
              </div>
            );
          })}
        </Card>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 14. Protocol config
// ─────────────────────────────────────────────────────────────
function ProtocolConfigScreen({ T }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card T={T} padding={20}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18 }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.4 }}>LPR — Lifestyle Precision Reset</span>
              <Pill T={T} tone="success" icon={<Icons.Check size={11}/>}>Publicado</Pill>
              <Pill T={T} tone="primary">v1.4.2</Pill>
            </div>
            <div style={{ fontSize: 12, color: T.textMute, marginTop: 4 }}>Publicado em 12/03/2026 por Dr. Helena Marques · Aplicado a 47 pacientes ativos</div>
          </div>
          <Button T={T} kind="ghost" size="sm" icon={<Icons.GitBranch/>}>v1.4.1 → v1.4.2 (diff)</Button>
          <Button T={T} kind="secondary" size="sm" icon={<Icons.Edit/>}>Nova versão (rascunho)</Button>
          <Button T={T} kind="primary" size="sm" icon={<Icons.Send/>}>Publicar protocolo</Button>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        <KPI T={T} label="Domínios cobertos" value="8" icon={<Icons.Layers/>}/>
        <KPI T={T} label="Marcadores rastreados" value="124" sub="exames + métricas" icon={<Icons.Activity/>}/>
        <KPI T={T} label="Questionários" value="10" sub="diários, sem., mensais" icon={<Icons.FileText/>}/>
        <KPI T={T} label="Regras Safety" value="14" sub="2 críticas · 5 média" icon={<Icons.Shield/>}/>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card T={T} title="Domínios cobertos" subtitle="8 domínios LPR · ordem de prioridade" padding={0}>
          {LPR_DOMAINS.map((d, i) => {
            const Di = Icons[d.icon];
            return (
              <div key={d.id} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px',
                borderBottom: i < LPR_DOMAINS.length - 1 ? `1px solid ${T.border}` : 0,
              }}>
                <span style={{ fontFamily: T.fontMono, fontSize: 11, color: T.textMute, width: 18 }}>{i + 1}</span>
                <Di size={14} color={T.p600}/>
                <span style={{ flex: 1, fontSize: 13, fontWeight: 500, color: T.text }}>{d.label}</span>
                <span style={{ fontSize: 11, color: T.textMute }}>{[14,12,8,9,15,10,11,7][i]} marcadores</span>
              </div>
            );
          })}
        </Card>

        <Card T={T} title="Exames" subtitle="Por categoria · obrigatório / desejável / plus" padding={0}>
          {[
            { cat: 'Obrigatórios', count: 8, list: 'Glicemia, Insulina, HbA1c, hsCRP, TSH, Vit D, B12, Ferritina', tone: 'error' },
            { cat: 'Desejáveis', count: 14, list: 'Lipidograma, Cortisol, T3, Hb glicada, GGT, ácido úrico…', tone: 'warning' },
            { cat: 'Plus', count: 22, list: 'CGM 14d, DEXA, calprotectina, microbioma, peptídeo C…', tone: 'info' },
          ].map((g, i) => (
            <div key={i} style={{ padding: '12px 16px', borderBottom: i < 2 ? `1px solid ${T.border}` : 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Pill T={T} tone={g.tone}>{g.cat}</Pill>
                <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{g.count} exames</span>
                <Button T={T} kind="ghost" size="sm" iconRight={<Icons.ChevronR/>} style={{ marginLeft: 'auto' }}>Editar</Button>
              </div>
              <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 4 }}>{g.list}</div>
            </div>
          ))}
        </Card>

        <Card T={T} title="Questionários & frequências" padding={0}>
          {QUESTIONNAIRES.map((q, i, arr) => (
            <div key={q.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0 }}>
              <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500, color: T.text }}>{q.name}</span>
              <Pill T={T} tone="neutral">{q.freq}</Pill>
              <span style={{ fontSize: 11, color: T.textMute, width: 80 }}>{q.domains.length} domínios</span>
            </div>
          ))}
        </Card>

        <Card T={T} title="Regras de score & alerta" subtitle="Como o sistema agrega e dispara" padding={0}>
          {[
            { name: 'Score por domínio', formula: 'Σ(driver_i × peso_i) · normalizado 0–100', edit: true },
            { name: 'Score global', formula: 'média ponderada · drivers críticos pesam 1.5×', edit: true },
            { name: 'Alerta de tendência', formula: 'IF Δ7d < -8 OU Δ30d < -15 → alerta', edit: true },
            { name: 'Padrão emergente', formula: 'cruzamento ≥3 domínios em piora simultânea', edit: true },
            { name: 'Dados faltantes', formula: 'IF cobertura_dominio < 60% → flag amarela', edit: true },
          ].map((r, i, arr) => (
            <div key={i} style={{ padding: '11px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${T.border}` : 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12.5, fontWeight: 600, color: T.text, flex: 1 }}>{r.name}</span>
                <Button T={T} kind="ghost" size="sm" icon={<Icons.Edit/>}>Editar</Button>
              </div>
              <div style={{ fontSize: 11.5, color: T.textMute, fontFamily: T.fontMono, marginTop: 3 }}>{r.formula}</div>
            </div>
          ))}
        </Card>
      </div>

      <Card T={T} title="Playbooks por fase" subtitle="Ordem de intervenções recomendada" padding={0}>
        <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {[
            { phase: 'Fase 1', title: 'Reset Circadiano', items: ['Janela sono 23:00–06:30', 'Exposição solar 10min', 'Janela alimentar 11:00–20:00'], tone: T.p600, dur: '14d' },
            { phase: 'Fase 2', title: 'Adesão & Comportamento', items: ['Rotina mínima viável', 'Micro-hábitos diários', 'Triggers + recompensa'], tone: T.warning, dur: '14d' },
            { phase: 'Fase 3', title: 'Intestino', items: ['Manejo de constipação', 'Ajuste alimentar fibra', 'Hidratação 30 ml/kg'], tone: T.info, dur: '14d' },
            { phase: 'Fase 4', title: 'Metabólico', items: ['Avaliação CGM 14d', 'Treino de força 3x/sem', 'Considerar GLP-1 (com Safety OK)'], tone: T.success, dur: 'open' },
          ].map((ph, i) => (
            <div key={i} style={{ padding: 14, border: `1px solid ${T.border}`, borderRadius: 10, background: T.bg, position: 'relative' }}>
              <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: ph.tone, borderRadius: '10px 10px 0 0' }}/>
              <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 600, letterSpacing: 0.2, textTransform: 'uppercase' }}>{ph.phase} · {ph.dur}</div>
              <div style={{ fontSize: 14, fontWeight: 700, color: T.text, marginTop: 4, marginBottom: 8, letterSpacing: -0.2 }}>{ph.title}</div>
              {ph.items.map((it, j) => (
                <div key={j} style={{ display: 'flex', gap: 6, fontSize: 12, color: T.textSoft, padding: '3px 0' }}>
                  <Icons.Check size={12} color={ph.tone} style={{ marginTop: 2, flexShrink: 0 }}/> {it}
                </div>
              ))}
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

// 15. Rules builder (Safety Engine config)
function RulesBuilderScreen({ T }) {
  const [active, setActive] = React.useState('R-014');
  const [conditions, setConditions] = React.useState([
    { id: 1, op: '', field: 'adesao_semanal', cmp: '<', value: '60', unit: '%' },
    { id: 2, op: 'AND', field: 'comportamental', cmp: '==', value: 'red', unit: '' },
  ]);
  const r = SAFETY_RULES.find((x) => x.id === active);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 16 }}>
      <Card T={T} padding={0}
        title="Regras do Safety Engine"
        subtitle={`${SAFETY_RULES.length} regras · ${SAFETY_RULES.filter((x) => x.enabled).length} ativas`}
        action={<Button T={T} kind="primary" size="sm" icon={<Icons.Plus/>}>Nova</Button>}>
        <div style={{ padding: '6px 12px 12px' }}>
          <Input T={T} icon={<Icons.Search/>} placeholder="Buscar regra…" full/>
        </div>
        <div style={{ borderTop: `1px solid ${T.border}`, maxHeight: 720, overflow: 'auto' }} className="lpr-scroll">
          {SAFETY_RULES.map((rule, i) => {
            const sev = rule.sev === 'high' ? 'error' : rule.sev === 'medium' ? 'warning' : 'info';
            const on = active === rule.id;
            return (
              <button key={rule.id} onClick={() => setActive(rule.id)} className="lpr-btn"
                style={{
                  display: 'block', width: '100%', padding: '11px 14px', border: 0,
                  borderBottom: i < SAFETY_RULES.length - 1 ? `1px solid ${T.border}` : 0,
                  background: on ? T.p50 : 'transparent', cursor: 'pointer', textAlign: 'left',
                  borderLeft: `3px solid ${on ? T.p600 : 'transparent'}`,
                  opacity: rule.enabled ? 1 : 0.6,
                }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: T.fontMono, fontSize: 11, fontWeight: 700, color: T.textMute }}>{rule.id}</span>
                  <Pill T={T} tone={sev}>{rule.sev === 'high' ? 'Alta' : rule.sev === 'medium' ? 'Média' : 'Baixa'}</Pill>
                  {!rule.enabled ? <Pill T={T} tone="neutral">Inativa</Pill> : null}
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: on ? T.p700 : T.text, marginTop: 4, lineHeight: 1.3 }}>{rule.name}</div>
              </button>
            );
          })}
        </div>
      </Card>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Card T={T} padding={20}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontFamily: T.fontMono, fontSize: 12, fontWeight: 700, color: T.textMute }}>{r.id}</span>
                <Pill T={T} tone={r.sev === 'high' ? 'error' : r.sev === 'medium' ? 'warning' : 'info'}>{r.sev === 'high' ? 'Severidade alta' : r.sev === 'medium' ? 'Média' : 'Baixa'}</Pill>
                {r.requireReview ? <Pill T={T} tone="info" icon={<Icons.Stethoscope size={10}/>}>Revisão obrigatória</Pill> : null}
                {!r.allowOverride ? <Pill T={T} tone="error" icon={<Icons.Lock size={10}/>}>Sem override</Pill> : null}
              </div>
              <div style={{ fontFamily: T.fontDisplay, fontSize: 18, fontWeight: 600, color: T.text, marginTop: 6, letterSpacing: -0.2 }}>{r.name}</div>
              <div style={{ fontSize: 12, color: T.textMute, marginTop: 2 }}>Disparada 47 vezes nos últimos 30 dias · 3 overrides registrados</div>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: T.textSoft }}>
                <input type="checkbox" defaultChecked={r.enabled} style={{ accentColor: T.p600, width: 14, height: 14 }}/>
                Regra ativa
              </label>
              <Button T={T} kind="secondary" size="sm" icon={<Icons.Database/>}>Testar com coorte</Button>
              <Button T={T} kind="primary" size="sm" icon={<Icons.Check/>}>Salvar</Button>
            </div>
          </div>
        </Card>

        <Card T={T} title="Construtor visual" subtitle="IF condições THEN decisão">
          <div style={{
            padding: 16, borderRadius: 8, background: T.surface, border: `1px solid ${T.border}`,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <Pill T={T} tone="primary">IF</Pill>
              <span style={{ fontSize: 12, color: T.textMute }}>todas as condições abaixo precisam ser verdadeiras</span>
            </div>
            {conditions.map((c, i) => (
              <div key={c.id} style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8 }}>
                {i > 0 ? (
                  <select value={c.op} style={selectStyle(T)}>
                    <option>AND</option><option>OR</option>
                  </select>
                ) : <span style={{ width: 64 }}/>}
                <select value={c.field} style={selectStyle(T, 220)}>
                  <option>adesao_semanal</option>
                  <option>comportamental</option>
                  <option>cortisol_am</option>
                  <option>psqi</option>
                  <option>hsCRP</option>
                  <option>delta_massa_magra</option>
                </select>
                <select value={c.cmp} style={selectStyle(T, 70)}>
                  <option>{'<'}</option><option>{'≤'}</option><option>{'=='}</option><option>{'≥'}</option><option>{'>'}</option><option>{'!='}</option>
                </select>
                <input value={c.value} style={inputStyle(T, 80)} readOnly/>
                {c.unit ? <span style={{ fontSize: 12, color: T.textMute }}>{c.unit}</span> : null}
                <button className="lpr-btn" style={{ width: 28, height: 28, border: `1px solid ${T.border}`, background: T.bg, borderRadius: 6, cursor: 'pointer' }}>
                  <Icons.X size={12} color={T.textMute}/>
                </button>
              </div>
            ))}
            <Button T={T} kind="ghost" size="sm" icon={<Icons.Plus/>}>Adicionar condição</Button>

            <div style={{ height: 14 }}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <Pill T={T} tone="error">THEN</Pill>
              <span style={{ fontSize: 12, color: T.textMute }}>aplicar decisão e mensagens</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
              <div>
                <Label T={T}>Decisão</Label>
                <select style={selectStyle(T, '100%')}>
                  <option>Block</option><option>Allow</option><option>Caution</option><option>Modify</option><option>Postpone</option><option>Require Medical Review</option>
                </select>
              </div>
              <div>
                <Label T={T}>Intervenção afetada</Label>
                <select style={selectStyle(T, '100%')}>
                  <option>GLP-1 (semaglutida)</option><option>Jejum intermitente</option><option>Treino intenso</option><option>Dieta restritiva</option><option>Suplementação ferro</option>
                </select>
              </div>
              <div>
                <Label T={T}>Severidade</Label>
                <select style={selectStyle(T, '100%')} defaultValue="Alta">
                  <option>Alta</option><option>Média</option><option>Baixa</option>
                </select>
              </div>
            </div>
            <div style={{ height: 12 }}/>
            <Label T={T}>Domínios afetados</Label>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
              {LPR_DOMAINS.map((d) => {
                const on = r.affectedDomains.includes(d.id);
                return (
                  <button key={d.id} className="lpr-btn" style={{
                    padding: '5px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: 500, cursor: 'pointer',
                    border: `1px solid ${on ? T.p600 : T.border}`, background: on ? T.p50 : T.bg, color: on ? T.p700 : T.textSoft,
                  }}>{d.label}</button>
                );
              })}
            </div>

            <div style={{ height: 14 }}/>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <Label T={T}>Mensagem para o médico</Label>
                <textarea defaultValue="Adesão semanal abaixo de 60% combinada com escore comportamental crítico. Recomenda-se estabilizar comportamento por ≥4 semanas antes de reavaliar."
                  style={{ ...inputStyle(T, '100%'), minHeight: 64, padding: 8, resize: 'vertical' }}/>
              </div>
              <div>
                <Label T={T}>Mensagem para o paciente</Label>
                <textarea defaultValue="Antes de avançar para medicamento, vamos estabilizar seu sono e rotina. Isso aumenta sua chance de sucesso."
                  style={{ ...inputStyle(T, '100%'), minHeight: 64, padding: 8, resize: 'vertical' }}/>
              </div>
            </div>

            <div style={{ height: 14 }}/>
            <div style={{ display: 'flex', gap: 18 }}>
              <label style={{ fontSize: 12, color: T.text, display: 'flex', alignItems: 'center', gap: 6 }}>
                <input type="checkbox" defaultChecked={r.requireReview} style={{ accentColor: T.p600, width: 14, height: 14 }}/>
                Exigir revisão médica
              </label>
              <label style={{ fontSize: 12, color: T.text, display: 'flex', alignItems: 'center', gap: 6 }}>
                <input type="checkbox" defaultChecked={r.allowOverride} style={{ accentColor: T.p600, width: 14, height: 14 }}/>
                Permitir override
              </label>
              <label style={{ fontSize: 12, color: T.text, display: 'flex', alignItems: 'center', gap: 6 }}>
                <input type="checkbox" style={{ accentColor: T.p600, width: 14, height: 14 }}/>
                Notificar comitê clínico
              </label>
            </div>
          </div>

          <div style={{ marginTop: 14, padding: 12, background: T.surfaceAlt, borderRadius: 8, fontFamily: T.fontMono, fontSize: 11.5, color: T.textSoft, lineHeight: 1.6 }}>
            <span style={{ color: T.info }}>IF</span> adesao_semanal {'<'} 60% <span style={{ color: T.info }}>AND</span> comportamental == red<br/>
            <span style={{ color: T.error }}>THEN</span> Block GLP-1 (severidade: alta)<br/>
            <span style={{ color: T.warning }}>REQUIRE</span> medical_review = true
          </div>
        </Card>
      </div>
    </div>
  );
}

function Label({ T, children }) {
  return <div style={{ fontSize: 11, color: T.textMute, fontWeight: 600, letterSpacing: 0.2, textTransform: 'uppercase', marginBottom: 4 }}>{children}</div>;
}
function selectStyle(T, w) {
  return {
    padding: '6px 8px', fontSize: 12.5, fontFamily: T.fontUI, color: T.text,
    borderRadius: 6, border: `1px solid ${T.borderStrong}`, background: T.bg,
    width: w || 100, outline: 'none',
  };
}
function inputStyle(T, w) {
  return {
    padding: '6px 10px', fontSize: 12.5, fontFamily: T.fontUI, color: T.text,
    borderRadius: 6, border: `1px solid ${T.borderStrong}`, background: T.bg,
    width: w || 100, outline: 'none', boxSizing: 'border-box',
  };
}

// ─────────────────────────────────────────────────────────────
// 8. Patient mobile — LPR Daily
// ─────────────────────────────────────────────────────────────
function LPRDailyScreen({ T }) {
  const [answers, setAnswers] = React.useState(() => {
    const o = {}; DAILY_QUESTIONS.forEach((q) => o[q.id] = q.value); return o;
  });
  const [submitted, setSubmitted] = React.useState(false);
  const set = (id, v) => setAnswers((a) => ({ ...a, [id]: v }));
  const answeredCount = DAILY_QUESTIONS.filter((q) => answers[q.id] != null && answers[q.id] !== '').length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: T.surface }}>
      {/* Top bar */}
      <div style={{ padding: '12px 16px 8px', borderBottom: `1px solid ${T.border}`, background: T.bg, position: 'sticky', top: 0, zIndex: 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <button style={{ background: 'transparent', border: 0, padding: 4, cursor: 'pointer' }}>
            <Icons.X size={18} color={T.textMute}/>
          </button>
          <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>LPR Daily</span>
          <span style={{ fontSize: 11.5, color: T.textMute, fontVariantNumeric: 'tabular-nums' }}>{answeredCount}/{DAILY_QUESTIONS.length}</span>
        </div>
        <div style={{ marginTop: 8 }}>
          <Meter T={T} value={(answeredCount / DAILY_QUESTIONS.length) * 100} color={T.p600} height={4}/>
        </div>
      </div>

      <div className="lpr-scroll" style={{ flex: 1, overflow: 'auto', padding: '12px 16px 100px' }}>
        <div style={{ padding: '6px 0 14px' }}>
          <div style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.4 }}>Bom dia, Mariana</div>
          <div style={{ fontSize: 13, color: T.textMute, marginTop: 4 }}>Leva 30–60 segundos. Suas respostas afetam o protocolo de hoje.</div>
        </div>

        {DAILY_QUESTIONS.map((q) => (
          <div key={q.id} style={{ background: T.bg, border: `1px solid ${T.border}`, borderRadius: 12, padding: 14, marginBottom: 10 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: T.text, marginBottom: q.hint ? 2 : 10 }}>{q.label}</div>
            {q.hint ? <div style={{ fontSize: 11.5, color: T.textMute, marginBottom: 10 }}>{q.hint}</div> : null}

            {q.type === 'scale' ? <ScaleControl T={T} value={answers[q.id]} onChange={(v) => set(q.id, v)} min={q.min} max={q.max} inverse={q.inverse}/> : null}
            {q.type === 'yesno' ? <YesNo T={T} value={answers[q.id]} onChange={(v) => set(q.id, v)}/> : null}
            {q.type === 'percent' ? <Percent T={T} value={answers[q.id]} onChange={(v) => set(q.id, v)}/> : null}
            {q.type === 'bristol' ? <Bristol T={T} value={answers[q.id]} onChange={(v) => set(q.id, v)}/> : null}
            {q.type === 'text' ? (
              <textarea value={answers[q.id]} onChange={(e) => set(q.id, e.target.value)}
                placeholder="Algo a destacar para sua médica? (opcional)"
                style={{
                  width: '100%', minHeight: 70, padding: 10, fontSize: 13, fontFamily: T.fontUI,
                  borderRadius: 8, border: `1px solid ${T.borderStrong}`, background: T.bg, color: T.text,
                  resize: 'vertical', outline: 'none', boxSizing: 'border-box',
                }}/>
            ) : null}
          </div>
        ))}

        <div style={{ marginTop: 12, padding: 14, background: T.p50, borderRadius: 12, border: `1px solid ${T.p100}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Icons.Shield size={14} color={T.p700}/>
            <span style={{ fontSize: 11.5, fontWeight: 600, color: T.p700, letterSpacing: 0.2, textTransform: 'uppercase' }}>Privacidade</span>
          </div>
          <div style={{ fontSize: 11.5, color: T.textSoft, lineHeight: 1.5 }}>
            Suas respostas são compartilhadas apenas com sua médica e a equipe clínica autorizada. Dados protegidos por LGPD.
          </div>
        </div>
      </div>

      {/* Sticky submit */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: 14, background: T.bg, borderTop: `1px solid ${T.border}` }}>
        <Button T={T} kind="primary" size="lg" full icon={<Icons.Check/>} onClick={() => setSubmitted(true)}>
          {submitted ? 'Enviado · obrigada!' : 'Enviar LPR Daily'}
        </Button>
      </div>
    </div>
  );
}

function ScaleControl({ T, value, onChange, min = 0, max = 10, inverse }) {
  return (
    <div>
      <div style={{ display: 'flex', gap: 4 }}>
        {Array.from({ length: max - min + 1 }, (_, i) => i + min).map((v) => {
          const on = value === v;
          // gradient: low = green, high = orange/red, with inverse flag
          const norm = (v - min) / (max - min);
          const stop = inverse ? norm : 1 - norm;
          const c = stop > 0.66 ? T.error : stop > 0.33 ? T.warning : T.success;
          return (
            <button key={v} onClick={() => onChange(v)} className="lpr-btn"
              style={{
                flex: 1, height: 38, borderRadius: 8, cursor: 'pointer', fontWeight: 600,
                fontSize: 13, fontVariantNumeric: 'tabular-nums',
                border: `1.5px solid ${on ? c : T.border}`,
                background: on ? c : T.bg, color: on ? '#fff' : T.text,
                boxShadow: on ? `0 0 0 3px ${c}33` : 'none',
              }}>{v}</button>
          );
        })}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: T.textMute, marginTop: 4 }}>
        <span>{inverse ? 'Pouco' : 'Mal'}</span>
        <span>{inverse ? 'Muito' : 'Ótimo'}</span>
      </div>
    </div>
  );
}
function YesNo({ T, value, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      {[{ v: true, label: 'Sim', c: T.success }, { v: false, label: 'Não', c: T.error }].map((o) => {
        const on = value === o.v;
        return (
          <button key={String(o.v)} onClick={() => onChange(o.v)} className="lpr-btn" style={{
            flex: 1, padding: '12px 0', borderRadius: 10, fontSize: 14, fontWeight: 600,
            border: `1.5px solid ${on ? o.c : T.border}`, background: on ? o.c : T.bg, color: on ? '#fff' : T.text,
            cursor: 'pointer', boxShadow: on ? `0 0 0 3px ${o.c}33` : 'none',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}
function Percent({ T, value, onChange }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <input type="range" min="0" max="100" step="5" value={value || 0} onChange={(e) => onChange(+e.target.value)}
          style={{ flex: 1, accentColor: T.p600, height: 6 }}/>
        <span style={{ fontFamily: T.fontMono, fontSize: 16, fontWeight: 700, color: T.text, fontVariantNumeric: 'tabular-nums', minWidth: 50, textAlign: 'right' }}>{value || 0}%</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: T.textMute, marginTop: 4 }}>
        <span>Não segui</span><span>Segui 100%</span>
      </div>
    </div>
  );
}
function Bristol({ T, value, onChange }) {
  const types = [
    { n: 1, desc: 'Caroços duros' },
    { n: 2, desc: 'Forma de salsicha c/ rachaduras' },
    { n: 3, desc: 'Salsicha lisa' },
    { n: 4, desc: 'Salsicha mole' },
    { n: 5, desc: 'Pedaços moles' },
    { n: 6, desc: 'Pastoso' },
    { n: 7, desc: 'Líquido' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
      {types.map((t) => {
        const on = value === t.n;
        const ideal = t.n === 3 || t.n === 4;
        const c = ideal ? T.success : (t.n === 2 || t.n === 5) ? T.warning : T.error;
        return (
          <button key={t.n} onClick={() => onChange(t.n)} className="lpr-btn" title={t.desc} style={{
            padding: '10px 0', borderRadius: 8, fontSize: 13, fontWeight: 700, cursor: 'pointer',
            border: `1.5px solid ${on ? c : T.border}`, background: on ? c : T.bg, color: on ? '#fff' : T.text,
            fontFamily: T.fontMono,
          }}>{t.n}</button>
        );
      })}
    </div>
  );
}

// 9. Patient home (mobile)
function PatientHomeScreen({ T, onOpenDaily }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: T.surface }}>
      <div style={{ padding: '14px 16px 10px', background: T.bg }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <LPRMark T={T} size={15}/>
          <button style={{ width: 32, height: 32, borderRadius: 8, border: `1px solid ${T.border}`, background: T.bg, position: 'relative', cursor: 'pointer' }}>
            <Icons.Bell size={14} color={T.textSoft}/>
            <span style={{ position: 'absolute', top: 6, right: 6, width: 6, height: 6, borderRadius: '50%', background: T.error }}/>
          </button>
        </div>
        <div style={{ marginTop: 12 }}>
          <div style={{ fontSize: 11.5, color: T.textMute }}>Sexta · 03 maio</div>
          <div style={{ fontFamily: T.fontDisplay, fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.4 }}>Olá, Mariana 👋</div>
          <div style={{ fontSize: 13, color: T.textSoft, marginTop: 4, lineHeight: 1.4 }}>
            Você está na <strong style={{ color: T.text }}>Fase 1 — Reset Circadiano</strong>. Hoje é sobre regular o sono.
          </div>
        </div>
      </div>

      <div className="lpr-scroll" style={{ flex: 1, overflow: 'auto', padding: '12px 16px 24px' }}>
        {/* LPR Daily card */}
        <div style={{
          padding: 14, borderRadius: 14, background: `linear-gradient(135deg, ${T.p700} 0%, ${T.p900} 100%)`, color: '#fff',
          display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12, cursor: 'pointer',
        }} onClick={onOpenDaily}>
          <span style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(255,255,255,0.18)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icons.Edit size={20} color="#fff"/>
          </span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.7)', fontWeight: 500, letterSpacing: 0.2, textTransform: 'uppercase' }}>LPR Daily · pendente</div>
            <div style={{ fontSize: 14.5, fontWeight: 600, marginTop: 2 }}>Como foi seu dia até agora?</div>
            <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>Leva ~45 segundos · 12 perguntas</div>
          </div>
          <Icons.ChevronR size={18} color="rgba(255,255,255,0.7)"/>
        </div>

        {/* Score simplified */}
        <div style={{ background: T.bg, border: `1px solid ${T.border}`, borderRadius: 14, padding: 14, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: T.textMute, letterSpacing: 0.2, textTransform: 'uppercase' }}>Seu progresso</span>
            <span style={{ fontSize: 11.5, color: T.success, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
              <Icons.TrendUp size={11}/> +4 esta semana
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
            <span style={{ fontFamily: T.fontDisplay, fontSize: 40, fontWeight: 700, color: T.text, letterSpacing: -1, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>58</span>
            <span style={{ fontSize: 13, color: T.textMute }}>de 100 · meta 70</span>
          </div>
          <Meter T={T} value={58} max={100} color={T.warning} height={6}/>
          <div style={{ display: 'flex', gap: 6, marginTop: 12, justifyContent: 'space-between' }}>
            {LPR_DOMAINS.map((d) => {
              const dom = MARIANA.domains[d.id];
              const c = STATUS_COLOR(T)[dom.semaphore];
              const Di = Icons[d.icon];
              return (
                <div key={d.id} style={{ flex: 1, textAlign: 'center' }}>
                  <span style={{ display: 'inline-flex', width: 30, height: 30, borderRadius: 8, background: c.bg, alignItems: 'center', justifyContent: 'center' }}>
                    <Di size={13} color={c.fg}/>
                  </span>
                  <div style={{ fontSize: 9, color: T.textMute, marginTop: 3 }}>{d.short}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Today's tasks */}
        <div style={{ background: T.bg, border: `1px solid ${T.border}`, borderRadius: 14, padding: 14, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>Tarefas de hoje</span>
            <span style={{ fontSize: 11, color: T.textMute }}>2/5 concluídas</span>
          </div>
          {[
            { label: 'Sair na luz natural por 10 min', time: 'até 9h', done: true, icon: Icons.Sun },
            { label: 'Última refeição até 20:00', time: 'até 20:00', done: true, icon: Icons.Apple },
            { label: 'Sem café após 14h', time: 'até 14:00', done: false, icon: Icons.Drop },
            { label: 'PSS-10 (questionário 5 min)', time: '14d em atraso', done: false, icon: Icons.FileText, alert: true },
            { label: 'Dormir antes de 23:30', time: 'esta noite', done: false, icon: Icons.Moon2 },
          ].map((t, i) => {
            const Ti = t.icon;
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: i > 0 ? `1px solid ${T.border}` : 0 }}>
                <span style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: t.done ? T.successBg : T.surfaceAlt, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {t.done ? <Icons.Check size={12} color={T.success}/> : <Ti size={12} color={t.alert ? T.warning : T.textMute}/>}
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, color: t.done ? T.textMute : T.text, fontWeight: 500, textDecoration: t.done ? 'line-through' : 'none' }}>{t.label}</div>
                  <div style={{ fontSize: 11, color: t.alert ? T.warning : T.textMute }}>{t.time}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Doctor message */}
        <div style={{ background: T.bg, border: `1px solid ${T.border}`, borderRadius: 14, padding: 14, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <Avatar name="Helena Marques" T={T} size={32}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: T.text }}>Dr. Helena Marques</div>
              <div style={{ fontSize: 10.5, color: T.textMute }}>Há 1h · Orientação clínica</div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: T.textSoft, lineHeight: 1.5 }}>
            Mariana, antes de pensarmos em remédio para emagrecer, vamos focar em estabilizar seu sono nas próximas 2 semanas. Confio em você 💪
          </div>
        </div>

        {/* Last 7 days mini chart */}
        <div style={{ background: T.bg, border: `1px solid ${T.border}`, borderRadius: 14, padding: 14, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: T.text }}>Últimos 7 dias</span>
            <span style={{ fontSize: 11, color: T.textMute }}>Sono · Energia · Humor</span>
          </div>
          <Sparkline T={T} values={[5,4,5,6,5,6,7]} color={T.info} fill={T.infoBg} width={310} height={42} strokeWidth={2}/>
        </div>

        {/* Patient alerts */}
        <div style={{ background: T.warningBg, border: `1px solid ${T.warningBorder}`, borderRadius: 14, padding: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Icons.AlertCir size={14} color={T.warning}/>
            <span style={{ fontSize: 12, fontWeight: 700, color: T.warning, letterSpacing: 0.2, textTransform: 'uppercase' }}>Atenção · Sono</span>
          </div>
          <div style={{ fontSize: 12.5, color: T.textSoft, lineHeight: 1.5 }}>
            Você dormiu menos de 6h em 4 dos últimos 7 dias. Tente dormir antes de 23:30 hoje.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SafetyEngineScreen, ProtocolConfigScreen, RulesBuilderScreen, LPRDailyScreen, PatientHomeScreen });
