/* ============================================================
   DASHBOARD VIEW — portfolio intelligence
   ============================================================ */

const { useState, useEffect, useRef, useMemo } = React;

/* ---- metric card ---- */
function MetricCard({ label, value, unit, sub, accent }) {
  return (
    <div className="metric" style={accent ? { borderLeft: "2px solid " + accent } : null}>
      <div className="m-label">{label}</div>
      <div className="m-value tnum">{value}{unit && <small> {unit}</small>}</div>
      <div className="m-delta">{sub}</div>
    </div>
  );
}

/* ---- mini sparkline for metric ---- */
function Spark({ data, color, w = 64, h = 26 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((d, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((d - min) / (max - min || 1)) * h;
    return x.toFixed(1) + "," + y.toFixed(1);
  }).join(" ");
  return (
    <svg className="m-spark" width={w} height={h} style={{ overflow: "visible" }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" opacity="0.85" />
    </svg>
  );
}

/* ---- sinistralidade line chart ---- */
function SinistChart() {
  const { anos, series } = SKY.sinistralidade;
  const [hover, setHover] = useState(null);
  const W = 880, H = 300, PADL = 38, PADR = 16, PADT = 16, PADB = 30;
  const plotW = W - PADL - PADR, plotH = H - PADT - PADB;
  const maxV = 80, minV = 0;
  const x = (i) => PADL + (i / (anos.length - 1)) * plotW;
  const y = (v) => PADT + plotH - ((v - minV) / (maxV - minV)) * plotH;
  const yTicks = [0, 20, 40, 60, 80];

  function onMove(e) {
    const rect = e.currentTarget.getBoundingClientRect();
    const px = ((e.clientX - rect.left) / rect.width) * W;
    let idx = Math.round(((px - PADL) / plotW) * (anos.length - 1));
    idx = Math.max(0, Math.min(anos.length - 1, idx));
    setHover(idx);
  }

  return (
    <div className="chart-wrap" style={{ position: "relative" }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }}
        onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
        {yTicks.map((t) => (
          <g key={t}>
            <line x1={PADL} x2={W - PADR} y1={y(t)} y2={y(t)} stroke="var(--rule-soft)" strokeWidth="1" />
            <text x={PADL - 8} y={y(t) + 3} textAnchor="end" className="chart-axis">{t}</text>
          </g>
        ))}
        {anos.map((a, i) => (
          <text key={a} x={x(i)} y={H - 10} textAnchor="middle" className="chart-axis">{`'${String(a).slice(2)}`}</text>
        ))}
        {hover !== null && <line x1={x(hover)} x2={x(hover)} y1={PADT} y2={PADT + plotH} stroke="var(--sv-ink-500)" strokeWidth="1" strokeDasharray="3 3" />}
        {series.map((s) => {
          const path = s.data.map((v, i) => (i === 0 ? "M" : "L") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
          return <path key={s.key} d={path} fill="none" stroke={s.color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />;
        })}
        {hover !== null && series.map((s) => (
          <circle key={s.key} cx={x(hover)} cy={y(s.data[hover])} r="3.5" fill="var(--bg)" stroke={s.color} strokeWidth="2" />
        ))}
      </svg>
      <div className="chart-legend">
        {series.map((s) => (
          <span className="cl-item" key={s.key}><i style={{ background: s.color }} />{s.key}</span>
        ))}
      </div>
      {hover !== null && (
        <div className="chart-tip" style={{ left: `calc(${(x(hover) / W) * 100}% )` }}>
          <div className="ct-year mono">{anos[hover]} · sinistralidade %</div>
          {series.slice().sort((a, b) => b.data[hover] - a.data[hover]).map((s) => (
            <div className="ct-row" key={s.key}><i style={{ background: s.color }} /><span>{s.key}</span><b className="mono">{s.data[hover]}%</b></div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- exposure simulator ---- */
function ExposureSim({ onAddProtocol }) {
  const curve = SKY.exposureCurve;
  const [limit, setLimit] = useState(20);
  const point = useMemo(() => {
    // interpolate reducao for current limit
    const sorted = [...curve].sort((a, b) => a.limit - b.limit);
    if (limit <= sorted[0].limit) return sorted[0].reducao;
    if (limit >= sorted[sorted.length - 1].limit) return sorted[sorted.length - 1].reducao;
    for (let i = 0; i < sorted.length - 1; i++) {
      if (limit >= sorted[i].limit && limit <= sorted[i + 1].limit) {
        const t = (limit - sorted[i].limit) / (sorted[i + 1].limit - sorted[i].limit);
        return Math.round(sorted[i].reducao + t * (sorted[i + 1].reducao - sorted[i].reducao));
      }
    }
    return -18;
  }, [limit]);

  return (
    <div className="exposure">
      <div className="exp-readout">
        <div className="exp-block">
          <span className="eyebrow">Limite em zona vermelha</span>
          <div className="exp-num tnum">{limit}<small>%</small></div>
        </div>
        <Icon name="arrowR" size={20} color="var(--fg-mute)" />
        <div className="exp-block">
          <span className="eyebrow">Sinistralidade estimada</span>
          <div className="exp-num tnum" style={{ color: "var(--risk-low)" }}>{point}<small>%</small></div>
        </div>
      </div>
      <input type="range" min="5" max="30" step="1" value={limit} className="exp-slider"
        onChange={(e) => setLimit(+e.target.value)}
        style={{ "--pct": ((limit - 5) / 25) * 100 + "%" }} />
      <div className="exp-scale mono"><span>5%</span><span>limite atual da carteira: 23,4%</span><span>30%</span></div>
      <div className="exp-foot">
        <p>Simulação retroativa sobre <b>127.267 glebas</b> · janela 5s (2020–2025). O cenário-base recomendado é <b className="coral">20%</b>, reduzindo a sinistralidade histórica em <b>−18%</b>.</p>
        <button className="btn btn-cyan" onClick={() => onAddProtocol && onAddProtocol("protocol")}>
          <Icon name="file" size={13} /> Adicionar ao protocolo
        </button>
      </div>
    </div>
  );
}

/* ---- dashboard ---- */
function DashboardView({ chat, onAction }) {
  const m = SKY.metrics;
  return (
    <div className="view-pad">
      <div className="view-head row jcsb aic wrap gap16">
        <div>
          <span className="eyebrow">// Portfólio · Resseguro Agrícola</span>
          <h2 style={{ marginTop: 6 }}>Visão de portfólio</h2>
          <p>Inteligência sistêmica sobre o recorte Sul. Onde o resultado deteriora, onde está protegido, e onde agir.</p>
        </div>
        <button className="btn btn-cyan" onClick={() => chat.askPrompt("deteriorando")}>
          <Icon name="sparkles" size={13} /> Resumir com IA
        </button>
      </div>

      {/* resilience hero */}
      <div className="res-hero">
        <Panel brackets accent bodyPad={true} style={{ display:"flex" }}>
          <div className="res-gauge-card" style={{ width:"100%" }}>
            <ResilienceGauge value={72} label="// ÍNDICE DE RESILIÊNCIA DO PORTFÓLIO" sublabel="Rating multicritério proprietário" />
          </div>
        </Panel>
        <div className="res-right">
          <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 ativo em Passo Fundo exige investigação antes de subscrever." />
          <Panel title="Produtos compatíveis · synergy match" bodyPad={false}
            right={<span className="mono" style={{ fontSize: 9.5, color: "var(--fg-mute)", letterSpacing: ".1em" }}>SCORE 72 · IRB</span>}>
            <SynergyFeed portfolioScore={72} />
          </Panel>
        </div>
      </div>

      {/* metric row */}
      <div className="metric-row">
        <MetricCard label="Glebas no portfólio" value={m.propriedades.value.toLocaleString("pt-BR")}
          accent="var(--sv-cyan)"
          sub={<span className="mono" style={{color:"var(--fg-mute)"}}>soja + milho · 2020–2025</span>} />
        <MetricCard label="Zona crítica · manchas" value={m.zonaCritica.value} unit="%"
          accent="var(--risk-critical)"
          sub={<span className="warnc"><Icon name="alert" size={13} /> acima do limite de {m.zonaCritica.limite}%</span>} />
        <MetricCard label="Zona segura · top leads" value={m.zonaSegura.value} unit="%"
          accent="var(--risk-low)"
          sub={<span className="warnc"><Icon name="trendDown" size={13} /> meta: {m.zonaSegura.meta}% (abaixo)</span>} />
        <MetricCard label="Score médio do portfólio" value={m.scoreMedio.value} unit="/ 100"
          accent="var(--sv-coral)"
          sub={<span className={m.scoreMedio.deltaJan < 0 ? "warnc" : "up"}><Icon name={m.scoreMedio.deltaJan < 0 ? "trendDown" : "trendUp"} size={13} /> {m.scoreMedio.deltaJan > 0 ? "+" : ""}{m.scoreMedio.deltaJan} pts vs. jan</span>} />
      </div>

      <div className="dash-grid">
        {/* regional table */}
        <Panel title="Breakdown regional · Triângulo das Bermudas" accent bodyPad={false}
          right={<span className="mono" style={{ fontSize: 9.5, color: "var(--fg-mute)", letterSpacing: ".1em" }}>SICOR/PROAGRO · 10A</span>}>
          <div className="tbl-scroll">
          <table className="tbl">
            <thead>
              <tr><th>Região</th><th>Score</th><th>Tendência 5s</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.label5s} /></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>
        </Panel>

        {/* sinistralidade chart */}
        <Panel title="Sinistralidade histórica · 10 anos" bodyPad={true}
          right={<span className="mono" style={{ fontSize: 9.5, color: "var(--fg-mute)", letterSpacing: ".1em" }}>% · 4 REGIÕES</span>}>
          <SinistChart />
        </Panel>
      </div>

      {/* exposure simulator */}
      <Panel title="Simulador de exposição · limite em zona vermelha" brackets accent bodyPad={true}
        right={<span className="mono" style={{ fontSize: 9.5, color: "var(--sv-cyan)", letterSpacing: ".1em" }}>PORTFOLIO AGENT</span>}>
        <ExposureSim onAddProtocol={onAction} />
      </Panel>
    </div>
  );
}

Object.assign(window, { DashboardView, MetricCard, SinistChart, ExposureSim, Spark });

/* ============================================================
   MVP-inspired components (Skyvidya identity)
   ============================================================ */

/* sub-index data (tier cards) */
const SUB_INDICES = [
  { tier:"01", name:"Performance",      val:78, src:"SICOR · 5s",     accent:"var(--sv-cyan)" },
  { tier:"02", name:"Climático",        val:64, src:"NDVI · NASA SMAP", accent:"var(--sv-warn)" },
  { tier:"03", name:"ESG / Compliance", val:81, src:"BACEN · CAR",      accent:"var(--risk-low)" },
];

function TierCard({ d }) {
  const [w, setW] = useState(0);
  useEffect(() => { const t = setTimeout(() => setW(d.val), 60); return () => clearTimeout(t); }, [d.val]);
  return (
    <div className="tier-card" style={{ "--tc-accent": d.accent }}>
      <div className="tc-top"><span className="tc-tier">TIER {d.tier}</span><span className="tc-src">{d.src}</span></div>
      <div className="tc-name">{d.name}</div>
      <div className="tc-rating"><span className="tc-val">{d.val}</span><span className="tc-rlabel">rating</span></div>
      <div className="tc-bar"><i style={{ width: w + "%" }} /></div>
    </div>
  );
}

function NeuralOutput({ text }) {
  return (
    <div className="neural">
      <span className="neural-ico"><Icon name="cpu" size={15} color="var(--sv-cyan)" /></span>
      <div className="neural-body">
        <div className="neural-head"><span className="nh-dot" /> Motor neural · saída</div>
        <div className="neural-txt">"{text}"</div>
      </div>
    </div>
  );
}

/* synergy match feed — credit/insurance products matched to portfolio score */
const SYNERGY = [
  { org:"Banco do Brasil",  prod:<>Custeio Pronamp · <b>8% a.a.</b></>,            tier:1, min:65 },
  { org:"BNDES",            prod:<>Crédito ABC+ Regenerativo · <b>desconto 15%</b></>, tier:1, min:70 },
  { org:"IRB Re",           prod:<>Resseguro Safra Premium · <b>franquia 20%</b></>, tier:2, min:75 },
  { org:"Proagro Mais",     prod:<>Cobertura ampliada · <b>gatilho 40%</b></>,      tier:3, min:60 },
];

function MiniRing({ pct, color }) {
  const R = 13, C = 2 * Math.PI * R;
  return (
    <svg width="34" height="34" viewBox="0 0 34 34">
      <circle cx="17" cy="17" r={R} fill="none" stroke="var(--sv-ink-600)" strokeWidth="3" />
      <circle cx="17" cy="17" r={R} fill="none" stroke={color} strokeWidth="3" strokeLinecap="round"
        strokeDasharray={`${(pct/100*C).toFixed(1)} ${C}`} transform="rotate(-90 17 17)" />
      <text x="17" y="18" textAnchor="middle" dominantBaseline="middle" className="mono" style={{ fontSize: 9, fill: "var(--fg)" }}>{pct}</text>
    </svg>
  );
}

function SynergyFeed({ portfolioScore = 72 }) {
  return (
    <div className="synergy-list">
      {SYNERGY.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>
  );
}

Object.assign(window, { TierCard, NeuralOutput, SynergyFeed, SUB_INDICES });

