// Mais — Profile + secondary screens (Prevenção, Hemograma)

window.MaisScreen = function MaisScreen({ T, onNavigate, gestante, setGestante }) {
  return (
    <div style={{ padding: '0 20px 120px', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ paddingTop: 14 }}>
        <SectionLabel>Perfil & ferramentas</SectionLabel>
        <h1 style={{
          fontFamily: 'Georgia, serif', fontSize: 30, lineHeight: 1.05,
          margin: '8px 0 0', color: T.ink, fontWeight: 500, letterSpacing: -0.5,
        }}>Mais.</h1>
      </div>

      {/* Profile / mode card */}
      <div style={{
        background: gestante ? T.forest : '#fff',
        color: gestante ? '#fff' : T.ink,
        borderRadius: 22, padding: 16,
        border: gestante ? 'none' : `1px solid ${T.hair}`,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{
          width: 52, height: 52, borderRadius: 99,
          background: gestante ? 'rgba(255,255,255,0.16)' : T.paperWarm,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name={gestante ? 'pregnant' : 'user'} size={26} color={gestante ? T.acid : T.forest} stroke={1.6}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, opacity: 0.6, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'ui-monospace, monospace' }}>
            Perfil atual
          </div>
          <div style={{ fontFamily: 'Georgia, serif', fontSize: 20, fontWeight: 500, letterSpacing: -0.2 }}>
            {gestante ? 'Modo Gestante' : 'Perfil Geral'}
          </div>
        </div>
        <Toggle on={gestante} onChange={setGestante} activeColor={T.acid} trackOff="rgba(22,32,31,0.12)"/>
      </div>

      {/* Tools row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <ToolCard T={T} onClick={() => onNavigate('hemograma')}
          icon="flask" color={T.water} label="Hemograma" detail="Lab analyzer"/>
        <ToolCard T={T} onClick={() => onNavigate('prevencao')}
          icon="leaf" color={T.moss} label="Prevenção" detail="Checklist 8/13"/>
      </div>

      {/* List sections */}
      <ListGroup T={T} label="Triagem">
        <ListRow T={T} icon="scan" color={T.forest} title="Nova triagem" detail="6 etapas"
          onClick={() => onNavigate('triagem')}/>
        <ListRow T={T} icon="print" color={T.ink} title="Relatório para o médico" detail="Imprimir"
          onClick={() => alert('Abriria a visualização de impressão.')}/>
        <ListRow T={T} icon="clock" color={T.lavender} title="Histórico de análises" detail="3 salvas" last/>
      </ListGroup>

      <ListGroup T={T} label="Educação">
        {gestante && (
          <ListRow T={T} icon="pregnant" color={T.acid} title="Guia Interativo Gestante" detail="Cozinha, exames e alertas"
            onClick={() => onNavigate('gestante')}/>
        )}
        <ListRow T={T} icon="book" color={T.water} title="Catálogo completo" detail="22 fichas"
          onClick={() => onNavigate('biblioteca')}/>
        <ListRow T={T} icon="shield" color={T.moss} title="Protocolos por idade" detail="Pediatria, adultos"
          onClick={() => {}}/>
        <ListRow T={T} icon="heart" color={T.rose} title="Sinais de urgência" detail="Quando procurar pronto‑socorro" last
          onClick={() => {}}/>
      </ListGroup>

      <ListGroup T={T} label="Sistema">
        <ListRow T={T} icon="info" color={T.inkSoft} title="Sobre o motor Bayesiano" detail="Como pensamos"
          onClick={() => {}}/>
        <ListRow T={T} icon="download" color={T.forest} title="Funciona offline" detail="100% local" last
          onClick={() => {}}/>
      </ListGroup>

      <div style={{
        padding: '10px 16px', fontSize: 11, color: T.inkMuted, textAlign: 'center',
        lineHeight: 1.5, fontFamily: 'ui-monospace, monospace', letterSpacing: 0.3,
      }}>
        Parasitas em Foco v2.0 · Privacidade total · Edge Computing
      </div>
    </div>
  );
};

function ToolCard({ T, icon, color, label, detail, onClick }) {
  return (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer',
      background: '#fff', borderRadius: 20, padding: 14,
      border: `1px solid ${T.hair}`,
      display: 'flex', flexDirection: 'column', gap: 10, minHeight: 120,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, background: `${color}14`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={20} color={color} stroke={1.7}/>
      </div>
      <div style={{ marginTop: 'auto' }}>
        <div style={{ fontFamily: 'Georgia, serif', fontSize: 17, color: T.ink, fontWeight: 500, letterSpacing: -0.2 }}>
          {label}
        </div>
        <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 2 }}>{detail}</div>
      </div>
    </button>
  );
}

