// Triagem — Wizard + Live Drawer
const { useState: useStateT, useMemo: useMemoT } = React;

// Bayesian-ish steps (didactic, not real LR)
window.TRIAGE_STEPS = [
  { id: 'digestive', title: 'Sintomas digestivos', subtitle: 'Etapa 1 · Marque o que sente',
    color: '#0f5147', options: [
      { id: 'd1', label: 'Diarreia persistente', detail: 'Mais de 7 dias', weights: { giardia: 1.6, ascaris: 0.9, schisto: 1.0, enterobius: 0.2 } },
      { id: 'd2', label: 'Dor abdominal em cólica', weights: { ascaris: 1.4, taenia: 1.1, giardia: 0.9 } },
      { id: 'd3', label: 'Distensão / gases', weights: { giardia: 1.5, ascaris: 0.8 } },
      { id: 'd4', label: 'Fezes gordurosas (esteatorreia)', weights: { giardia: 2.1 } },
      { id: 'd5', label: 'Sangue nas fezes', weights: { schisto: 2.2 }, redFlag: true },
      { id: 'd6', label: 'Eliminação de proglotes', weights: { taenia: 3.5 } },
    ]
  },
  { id: 'skin', title: 'Pele e prurido', subtitle: 'Etapa 2 · Sinais cutâneos',
    color: '#618544', options: [
      { id: 's1', label: 'Prurido anal noturno', weights: { enterobius: 3.0 } },
      { id: 's2', label: 'Larva migrans (lesão linear)', weights: { strongy: 2.4 } },
      { id: 's3', label: 'Urticária recorrente', weights: { strongy: 1.4, ascaris: 1.2 } },
      { id: 's4', label: 'Edema palpebral unilateral', weights: { chagas: 2.6 } },
    ]
  },
  { id: 'systemic', title: 'Sintomas sistêmicos', subtitle: 'Etapa 3 · Quadro geral',
    color: '#217f8c', options: [
      { id: 'sy1', label: 'Febre prolongada (>7 dias)', weights: { toxo: 1.6, schisto: 1.3, chagas: 1.4 } },
      { id: 'sy2', label: 'Perda de peso involuntária', weights: { taenia: 1.6, ascaris: 1.0 } },
      { id: 'sy3', label: 'Fadiga / palidez', weights: { ascaris: 1.2, schisto: 1.1 } },
      { id: 'sy4', label: 'Linfonodos aumentados', weights: { toxo: 1.8, chagas: 1.2 } },
    ]
  },
  { id: 'neuro', title: 'Sistema neurológico', subtitle: 'Etapa 4 · Sinais de alerta',
    color: '#74629b', options: [
      { id: 'n1', label: 'Cefaleia persistente', weights: { toxo: 1.3 } },
      { id: 'n2', label: 'Convulsões recentes', weights: { taenia: 2.4 }, redFlag: true },
      { id: 'n3', label: 'Alterações visuais', weights: { toxo: 1.6 } },
    ]
  },
  { id: 'urgent', title: 'Urgência clínica', subtitle: 'Etapa 5 · Procure atendimento se marcar',
    color: '#b94a5d', options: [
      { id: 'u1', label: 'Sangue vivo nas fezes ou vômito', weights: {}, redFlag: true },
      { id: 'u2', label: 'Desidratação severa', weights: {}, redFlag: true },
      { id: 'u3', label: 'Febre acima de 39,5°C', weights: {}, redFlag: true },
    ]
  },
  { id: 'exposure', title: 'Histórico de exposição', subtitle: 'Etapa 6 · Contexto ajuda muito',
    color: '#c15f42', options: [
      { id: 'e1', label: 'Banho em rio / lagoa', weights: { schisto: 2.0, strongy: 1.0 } },
      { id: 'e2', label: 'Carne mal passada (bovina/suína)', weights: { taenia: 2.4, toxo: 1.5 } },
      { id: 'e3', label: 'Contato com gatos / areia', weights: { toxo: 1.8 } },
      { id: 'e4', label: 'Andar descalço em solo úmido', weights: { strongy: 1.6, ascaris: 1.1 } },
      { id: 'e5', label: 'Área endêmica de Chagas', weights: { chagas: 2.2 } },
      { id: 'e6', label: 'Higiene precária da água', weights: { giardia: 1.5, ascaris: 1.4 } },
    ]
  },
];

function computeProbs(selected) {
  // start with prior prevalences
  const logOdds = {};
  PARASITES.forEach(p => { logOdds[p.id] = Math.log(p.prevalence / (1 - p.prevalence)); });
  // accumulate
  Object.values(selected).forEach(opt => {
    Object.entries(opt.weights || {}).forEach(([pid, lr]) => {
      if (logOdds[pid] !== undefined) logOdds[pid] += Math.log(lr);
    });
  });
  // odds -> probability
  const results = PARASITES.map(p => {
    const o = Math.exp(logOdds[p.id]);
    return { ...p, prob: o / (1 + o) };
  }).sort((a, b) => b.prob - a.prob);
  return results;
}
window.computeProbs = computeProbs;

