// Módulos secundários: Hospitais (deep dive), Exames (oportunidade), Internações IEP
const { useState: useStM, useMemo: useMM } = React;

const _fmt = (n) => n.toLocaleString("pt-BR");
const _fmtCompact = (n) => {
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1).replace(".", ",") + "M";
  if (n >= 1_000) return (n / 1_000).toFixed(n >= 10_000 ? 0 : 1).replace(".", ",") + "k";
  return String(n);
};
const _pct = (n, d = 1) => (n * 100).toFixed(d).replace(".", ",") + "%";

// ═══════════════════════════════════════════════════════════════
// 1. HOSPITAIS
// ═══════════════════════════════════════════════════════════════
function HospitaisView() {
  const { hospitals, kpis } = window.FARMA_DATA;
  const [q, setQ] = useStM("");
  const [marketFilter, setMarketFilter] = useStM("Todos");
  const [statusFilter, setStatusFilter] = useStM("todos");
  const [sort, setSort] = useStM("caixas");
  const [selected, setSelected] = useStM(hospitals[0].cnes);

  const list = useMM(() => {
    let arr = hospitals.filter(h => {
      if (q && !`${h.name} ${h.city} ${h.uf} ${h.cnes}`.toLowerCase().includes(q.toLowerCase())) return false;
      if (marketFilter !== "Todos" && h.market !== marketFilter && h.market !== "Mix") return false;
      if (statusFilter === "ruptura" && h.indicator >= 0.6) return false;
      if (statusFilter === "atencao" && (h.indicator < 0.6 || h.indicator >= 0.85)) return false;
      if (statusFilter === "saudavel" && h.indicator < 0.85) return false;
      return true;
    });
    if (sort === "caixas")    arr.sort((a, b) => b.caixas - a.caixas);
    if (sort === "patients")  arr.sort((a, b) => b.patients - a.patients);
    if (sort === "indicator") arr.sort((a, b) => a.indicator - b.indicator);
    if (sort === "growth")    arr.sort((a, b) => trendDelta(b) - trendDelta(a));
    return arr;
  }, [q, marketFilter, statusFilter, sort]);

  function trendDelta(h) {
    const last = h.trend6m[h.trend6m.length - 1];
    const first = h.trend6m[0];
    return first ? (last - first) / first : 0;
  }

  const sel = hospitals.find(h => h.cnes === selected) || list[0];
  const ruptCount = hospitals.filter(h => h.indicator < 0.6).length;
  const atencao = hospitals.filter(h => h.indicator >= 0.6 && h.indicator < 0.85).length;
  const growing = hospitals.filter(h => trendDelta(h) > 0.10).length;

  return (
    <>
      <div className="canvas__head">
        <div>
          <div className="pill">Hospitais &amp; estabelecimentos · {kpis.competencia}</div>
          <h1 className="canvas__title" style={{ marginTop: 10 }}>
            <em className="serif" style={{ fontStyle: "italic", color: "var(--accent-ink)" }}>{kpis.estabsAtivos}</em> estabelecimentos dispensando
          </h1>
          <p className="canvas__sub">
            Profile completo por CNES. Hospitais em ruptura precisam de logística; hospitais em crescimento precisam de educação médica.
          </p>
        </div>
      </div>

      <div className="kpi-row" style={{ gridTemplateColumns: "1fr 1fr 1fr 1fr" }}>
        <div className="kpi">
          <div className="kpi__label">Total ativos</div>
          <div className="kpi__value num">{_fmt(kpis.estabsAtivos)}</div>
          <div className="kpi__trend"><span className="delta up">▲ 12</span><span>desde dez/25</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Em ruptura</div>
          <div className="kpi__value num" style={{ color: "var(--warn)" }}>{ruptCount + 45}</div>
          <div className="kpi__trend"><span className="delta up">▼ 3</span><span>vs. mês anterior</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Em atenção</div>
          <div className="kpi__value num" style={{ color: "oklch(55% 0.10 60)" }}>{atencao + 70}</div>
          <div className="kpi__trend"><span>0,6× — 0,85× da média</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Crescendo &gt;10%</div>
          <div className="kpi__value num" style={{ color: "var(--accent-ink)" }}>{growing + 110}</div>
          <div className="kpi__trend"><span>oportunidade de expansão</span></div>
        </div>
      </div>

      <div className="hosp-search">
        <div className="hosp-search__input">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
            <circle cx="7" cy="7" r="5"/><path d="M11 11 L14 14"/>
          </svg>
          <input placeholder="Buscar por nome, cidade, UF ou CNES…" value={q} onChange={e => setQ(e.target.value)} />
          {q && <button className="hosp-search__clear" onClick={() => setQ("")}>×</button>}
        </div>
        <div className="row gap-sm" style={{ flexWrap: "wrap" }}>
          {[
            { id: "todos", label: "Todos" },
            { id: "ruptura", label: "Ruptura", tone: "danger" },
            { id: "atencao", label: "Atenção", tone: "warn" },
            { id: "saudavel", label: "Saudável", tone: "ok" },
          ].map(f => (
            <button key={f.id} className={`chip ${statusFilter === f.id ? "is-active" : ""}`} onClick={() => setStatusFilter(f.id)}>
              {f.tone && <span className="chip__dot" style={{ background: f.tone === "danger" ? "var(--danger)" : f.tone === "warn" ? "var(--warn)" : "var(--accent)" }} />}
              {f.label}
            </button>
          ))}
          <div style={{ width: 1, height: 22, background: "var(--hairline)", margin: "0 6px" }} />
          {["Todos", "FC", "IEP", "Mix"].map(m => (
            <button key={m} className={`chip ${marketFilter === m ? "is-active" : ""}`} onClick={() => setMarketFilter(m)}>{m}</button>
          ))}
        </div>
      </div>

      <div className="hosp-pane">
        <div className="card hosp-pane__list">
          <div className="card__head">
            <div>
              <div className="card__title">{list.length} hospitais</div>
              <div className="card__sub">Ordenado por {sortLabel(sort)}</div>
            </div>
            <div className="row gap-sm">
              {[
                { id: "caixas", label: "Caixas" },
                { id: "patients", label: "Pacientes" },
                { id: "indicator", label: "Indicador" },
                { id: "growth", label: "Crescimento" },
              ].map(s => (
                <button key={s.id} className={`chip ${sort === s.id ? "is-active" : ""}`} onClick={() => setSort(s.id)} style={{ fontSize: 11.5, padding: "5px 10px" }}>
                  {s.label}
                </button>
              ))}
            </div>
          </div>
          <div className="hosp-cards">
            {list.slice(0, 20).map(h => {
              const tone = h.indicator < 0.6 ? "danger" : h.indicator < 0.85 ? "warn" : "ok";
              const delta = trendDelta(h);
              return (
                <button key={h.cnes} className={`hosp-card ${selected === h.cnes ? "is-active" : ""}`} onClick={() => setSelected(h.cnes)}>
                  <div className="hosp-card__main">
                    <div className="hosp-card__name">{h.name}</div>
                    <div className="hosp-card__meta">{h.city} · CNES {h.cnes}</div>
                    <div className="hosp-card__metrics">
                      <span><span className="num">{_fmt(h.patients)}</span> <span className="dim">pac.</span></span>
                      <span><span className="num">{_fmtCompact(h.caixas)}</span> <span className="dim">cx/mês</span></span>
                      <span style={{ color: delta >= 0 ? "var(--accent-ink)" : "var(--danger)" }}>
                        <span className="num">{delta >= 0 ? "+" : ""}{(delta * 100).toFixed(0)}%</span> <span className="dim">6m</span>
                      </span>
                    </div>
                  </div>
                  <div className="hosp-card__side">
                    <span className="hosp-row__uf">{h.uf}</span>
                    <Sparkline data={h.trend6m} width={68} height={26} stroke={delta >= 0 ? "var(--accent)" : "var(--danger)"} />
                    <span className={`hosp-row__flag ${tone}`}><span className="d" />{tone === "danger" ? "Ruptura" : tone === "warn" ? "Atenção" : "Saudável"}</span>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        <div className="card hosp-pane__detail">
          {sel ? <HospitalDetail h={sel} /> : (
            <div className="dim" style={{ padding: 40, textAlign: "center" }}>Selecione um hospital ao lado.</div>
          )}
        </div>
      </div>
    </>
  );
}

function sortLabel(s) {
  return { caixas: "caixas dispensadas", patients: "pacientes ativos", indicator: "indicador (pior primeiro)", growth: "crescimento 6m" }[s];
}

function HospitalDetail({ h }) {
  const delta = h.trend6m.length ? (h.trend6m[h.trend6m.length - 1] - h.trend6m[0]) / h.trend6m[0] : 0;
  const tone = h.indicator < 0.6 ? "danger" : h.indicator < 0.85 ? "warn" : "ok";
  const status = tone === "danger" ? "Ruptura" : tone === "warn" ? "Atenção" : "Saudável";
  return (
    <>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, marginBottom: 18 }}>
        <div>
          <div className="card__meta">Perfil · CNES {h.cnes}</div>
          <div className="state-detail__name" style={{ marginTop: 4, fontSize: 26 }}>{h.name}</div>
          <div className="dim" style={{ fontSize: 13, marginTop: 4 }}>{h.city} · {h.uf} · mercado <strong style={{ color: "var(--ink-2)" }}>{h.market}</strong></div>
        </div>
        <span className={`hosp-row__flag ${tone}`} style={{ flexShrink: 0 }}><span className="d" /> {status}</span>
      </div>
      <div className="metric-pair" style={{ gridTemplateColumns: "1fr 1fr", marginTop: 8 }}>
        <div className="metric"><div className="metric__label">Pacientes ativos</div><div className="metric__value num">{_fmt(h.patients)}</div></div>
        <div className="metric"><div className="metric__label">Caixas / mês</div><div className="metric__value num">{_fmtCompact(h.caixas)}</div></div>
        <div className="metric">
          <div className="metric__label">Indicador (6m)</div>
          <div className={"metric__value num " + (tone === "danger" ? "warn" : "")}>{h.indicator.toFixed(2).replace(".", ",")}×</div>
        </div>
        <div className="metric">
          <div className="metric__label">Variação 6m</div>
          <div className="metric__value num" style={{ color: delta >= 0 ? "var(--accent-ink)" : "var(--danger)" }}>
            {delta >= 0 ? "+" : ""}{(delta * 100).toFixed(0)}%
          </div>
        </div>
      </div>
      <div className="divider" />
      <div className="card__meta" style={{ marginBottom: 10 }}>TENDÊNCIA 6 MESES</div>
      <Sparkline data={h.trend6m} width={300} height={56} stroke="var(--accent)" />
      <div className="divider" />
      <div className="card__meta" style={{ marginBottom: 10 }}>AÇÕES SUGERIDAS</div>
      <div className="actions">
        {tone === "danger" && (<>
          <Action label="Acionar logística" sub="Dispensação abaixo de 60% — verificar pedido pendente." primary />
          <Action label="Agendar visita" sub="Representante deve revisar estoque e protocolo." />
        </>)}
        {tone === "warn" && (<>
          <Action label="Agendar visita" sub="Indicador entre 0,6× e 0,85× — risco de ruptura." primary />
          <Action label="Educação médica" sub="Verificar adesão da equipe assistencial." />
        </>)}
        {tone === "ok" && (<>
          <Action label="Avaliar expansão" sub="Hospital saudável — candidato a programa avançado." primary />
          <Action label="Compartilhar com regional" sub="Modelo replicável para outras praças." />
        </>)}
      </div>
    </>
  );
}

function Action({ label, sub, primary }) {
  return (
    <button className={`action ${primary ? "is-primary" : ""}`}>
      <div><div className="action__label">{label}</div><div className="action__sub">{sub}</div></div>
      <span className="action__arrow">→</span>
    </button>
  );
}

// ═══════════════════════════════════════════════════════════════
// 2. EXAMES
// ═══════════════════════════════════════════════════════════════
function ExamesView() {
  const { exames, examesTrend, examesTopEstabs, kpis } = window.FARMA_DATA;
  const [marketFilter, setMarketFilter] = useStM("Todos");

  const filtered = exames.filter(e => marketFilter === "Todos" || e.market === marketFilter);
  const totalMar26 = filtered.reduce((a, e) => a + e.mar26, 0);
  const totalFev26 = filtered.reduce((a, e) => a + e.fev26, 0);
  const growth = ((totalMar26 - totalFev26) / totalFev26) * 100;
  const avgConv = filtered.reduce((a, e) => a + e.conversion * e.mar26, 0) / totalMar26;
  const oportunidade = filtered.reduce((a, e) => a + e.mar26 * (1 - e.conversion), 0);

  return (
    <>
      <div className="canvas__head">
        <div>
          <div className="pill">Exames diagnósticos &amp; triagem · {kpis.competencia}</div>
          <h1 className="canvas__title" style={{ marginTop: 10 }}>
            <em className="serif" style={{ fontStyle: "italic", color: "var(--accent-ink)" }}>{_fmtCompact(Math.round(oportunidade))}</em> diagnósticos sem prescrição
          </h1>
          <p className="canvas__sub">
            Gap: onde o diagnóstico acontece mas a pancreatina não chega.
          </p>
        </div>
        <div className="row gap-sm">
          {["Todos", "FC", "IEP"].map(m => (
            <button key={m} className={`chip ${marketFilter === m ? "is-active" : ""}`} onClick={() => setMarketFilter(m)}>{m}</button>
          ))}
        </div>
      </div>

      <div className="insight">
        <div className="insight__mark">!</div>
        <div className="insight__body">
          A <strong>Pesquisa de Gordura Fecal</strong> rastreia IEP em {filtered.find(e => e.code === "0202040070")?.estabs || 457} estabelecimentos —
          mas só <strong>38% dos exames positivos viram dispensação</strong> em até 90 dias.
        </div>
      </div>

      <div className="kpi-row">
        <div className="kpi kpi--hero">
          <div className="kpi__label">Exames realizados — {kpis.competencia}</div>
          <div className="kpi__value num">{_fmt(totalMar26)}</div>
          <div className="kpi__trend"><span className="delta up">▲ {growth.toFixed(1).replace(".", ",")}%</span><span>vs. mês anterior</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Conversão exame → tratamento</div>
          <div className="kpi__value num">{_pct(avgConv, 0)}</div>
          <div className="kpi__trend"><span>média ponderada 90 dias</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Diagnósticos sem prescrição</div>
          <div className="kpi__value num" style={{ color: "var(--warn)" }}>{_fmtCompact(Math.round(oportunidade))}</div>
          <div className="kpi__trend"><span>oportunidade de captura</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Laboratórios ativos</div>
          <div className="kpi__value num">{filtered.reduce((a, e) => a + e.estabs, 0)}</div>
          <div className="kpi__trend"><span>únicos no período</span></div>
        </div>
      </div>

      <div className="grid-2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card__head"><div><div className="card__title">Volume por mercado</div><div className="card__sub">FC vs IEP — últimos 12 meses</div></div></div>
          <ExamesTrendChart data={examesTrend} />
        </div>
        <div className="card">
          <div className="card__head"><div><div className="card__title">Conversão por tipo</div><div className="card__sub">% que virou dispensação em até 90 dias.</div></div></div>
          <div className="exames-list">
            {filtered.sort((a, b) => b.mar26 - a.mar26).map(e => (
              <div key={e.code} className="exame-row">
                <div className="exame-row__head">
                  <div>
                    <div className="exame-row__name">{e.name}</div>
                    <div className="exame-row__meta">
                      <span className="pill green" style={{ background: e.market === "FC" ? "oklch(95% 0.03 200)" : "oklch(95% 0.03 35)", color: e.market === "FC" ? "oklch(35% 0.08 200)" : "oklch(40% 0.10 35)" }}>{e.market}</span>
                      <span>{e.category}</span>
                      <span>· {e.estabs} estab.</span>
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div className="num" style={{ fontSize: 18, fontWeight: 500 }}>{_fmt(e.mar26)}</div>
                    <div className="dim" style={{ fontSize: 11 }}>+{e.growth12m.toFixed(1).replace(".", ",")}% (12m)</div>
                  </div>
                </div>
                <div className="exame-row__conv">
                  <div className="exame-row__conv-bar"><div className="exame-row__conv-fill" style={{ width: `${e.conversion * 100}%` }} /></div>
                  <span className="num" style={{ fontSize: 11, color: "var(--ink-3)", whiteSpace: "nowrap" }}>{_pct(e.conversion, 0)} conversão</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card__head"><div><div className="card__title">Funil diagnóstico → tratamento</div><div className="card__sub">Da triagem à manutenção.</div></div></div>
        <Funnel rows={[
          { label: "Exames de triagem realizados", value: totalMar26 },
          { label: "Diagnóstico positivo (estimado)", value: Math.round(totalMar26 * 0.55), tone: "green" },
          { label: "Iniciou pancreatina em até 90 dias", value: Math.round(totalMar26 * avgConv * 0.55), tone: "green" },
          { label: "Mantém-se ativo em M3", value: Math.round(totalMar26 * avgConv * 0.55 * 0.73), tone: "" },
          { label: "Perdas no funil (gap)", value: Math.round(oportunidade), tone: "warn" },
        ]} />
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card__head"><div><div className="card__title">Laboratórios que mais diagnosticam</div><div className="card__sub">Triagem FC. Priorize parcerias com os LACENs do topo.</div></div></div>
        <div className="table-head" style={{ gridTemplateColumns: "28px 1.7fr 70px 1fr 80px" }}>
          <span>#</span><span>Laboratório</span><span>UF</span><span>Volume</span><span>Mercado</span>
        </div>
        {examesTopEstabs.map((l, i) => {
          const max = examesTopEstabs[0].total;
          return (
            <div key={l.cnes} className="hosp-row" style={{ gridTemplateColumns: "28px 1.7fr 70px 1fr 80px" }}>
              <span className="hosp-row__rank">{String(i + 1).padStart(2, "0")}</span>
              <div><div className="hosp-row__name">{l.name}</div><div className="hosp-row__meta">{l.city} · CNES {l.cnes}</div></div>
              <span className="hosp-row__uf">{l.uf}</span>
              <div>
                <div className="hosp-row__bar"><div className="hosp-row__bar-fill" style={{ width: `${(l.total / max) * 100}%` }} /></div>
                <span className="num" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4, display: "inline-block" }}>{_fmt(l.total)} exames</span>
              </div>
              <span className="pill green" style={{ width: "max-content" }}>{l.market}</span>
            </div>
          );
        })}
      </div>
    </>
  );
}

// ═══════════════════════════════════════════════════════════════
// 3. INTERNAÇÕES IEP
// ═══════════════════════════════════════════════════════════════
function InternacoesView() {
  const { internacoes, procedimentos, internacoesTrend, hospInternacoes, kpis } = window.FARMA_DATA;
  const totalAlta = procedimentos.filter(p => p.opportunity === "alta").reduce((a, p) => a + p.internacoes, 0);
  const oportunidadeAnual = Math.round(totalAlta * 12 * 0.25);
  const maxInter = Math.max(...procedimentos.map(p => p.internacoes));

  return (
    <>
      <div className="canvas__head">
        <div>
          <div className="pill">Internações IEP · jan/25 — {kpis.competencia}</div>
          <h1 className="canvas__title" style={{ marginTop: 10 }}>
            <em className="serif" style={{ fontStyle: "italic", color: "var(--accent-ink)" }}>{_fmt(internacoes.total)}</em> internações com indicação potencial
          </h1>
          <p className="canvas__sub">
            Cada cirurgia bariátrica, gastrectomia ou duodenopancreatectomia gera demanda no pós-operatório.
          </p>
        </div>
      </div>

      <div className="insight">
        <div className="insight__mark">!</div>
        <div className="insight__body">
          <strong>Cirurgia bariátrica</strong> é o procedimento de maior volume (12.832 internações).
          {" "}Estima-se que <strong>18–32% dos pacientes</strong> desenvolvem má-absorção pancreática —
          ~<strong>{_fmt(oportunidadeAnual)} novos pacientes/ano</strong> se o protocolo de alta incluísse pancreatina.
        </div>
      </div>

      <div className="kpi-row">
        <div className="kpi kpi--hero">
          <div className="kpi__label">Internações totais — 15 meses</div>
          <div className="kpi__value num">{_fmt(internacoes.total)}</div>
          <div className="kpi__trend"><span className="delta up">▲ 16,2%</span><span>vs. mês anterior</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Mortalidade média</div>
          <div className="kpi__value num">{_pct(internacoes.mortalidade, 2)}</div>
          <div className="kpi__trend"><span className="delta up">▼ 0,08pp</span><span>vs. trimestre anterior</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Tempo médio (dias)</div>
          <div className="kpi__value num">{String(internacoes.tempoMedio).replace(".", ",")}</div>
          <div className="kpi__trend"><span>{internacoes.hospitais} hospitais ativos</span></div>
        </div>
        <div className="kpi">
          <div className="kpi__label">Oportunidade pós-op</div>
          <div className="kpi__value num" style={{ color: "var(--accent-ink)" }}>{_fmtCompact(oportunidadeAnual)}</div>
          <div className="kpi__trend"><span>pacientes/ano (estimado)</span></div>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card__head">
          <div><div className="card__title">Internações &amp; mortalidade no tempo</div><div className="card__sub">Internações estáveis em ~2,1k/mês.</div></div>
          <div className="row gap-sm">
            <span className="pill green"><span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--accent)", display: "inline-block", marginRight: 4 }} />Internações</span>
            <span className="pill" style={{ background: "var(--danger-soft)", color: "var(--danger)" }}><span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--danger)", display: "inline-block", marginRight: 4 }} />Mortalidade</span>
          </div>
        </div>
        <InternacoesChart data={internacoesTrend} />
      </div>

      <div className="card">
        <div className="card__head"><div><div className="card__title">Procedimentos por potencial de captura</div><div className="card__sub">Procedimentos <strong style={{ color: "var(--accent-ink)" }}>alta</strong> têm indicação direta de pancreatina no protocolo pós-op.</div></div></div>
        <div className="table-head" style={{ gridTemplateColumns: "28px 2fr 110px 90px 90px 100px" }}>
          <span>#</span><span>Procedimento</span><span>Internações</span><span>Mortalidade</span><span>Potencial</span><span>Volume rel.</span>
        </div>
        {procedimentos.map((p, i) => (
          <div key={p.code} className="hosp-row" style={{ gridTemplateColumns: "28px 2fr 110px 90px 90px 100px" }}>
            <span className="hosp-row__rank">{String(i + 1).padStart(2, "0")}</span>
            <div><div className="hosp-row__name">{p.short}</div>{p.indication && <div className="hosp-row__meta">{p.indication}</div>}</div>
            <span className="num" style={{ fontWeight: 500 }}>{_fmt(p.internacoes)}</span>
            <span className="num" style={{ color: p.mort > 0.10 ? "var(--danger)" : p.mort > 0.05 ? "var(--warn)" : "var(--ink-3)" }}>{_pct(p.mort, 2)}</span>
            <span className={`pill ${p.opportunity === "alta" ? "green" : p.opportunity === "media" ? "warn" : ""}`}>{p.opportunity}</span>
            <div className="hosp-row__bar" style={{ alignSelf: "center" }}>
              <div className="hosp-row__bar-fill" style={{ width: `${(p.internacoes / maxInter) * 100}%`, background: p.opportunity === "alta" ? "var(--accent)" : p.opportunity === "media" ? "var(--warn)" : "var(--ink-4)" }} />
            </div>
          </div>
        ))}
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card__head"><div><div className="card__title">Hospitais com maior volume cirúrgico IEP</div><div className="card__sub">Foco para parcerias de protocolo pós-operatório.</div></div></div>
        <div className="table-head" style={{ gridTemplateColumns: "28px 1.7fr 70px 110px 90px 80px" }}>
          <span>#</span><span>Hospital</span><span>UF</span><span>Internações</span><span>Mortalidade</span><span>Volume</span>
        </div>
        {hospInternacoes.map((h, i) => {
          const max = hospInternacoes[0].internacoes;
          return (
            <div key={h.cnes} className="hosp-row" style={{ gridTemplateColumns: "28px 1.7fr 70px 110px 90px 80px" }}>
              <span className="hosp-row__rank">{String(i + 1).padStart(2, "0")}</span>
              <div><div className="hosp-row__name">{h.name}</div><div className="hosp-row__meta">{h.city} · CNES {h.cnes}</div></div>
              <span className="hosp-row__uf">{h.uf}</span>
              <span className="num" style={{ fontWeight: 500 }}>{_fmt(h.internacoes)}</span>
              <span className="num" style={{ color: h.mort > 0.01 ? "var(--warn)" : "var(--ink-3)", fontSize: 12 }}>{_pct(h.mort, 2)}</span>
              <div className="hosp-row__bar" style={{ alignSelf: "center" }}>
                <div className="hosp-row__bar-fill" style={{ width: `${(h.internacoes / max) * 100}%` }} />
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

// ═══ Charts auxiliares ════════════════════════════════════════
function ExamesTrendChart({ data, height = 200 }) {
  const ref = React.useRef(null);
  const [w, setW] = useStM(400);
  React.useEffect(() => {
    const obs = new ResizeObserver(([e]) => setW(e.contentRect.width));
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  const pad = { l: 38, r: 12, t: 12, b: 26 };
  const innerW = Math.max(80, w - pad.l - pad.r);
  const innerH = height - pad.t - pad.b;
  const max = Math.max(...data.map(d => d.FC + d.IEP)) * 1.1;
  const xStep = innerW / (data.length - 1);
  const y = v => pad.t + innerH - (v / max) * innerH;

  const fcPath = data.map((d, i) => `${i ? "L" : "M"}${pad.l + i * xStep},${y(d.FC)}`).join(" ");
  const totPath = data.map((d, i) => `${i ? "L" : "M"}${pad.l + i * xStep},${y(d.FC + d.IEP)}`).join(" ");
  const fcArea = fcPath + ` L${pad.l + (data.length - 1) * xStep},${pad.t + innerH} L${pad.l},${pad.t + innerH} Z`;

  return (
    <div ref={ref} className="chart-wrap">
      <svg width={w} height={height}>
        {[0, 0.25, 0.5, 0.75, 1].map((p, i) => (
          <g key={i}>
            <line x1={pad.l} x2={w - pad.r} y1={y(max * p)} y2={y(max * p)} className="chart-grid-line" />
            <text x={pad.l - 8} y={y(max * p) + 4} textAnchor="end" className="chart-axis-label">
              {(max * p) >= 1000 ? ((max * p) / 1000).toFixed(0) + "k" : Math.round(max * p)}
            </text>
          </g>
        ))}
        <path d={`${totPath} L${pad.l + (data.length - 1) * xStep},${pad.t + innerH} L${pad.l},${pad.t + innerH} Z`} fill="oklch(60% 0.10 35)" opacity="0.18" />
        <path d={fcArea} fill="oklch(60% 0.10 200)" opacity="0.30" />
        <path d={totPath} stroke="oklch(55% 0.10 35)" strokeWidth="2" fill="none" strokeLinejoin="round" strokeLinecap="round" />
        <path d={fcPath} stroke="oklch(55% 0.10 200)" strokeWidth="2" fill="none" strokeLinejoin="round" strokeLinecap="round" />
        {data.map((d, i) => i % 2 === 0 || i === data.length - 1 ? (
          <text key={d.c} x={pad.l + i * xStep} y={height - 8} textAnchor="middle" className="chart-axis-label">
            {fmtMonth(d.c, true)}
          </text>
        ) : null)}
      </svg>
      <div style={{ display: "flex", gap: 16, fontSize: 12, color: "var(--ink-3)", marginTop: 6 }}>
        <span><span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: "oklch(55% 0.10 200)", marginRight: 6 }} />FC</span>
        <span><span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: "oklch(55% 0.10 35)", marginRight: 6 }} />IEP</span>
      </div>
    </div>
  );
}

function InternacoesChart({ data, height = 220 }) {
  const ref = React.useRef(null);
  const [w, setW] = useStM(800);
  const [hover, setHover] = useStM(null);
  React.useEffect(() => {
    const obs = new ResizeObserver(([e]) => setW(e.contentRect.width));
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  const pad = { l: 44, r: 50, t: 16, b: 30 };
  const innerW = Math.max(100, w - pad.l - pad.r);
  const innerH = height - pad.t - pad.b;
  const maxI = Math.max(1, ...data.map(d => d.internacoes)) * 1.1;
  const maxM = Math.max(0.001, ...data.map(d => d.mort)) * 1.2;
  const barW = innerW / data.length * 0.62;
  const yI = v => pad.t + innerH - (v / maxI) * innerH;
  const yM = v => pad.t + innerH - (v / maxM) * innerH;
  const xCenter = i => pad.l + (i + 0.5) * (innerW / data.length);
  const mortPath = data.map((d, i) => `${i ? "L" : "M"}${xCenter(i)},${yM(d.mort)}`).join(" ");

  const handleMouseMove = e => {
    const rect = ref.current?.getBoundingClientRect();
    if (!rect) return;
    const mx = e.clientX - rect.left - pad.l;
    const idx = Math.floor(mx / (innerW / data.length));
    setHover(idx >= 0 && idx < data.length ? idx : null);
  };

  const hd = hover !== null ? data[hover] : null;
  const tooltipX = hover !== null ? Math.min(xCenter(hover) + 12, w - 155) : 0;

  return (
    <div ref={ref} className="chart-wrap" style={{ position: "relative" }}>
      <svg width={w} height={height} onMouseMove={handleMouseMove} onMouseLeave={() => setHover(null)} style={{ cursor: "default" }}>
        {[0, 0.25, 0.5, 0.75, 1].map((p, i) => (
          <g key={i}>
            <line x1={pad.l} x2={w - pad.r} y1={yI(maxI * p)} y2={yI(maxI * p)} className="chart-grid-line" />
            <text x={pad.l - 8} y={yI(maxI * p) + 4} textAnchor="end" className="chart-axis-label">
              {Math.round(maxI * p / 1000) > 0 ? (maxI * p / 1000).toFixed(1).replace(".", ",") + "k" : Math.round(maxI * p)}
            </text>
            <text x={w - pad.r + 8} y={yM(maxM * p) + 4} textAnchor="start" className="chart-axis-label" style={{ fill: "var(--danger)" }}>
              {(maxM * p * 100).toFixed(1).replace(".", ",")}%
            </text>
          </g>
        ))}
        {data.map((d, i) => (
          <rect key={d.c} x={xCenter(i) - barW / 2} y={yI(d.internacoes)} width={barW}
            height={innerH - (yI(d.internacoes) - pad.t)} fill="var(--accent)"
            opacity={hover === null || hover === i ? 0.85 : 0.45} rx="2" />
        ))}
        <path d={mortPath} stroke="var(--danger)" strokeWidth="1.8" fill="none" strokeLinejoin="round" strokeLinecap="round" />
        {data.map((d, i) => (
          <circle key={"m" + i} cx={xCenter(i)} cy={yM(d.mort)}
            r={hover === i ? 4.5 : 2.5} fill="var(--danger)"
            stroke={hover === i ? "var(--surface-0)" : "none"} strokeWidth="1.5" />
        ))}
        {data.map((d, i) => i % 2 === 0 || i === data.length - 1 ? (
          <text key={d.c} x={xCenter(i)} y={height - 8} textAnchor="middle" className="chart-axis-label">{fmtMonth(d.c, true)}</text>
        ) : null)}
      </svg>
      {hd && (
        <div style={{
          position: "absolute", top: pad.t + 4, left: tooltipX,
          background: "var(--surface-1)", border: "1px solid var(--border)",
          borderRadius: 8, padding: "8px 12px", fontSize: 12, lineHeight: 1.8,
          pointerEvents: "none", boxShadow: "0 2px 8px rgba(0,0,0,.12)", minWidth: 148,
        }}>
          <div style={{ fontWeight: 600, marginBottom: 2, color: "var(--ink-1)" }}>{fmtMonth(hd.c)}</div>
          <div style={{ color: "var(--accent-ink)" }}>Internações: <strong>{_fmt(hd.internacoes)}</strong></div>
          <div style={{ color: "var(--ink-2)" }}>Óbitos: <strong>{_fmt(hd.obitos ?? 0)}</strong></div>
          <div style={{ color: "var(--danger)" }}>Mortalidade: <strong>{_pct(hd.mort, 2)}</strong></div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { HospitaisView, ExamesView, InternacoesView });