function ListGroup({ T, label, children }) {
  return (
    <div>
      <SectionLabel style={{ padding: '0 16px 8px' }}>{label}</SectionLabel>
      <div style={{
        background: '#fff', borderRadius: 20, overflow: 'hidden',
        border: `1px solid ${T.hair}`,
      }}>{children}</div>
    </div>
  );
}

function ListRow({ T, icon, color, title, detail, last, onClick }) {
  return (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer', width: '100%', boxSizing: 'border-box',
      display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
      borderBottom: last ? 'none' : `1px solid ${T.hair}`,
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 8, background: `${color}14`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <Icon name={icon} size={17} color={color} stroke={1.7}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14.5, color: T.ink, fontWeight: 500 }}>{title}</div>
        <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 1 }}>{detail}</div>
      </div>
      <Icon name="chevron" size={14} color={T.inkMuted}/>
    </button>
  );
}

function Toggle({ on, onChange, activeColor, trackOff }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      all: 'unset', cursor: 'pointer',
      width: 50, height: 30, borderRadius: 99, position: 'relative',
      background: on ? activeColor : trackOff, transition: 'all 0.2s',
    }}>
      <div style={{
        position: 'absolute', top: 3, left: on ? 23 : 3,
        width: 24, height: 24, borderRadius: 99,
        background: '#fff', transition: 'left 0.2s',
        boxShadow: '0 2px 4px rgba(0,0,0,0.15)',
      }}/>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Prevenção screen