window.TriagemScreen = function TriagemScreen({ T, onNavigate, gestante, savedProbs, setSavedProbs }) {
  const [step, setStep] = useStateT(0);
  const [selected, setSelected] = useStateT({}); // id -> option
  const [drawer, setDrawer] = useStateT(false);
  const [prevTop, setPrevTop] = useStateT([]);
  const [toast, setToast] = useStateT(null);

  const current = TRIAGE_STEPS[step];
  const progress = (step + 1) / TRIAGE_STEPS.length;

  const probs = useMemoT(() => computeProbs(selected), [selected]);
  const top3Ids = probs.slice(0, 3).map(p => p.id).join(',');

  // detect "entered top 3"
  React.useEffect(() => {
    if (!prevTop.length) { setPrevTop(probs.slice(0, 3).map(p => p.id)); return; }
    const now = probs.slice(0, 3).map(p => p.id);
    const newEntry = now.find(id => !prevTop.includes(id));
    if (newEntry) {
      const p = PARASITES.find(x => x.id === newEntry);
      setToast({ text: `${p.popular} entrou no Top 3`, color: p.color });
      setTimeout(() => setToast(null), 2400);
    }
    setPrevTop(now);
  }, [top3Ids]);

  const toggle = (opt) => {
    setSelected(s => {
      const next = { ...s };
      if (next[opt.id]) delete next[opt.id];
      else next[opt.id] = opt;
      return next;
    });
  };

  const isLast = step === TRIAGE_STEPS.length - 1;

  const finish = () => {
    setSavedProbs(probs);
    onNavigate('resultado');
  };

  const redFlagActive = Object.values(selected).some(o => o.redFlag);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Sticky header */}
      <div style={{ padding: '0 20px 12px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <button onClick={() => onNavigate('home')} style={{
            all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4,
            color: T.inkSoft, fontSize: 14, fontWeight: 500,
          }}>
            <Icon name="close" size={20} stroke={2}/>
          </button>
          <SectionLabel>Etapa {step + 1} de {TRIAGE_STEPS.length}</SectionLabel>
          <button onClick={() => setDrawer(true)} style={{
            all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
            padding: '6px 10px', borderRadius: 99, background: T.forestDeep, color: '#fff',
            fontSize: 11, letterSpacing: 0.5, textTransform: 'uppercase', fontFamily: 'ui-monospace, monospace',
            fontWeight: 600,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 99, background: T.acid, boxShadow: `0 0 8px ${T.acid}` }}/>
            Top {probs.slice(0,3).filter(p => p.prob > 0.03).length}
          </button>
        </div>
        {/* progress bar */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 18 }}>
          {TRIAGE_STEPS.map((s, i) => (
            <div key={s.id} style={{
              flex: 1, height: 4, borderRadius: 99,
              background: i <= step ? current.color : T.hair,
              transition: 'background 0.3s',
            }}/>
          ))}
        </div>
        <SectionLabel color={current.color}>{current.subtitle}</SectionLabel>
        <h2 style={{
          fontFamily: 'Georgia, serif', fontSize: 26, lineHeight: 1.1,
          margin: '6px 0 0', color: T.ink, letterSpacing: -0.4, fontWeight: 500,
        }}>{current.title}</h2>
      </div>

      {/* Red flag banner */}
      {redFlagActive && (
        <div style={{
          margin: '0 20px 12px', padding: '12px 14px', borderRadius: 16,
          background: '#b94a5d', color: '#fff',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <Icon name="alert" size={20} color="#fff" stroke={2}/>
          <div>
            <div style={{ fontWeight: 600, fontSize: 13 }}>Sinal de urgência marcado</div>
            <div style={{ fontSize: 12, opacity: 0.85 }}>Procure atendimento médico hoje.</div>
          </div>
        </div>
      )}

      {/* Options */}
      <div style={{ flex: 1, overflow: 'auto', padding: '0 20px 12px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {current.options.map((opt, i) => {
            const on = !!selected[opt.id];
            return (
              <button key={opt.id} onClick={() => toggle(opt)} style={{
                all: 'unset', cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 16px', borderRadius: 18,
                background: on ? current.color : '#fff',
                color: on ? '#fff' : T.ink,
                border: `1px solid ${on ? current.color : T.hair}`,
                transition: 'all 0.2s',
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 8,
                  background: on ? 'rgba(255,255,255,0.18)' : T.paperWarm,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'ui-monospace, monospace', fontSize: 12, fontWeight: 600,
                  color: on ? '#fff' : T.inkSoft, flexShrink: 0,
                }}>
                  {on ? <Icon name="check" size={16} color="#fff" stroke={2.4}/> : String(i+1).padStart(2,'0')}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 500, lineHeight: 1.2 }}>{opt.label}</div>
                  {opt.detail && <div style={{ fontSize: 12, opacity: on ? 0.7 : 0.5, marginTop: 2 }}>{opt.detail}</div>}
                </div>
                {opt.redFlag && (
                  <Pill color={on ? '#fff' : '#b94a5d'} bg={on ? 'rgba(255,255,255,0.18)' : 'rgba(185,74,93,0.1)'} style={{ fontSize: 9.5 }}>
                    Urgência
                  </Pill>
                )}
              </button>
            );
          })}
        </div>

        <button onClick={() => toggle({ id: `none_${current.id}`, label: 'Nenhum dos itens acima', weights: {} })} style={{
          all: 'unset', cursor: 'pointer', display: 'block', textAlign: 'center',
          margin: '14px auto 0', padding: '10px 16px', borderRadius: 99,
          fontSize: 13, color: T.inkSoft, fontWeight: 500,
        }}>
          Nenhum dos itens acima
        </button>
      </div>

      {/* Bottom action — sticky */}
      <div style={{
        flexShrink: 0, padding: '12px 20px 32px',
        background: `linear-gradient(180deg, transparent 0%, ${T.paper} 30%)`,
        display: 'flex', gap: 10,
      }}>
        {step > 0 && (
          <button onClick={() => setStep(step - 1)} style={{
            all: 'unset', cursor: 'pointer',
            padding: '14px 18px', borderRadius: 99, fontWeight: 600,
            background: '#fff', color: T.ink, border: `1px solid ${T.hair}`,
            fontSize: 14,
          }}>Voltar</button>
        )}
        <button
          onClick={isLast ? finish : () => setStep(step + 1)}
          style={{
            all: 'unset', cursor: 'pointer', flex: 1,
            padding: '14px 20px', borderRadius: 99, fontWeight: 600,
            background: T.forestDeep, color: '#fff', textAlign: 'center',
            fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: `0 8px 24px -10px ${T.forestDeep}`,
          }}>
          {isLast ? 'Ver resultados' : 'Próxima etapa'}
          <Icon name="arrow" size={16} color="#fff" stroke={2.2}/>
        </button>
      </div>

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'absolute', left: 20, right: 20, top: 90, zIndex: 30,
          padding: '12px 14px', borderRadius: 16, background: T.ink, color: '#fff',
          display: 'flex', alignItems: 'center', gap: 10,
          boxShadow: '0 14px 40px -10px rgba(0,0,0,0.4)',
        }}>
          <Icon name="sparkle" size={18} color={toast.color} stroke={2}/>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{toast.text}</div>
        </div>
      )}

      {/* Live Drawer (bottom sheet) */}
      {drawer && <LiveDrawer T={T} probs={probs} selected={selected} onClose={() => setDrawer(false)}/>}
    </div>
  );
};

