/* ============================================================
   SKYVIDYA OBSERVATORY v2 — clean tab views
   Simulador (exposure) + Match (synergy) extracted to their
   own tabs; Carteira = a slim, persona-tuned panel.
   Reuses dashboard.jsx components.
   ============================================================ */
const { useState: useStateV2 } = React;

/* ---- shared view header ---- */
function ViewHead({ n, eyebrow, title, sub, right }) {
  return (
    <div className="v2-head">
      <div>
        <span className="eyebrow">{eyebrow}</span>
        <h2>{title}</h2>
        {sub && <p>{sub}</p>}
      </div>
      {right}
    </div>
  );
}

/* ============== SIMULADOR ============== */
function SimuladorView({ chat, onAction }) {
  return (
    <div className="v2-pad fade-up">
      <ViewHead
        eyebrow="// Simulador · limite em zona vermelha"
        title="Simulador de exposição"
        sub="Quanto da sinistralidade histórica cai ao limitar a exposição em zonas de alto risco. Retroativo sobre 10 anos de carteira."
        right={<span className="v2-agent mono">PORTFOLIO AGENT</span>}
      />
      <div className="v2-card brackets">
        <ExposureSim onAddProtocol={onAction} />
      </div>

      <div className="v2-grid-2" style={{ marginTop: 16 }}>
        <div className="v2-card">
          <div className="v2-card-h"><span className="ctitle">Sinistralidade histórica · 10a</span><span className="mono v2-meta">% · 4 REGIÕES</span></div>
          <div style={{ padding: 16 }}><SinistChart /></div>
        </div>
        <div className="v2-card">
          <div className="v2-card-h"><span className="ctitle">Curva de exposição</span><span className="mono v2-meta">LIMITE → REDUÇÃO</span></div>
          <div style={{ padding: 16 }}>
            <table className="tbl">
              <thead><tr><th>Limite zona vermelha</th><th>Redução sinistralidade</th><th>Custo de volume</th></tr></thead>
              <tbody>
                {[["30%","−9%","—"],["25%","−13%","−2%"],["20%","−18%","−6%"],["15%","−24%","−14%"],["10%","−31%","−26%"]].map((r,i)=>(
                  <tr key={i} className={r[0]==="20%"?"sel":""}>
                    <td className="num">{r[0]}</td>
                    <td className="num" style={{color:"var(--risk-low)"}}>{r[1]}</td>
                    <td className="num soft">{r[2]}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============== MATCH (synergy) ============== */
const MATCH_TABS = [
  { id: "credito", label: "Crédito" },
  { id: "seguro", label: "Seguro" },
  { id: "insumos", label: "Insumos" },
];
const MATCH_DATA = {
  credito: [
    { org: "Banco do Brasil", prod: "Custeio Pronamp · 8% a.a.", tier: 1, min: 65 },
    { org: "BNDES", prod: "Crédito ABC+ Regenerativo · desconto 15%", tier: 1, min: 70 },
    { org: "Sicredi", prod: "Capital de giro safra · 11% a.a.", tier: 2, min: 60 },
  ],
  seguro: [
    { org: "IRB Re", prod: "Resseguro Safra Premium · franquia 20%", tier: 2, min: 75 },
    { org: "Proagro Mais", prod: "Cobertura ampliada · gatilho 40%", tier: 3, min: 60 },
    { org: "Swiss Re", prod: "Paramétrico de seca · NDVI trigger", tier: 1, min: 78 },
  ],
  insumos: [
    { org: "Bayer", prod: "Pacote soja + financiamento safra", tier: 2, min: 62 },
    { org: "Yara", prod: "Fertilizante de precisão · mapa NDVI", tier: 1, min: 68 },
    { org: "John Deere", prod: "Plantio variável · leasing 24m", tier: 1, min: 72 },
  ],
};
function MatchView({ portfolioScore = 72 }) {
  const [tab, setTab] = useStateV2("credito");
  const rows = MATCH_DATA[tab];
  return (
    <div className="v2-pad fade-up">
      <ViewHead
        eyebrow="// Synergy match · produtos compatíveis"
        title="Match de produtos"
        sub="Crédito, seguro e insumos compatíveis com o score do recorte — calculado contra o limiar de elegibilidade de cada oferta."
        right={<span className="v2-agent mono">SCORE {portfolioScore} · MATCH ENGINE</span>}
      />
      <div className="seg" style={{ marginBottom: 16, width: "fit-content" }}>
        {MATCH_TABS.map((mt) => (
          <button key={mt.id} className={tab === mt.id ? "on" : ""} onClick={() => setTab(mt.id)}>{mt.label}</button>
        ))}
      </div>
      <div className="v2-card" style={{ overflow: "hidden" }}>
        <div className="synergy-list">
          {rows.map((s, i) => {
            const ok = portfolioScore >= s.min;
            const color = ok ? "var(--risk-low)" : "var(--fg-mute)";
            return (
              <div className="syn-item" key={i}>
                <div className="syn-main">
                  <div className="syn-org">{s.org}</div>
                  <div className="syn-prod">{s.prod}</div>
                </div>
                <div className="syn-meta">
                  <span className={"syn-tier t" + s.tier}>Tier {s.tier}</span>
                  <span className="syn-score">min_score {s.min}</span>
                </div>
                <div className="syn-match">
                  <MiniRing pct={portfolioScore} color={color} />
                  <span className={"syn-eligible " + (ok ? "ok" : "no")}>{ok ? "elegível" : "abaixo"}</span>
                  <Icon name="arrowR" size={14} className="syn-arrow" />
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ============== CARTEIRA (slim dashboard) ============== */
function CarteiraView({ chat, persona }) {
  const m = SKY.metrics;
  return (
    <div className="v2-pad fade-up">
      <ViewHead
        eyebrow={"// " + persona.role}
        title="Visão de carteira"
        sub={persona.tagline}
        right={<button className="btn btn-cyan" onClick={() => chat.askPrompt(persona.aiPrompt)}><Icon name="sparkles" size={13} /> Resumir com IA</button>}
      />

      <div className="v2-hero">
        <div className="v2-card v2-gauge brackets">
          <ResilienceGauge value={72} label="// ÍNDICE DE RESILIÊNCIA" sublabel="Rating multicritério" size={232} />
        </div>
        <div className="v2-hero-r">
          <div className="tier-cards">
            {SUB_INDICES.map((d) => <TierCard key={d.name} d={d} />)}
          </div>
          <NeuralOutput text="Portfólio operável — 61% em zona segura. Climático puxa o índice para baixo (estiagem NW RS). Cluster de anomalia em Passo Fundo exige investigação." />
        </div>
      </div>

      <div className="v2-card" style={{ overflow: "hidden", marginTop: 16 }}>
        <div className="v2-card-h"><span className="ctitle">Breakdown regional · Triângulo das Bermudas</span><span className="mono v2-meta">SICOR/PROAGRO · 10A</span></div>
        <div className="tbl-scroll">
          <table className="tbl">
            <thead><tr><th>Região</th><th>Score</th><th>Tendência 10a</th><th>A</th><th>B</th><th>C</th><th>Ação</th></tr></thead>
            <tbody>
              {SKY.regionalRisk.map((r) => (
                <tr key={r.regiao} onClick={() => chat.askPrompt(r.tendencia === "anomaly" ? "fraude" : "deteriorando")}>
                  <td><b style={{ color: "var(--fg)", fontWeight: 500 }}>{r.regiao}</b> <span className="mono soft" style={{ fontSize: 10 }}>{r.uf}</span></td>
                  <td><ScorePill score={r.score} width={40} /></td>
                  <td><TrendTag tendencia={r.tendencia} label={r.label10a} /></td>
                  <td className="num" style={{ color: "var(--risk-low)" }}>{r.tier_a}%</td>
                  <td className="num warnc">{r.tier_b}%</td>
                  <td className="num down">{r.tier_c}%</td>
                  <td><ActionTag acao={r.acao} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SimuladorView, MatchView, CarteiraView, ViewHead });