window.PrevencaoScreen = function PrevencaoScreen({ T, onNavigate }) {
  const [checked, setChecked] = React.useState({
    h1: true, h2: true, h3: true, h4: false, h5: true, h6: false,
    h7: true, h8: true, h9: true, h10: false, h11: false, h12: true, h13: true,
  });
  const items = [
    { id: 'h1', group: 'Higiene', text: 'Lavar as mãos antes das refeições' },
    { id: 'h2', group: 'Higiene', text: 'Lavar as mãos após o banheiro' },
    { id: 'h3', group: 'Higiene', text: 'Manter unhas curtas e limpas' },
    { id: 'h4', group: 'Higiene', text: 'Lavar verduras com hipoclorito' },
    { id: 'h5', group: 'Água & alimentos', text: 'Beber apenas água filtrada/fervida' },
    { id: 'h6', group: 'Água & alimentos', text: 'Cozinhar carnes acima de 70°C' },
    { id: 'h7', group: 'Água & alimentos', text: 'Higienizar frutas com casca' },
    { id: 'h8', group: 'Ambiente', text: 'Calçados ao sair de casa' },
    { id: 'h9', group: 'Ambiente', text: 'Caixa d\'água limpa a cada 6 meses' },
    { id: 'h10', group: 'Ambiente', text: 'Sanitização de áreas de animais' },
    { id: 'h11', group: 'Comunidade', text: 'Saneamento básico funcionando' },
    { id: 'h12', group: 'Comunidade', text: 'Vermifugação periódica de pets' },
    { id: 'h13', group: 'Comunidade', text: 'Triagem anual da família' },
  ];
  const count = Object.values(checked).filter(Boolean).length;
  const grouped = {};
  items.forEach(it => { (grouped[it.group] ||= []).push(it); });
  const groups = Object.keys(grouped);

  return (
    <div style={{ padding: '0 20px 120px', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ paddingTop: 14 }}>
        <button onClick={() => onNavigate('home')} style={{
          all: 'unset', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 13, color: T.inkSoft, marginBottom: 12,
        }}>
          <Icon name="chevron" size={14} stroke={2} color={T.inkSoft}/> Início
        </button>
        <SectionLabel>Hábitos protetores</SectionLabel>
        <h1 style={{
          fontFamily: 'Georgia, serif', fontSize: 30, lineHeight: 1.05,
          margin: '6px 0 0', color: T.ink, fontWeight: 500, letterSpacing: -0.5,
        }}>Prevenção.</h1>
      </div>

      {/* Progress */}
      <div style={{ background: T.moss, color: '#fff', padding: 18, borderRadius: 22, position: 'relative', overflow: 'hidden' }}>
        <div style={{
          position: 'absolute', top: -50, right: -50, width: 180, height: 180, borderRadius: '50%',
          background: `radial-gradient(circle, ${T.acid}40 0%, transparent 70%)`,
        }}/>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 52, fontWeight: 500, lineHeight: 1, color: T.acid }}>
            {count}
          </div>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, opacity: 0.65 }}>/ {items.length}</div>
        </div>
        <div style={{ position: 'relative', marginTop: 10, fontSize: 13, color: 'rgba(255,255,255,0.85)', maxWidth: 240, lineHeight: 1.4 }}>
          hábitos marcados como ativos na sua rotina.
        </div>
        <div style={{ position: 'relative', marginTop: 14 }}>
          <ProbBar value={count / items.length} color={T.acid} height={6} bg="rgba(255,255,255,0.15)"/>
        </div>
      </div>

      {groups.map(g => (
        <div key={g}>
          <SectionLabel style={{ padding: '0 4px 8px' }}>{g}</SectionLabel>
          <div style={{ background: '#fff', borderRadius: 20, overflow: 'hidden', border: `1px solid ${T.hair}` }}>
            {grouped[g].map((it, i) => {
              const on = checked[it.id];
              return (
                <button key={it.id} onClick={() => setChecked(c => ({ ...c, [it.id]: !c[it.id] }))} style={{
                  all: 'unset', cursor: 'pointer', width: '100%', boxSizing: 'border-box',
                  display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                  borderBottom: i === grouped[g].length - 1 ? 'none' : `1px solid ${T.hair}`,
                }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: 8,
                    background: on ? T.moss : 'transparent',
                    border: on ? `1px solid ${T.moss}` : `1.5px solid ${T.hair}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    {on && <Icon name="check" size={16} color="#fff" stroke={2.4}/>}
                  </div>
                  <div style={{ flex: 1, fontSize: 14.5, color: on ? T.ink : T.inkSoft,
                    textDecoration: on ? 'none' : 'none' }}>
                    {it.text}
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────
// Hemograma simulator
window.HemogramaScreen = function HemogramaScreen({ T, onNavigate }) {
  const [eos, setEos] = React.useState(820); // /mm³ — normal 50-500
  const [bas, setBas] = React.useState(80);   // /mm³ — normal 0-100
  const [fer, setFer] = React.useState(45);   // ng/mL — normal 30-300

  const eosStatus = eos > 500 ? { label: 'Eosinofilia', color: T.clay } : { label: 'Normal', color: T.moss };
  const basStatus = bas > 100 ? { label: 'Basofilia', color: T.lavender } : { label: 'Normal', color: T.moss };
  const ferStatus = fer < 30 ? { label: 'Baixa', color: T.rose } : fer > 300 ? { label: 'Alta', color: T.clay } : { label: 'Normal', color: T.moss };

  const hints = [];
  if (eos > 500) hints.push({ color: T.clay, text: 'Eosinofilia sugere helmintíase ativa (Ascaris, Strongyloides, Schistosoma).' });
  if (bas > 100) hints.push({ color: T.lavender, text: 'Basofilia leve pode acompanhar reações de hipersensibilidade.' });
  if (fer < 30) hints.push({ color: T.rose, text: 'Ferritina baixa: investigar perdas crônicas (ancilostomíase, esquistossomose).' });
  if (!hints.length) hints.push({ color: T.moss, text: 'Resultados dentro da faixa de referência — sem sinais laboratoriais de parasitose.' });

  return (
    <div style={{ padding: '0 20px 120px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ paddingTop: 14 }}>
        <button onClick={() => onNavigate('home')} style={{
          all: 'unset', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 13, color: T.inkSoft, marginBottom: 12,
        }}>
          <Icon name="chevron" size={14} stroke={2} color={T.inkSoft}/> Início
        </button>
        <SectionLabel color={T.water}>Lab analyzer · didático</SectionLabel>
        <h1 style={{
          fontFamily: 'Georgia, serif', fontSize: 30, lineHeight: 1.05,
          margin: '6px 0 0', color: T.ink, fontWeight: 500, letterSpacing: -0.5,
        }}>Simulador de<br/><span style={{ fontStyle: 'italic', color: T.water }}>hemograma.</span></h1>
      </div>

      <HemoControl label="Eosinófilos" unit="/mm³" value={eos} min={0} max={2500} normal={[50, 500]} status={eosStatus} onChange={setEos} T={T}/>
      <HemoControl label="Basófilos" unit="/mm³" value={bas} min={0} max={400} normal={[0, 100]} status={basStatus} onChange={setBas} T={T}/>
      <HemoControl label="Ferritina" unit="ng/mL" value={fer} min={0} max={500} normal={[30, 300]} status={ferStatus} onChange={setFer} T={T}/>

      <div style={{
        background: T.ink, color: '#fff', borderRadius: 22, padding: 18,
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        <SectionLabel color="rgba(255,255,255,0.5)">Interpretação</SectionLabel>
        {hints.map((h, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <span style={{ width: 8, height: 8, borderRadius: 99, background: h.color, marginTop: 7, flexShrink: 0 }}/>
            <div style={{ fontSize: 13.5, lineHeight: 1.5, color: 'rgba(255,255,255,0.85)' }}>{h.text}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

function HemoControl({ label, unit, value, min, max, normal, status, onChange, T }) {
  const pct = (value - min) / (max - min);
  const nMin = (normal[0] - min) / (max - min);
  const nMax = (normal[1] - min) / (max - min);
  return (
    <div style={{ background: '#fff', borderRadius: 22, padding: 16, border: `1px solid ${T.hair}` }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'Georgia, serif', fontSize: 18, color: T.ink, fontWeight: 500 }}>{label}</div>
          <div style={{ fontSize: 11, color: T.inkSoft, marginTop: 2, fontFamily: 'ui-monospace, monospace' }}>
            Referência: {normal[0]}–{normal[1]} {unit}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 26, color: status.color, fontWeight: 500, lineHeight: 1 }}>
            {value}<span style={{ fontSize: 12, opacity: 0.55 }}> {unit}</span>
          </div>
          <Pill color={status.color} bg={`${status.color}14`} style={{ marginTop: 6 }}>{status.label}</Pill>
        </div>
      </div>
      <div style={{ marginTop: 16, position: 'relative', height: 30 }}>
        {/* track */}
        <div style={{
          position: 'absolute', top: 12, left: 0, right: 0, height: 6,
          background: T.hair, borderRadius: 99,
        }}/>
        {/* normal range band */}
        <div style={{
          position: 'absolute', top: 12, height: 6, borderRadius: 99,
          left: `${nMin * 100}%`, width: `${(nMax - nMin) * 100}%`,
          background: `${T.moss}55`,
        }}/>
        {/* fill up to value */}
        <div style={{
          position: 'absolute', top: 12, height: 6, borderRadius: 99,
          left: 0, width: `${pct * 100}%`,
          background: status.color, opacity: 0.5,
        }}/>
        {/* thumb */}
        <input
          type="range" min={min} max={max} value={value}
          onChange={(e) => onChange(parseInt(e.target.value))}
          style={{ width: '100%', position: 'absolute', top: 0, left: 0,
            opacity: 0, height: 30, cursor: 'pointer', margin: 0 }}
        />
        <div style={{
          position: 'absolute', top: 6, left: `calc(${pct * 100}% - 9px)`,
          width: 18, height: 18, borderRadius: 99,
          background: '#fff', border: `3px solid ${status.color}`,
          boxShadow: '0 2px 6px rgba(0,0,0,0.15)', pointerEvents: 'none',
        }}/>
      </div>
    </div>
  );
}