function LiveDrawer({ T, probs, selected, onClose }) {
  const visible = probs.filter(p => p.prob > 0.03);
  const discarded = probs.filter(p => p.prob <= 0.03);
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 40,
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      background: 'rgba(15,30,28,0.4)', backdropFilter: 'blur(4px)',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: T.paper, borderRadius: '28px 28px 0 0',
        padding: '14px 20px 30px', maxHeight: '82%',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.18)',
      }}>
        {/* handle */}
        <div style={{ width: 40, height: 5, borderRadius: 99, background: T.hair, margin: '0 auto 14px' }}/>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
          <div>
            <SectionLabel>Painel ao vivo</SectionLabel>
            <h3 style={{ fontFamily: 'Georgia, serif', fontSize: 22, margin: '4px 0 0', color: T.ink, letterSpacing: -0.3, fontWeight: 500 }}>
              Ranking probabilístico
            </h3>
          </div>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', padding: 8 }}>
            <Icon name="close" size={20} color={T.inkSoft}/>
          </button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', paddingBottom: 8 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {visible.map((p, i) => (
              <div key={p.id} style={{
                background: '#fff', padding: '12px 14px', borderRadius: 16,
                border: `1px solid ${T.hair}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 6, background: `${p.color}18`,
                    color: p.color, fontFamily: 'ui-monospace, monospace', fontSize: 11, fontWeight: 600,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{i + 1}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14.5, color: T.ink, fontWeight: 500 }}>{p.popular}</div>
                    <div style={{ fontFamily: 'Georgia, serif', fontStyle: 'italic', fontSize: 11.5, color: T.inkSoft }}>
                      {p.name}
                    </div>
                  </div>
                  <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 16, color: p.color, fontWeight: 600 }}>
                    {Math.round(p.prob * 100)}%
                  </div>
                </div>
                <ProbBar value={p.prob} color={p.color}/>
              </div>
            ))}
          </div>

          {discarded.length > 0 && (
            <div style={{ marginTop: 16 }}>
              <SectionLabel style={{ marginBottom: 8 }}>Descartados (&lt;3%)</SectionLabel>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {discarded.map(p => (
                  <Pill key={p.id} color={T.inkMuted} bg={T.hair} style={{ textTransform: 'none', letterSpacing: 0, fontSize: 11, fontFamily: 'system-ui' }}>
                    {p.popular}
                  </Pill>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
