/* ============================================================
   SKYVIDYA v6 — ENTIDADE 360 · Composição do SkyVidya Score
   Layout: COMPOSIÇÃO (wheel) + SKYVIDYA SCORE + INSIGHTS
   ============================================================ */
const { useState, useMemo } = React;

/* ---- legend categories per sub-score (mockup uses 4) ---- */
const LEGEND_CAT = {
  cadastral: "compliance", esg: "compliance",
  agro: "agro", desmate: "agro", prod: "agro",
  green: "market",
  credito: "financeiro", imob: "financeiro",
  saude: "compliance", utilities: "agro",
};
const LEGEND_DEFS = [
  { id: "compliance", label: "Compliance", color: "var(--sv-coral)" },
  { id: "agro",       label: "Agro",       color: "var(--risk-low)" },
  { id: "market",   label: "Market",   color: "var(--sv-cyan)" },
  { id: "financeiro", label: "Financeiro", color: "var(--sv-warn)" },
];
const LEGEND_COLOR = Object.fromEntries(LEGEND_DEFS.map(l => [l.id, l.color]));

/* ---- chip 5W1H (preserved from previous version) ---- */
function Facet({ icon, label, children }) {
  return (
    <div className="facet">
      <span className="facet-ic"><Icon name={icon} size={13} /></span>
      <div className="facet-t"><span className="mono">{label}</span><b>{children}</b></div>
    </div>
  );
}

/* ---- evolution sparkline (12-month line for the main score) ---- */
function EvolutionChart({ data, w = 420, h = 130 }) {
  const max = 100, min = 0;
  const PAD = { l: 30, r: 14, t: 14, b: 22 };
  const W = w - PAD.l - PAD.r, H = h - PAD.t - PAD.b;
  const x = (i) => PAD.l + (i / (data.length - 1)) * W;
  const y = (v) => PAD.t + H - ((v - min) / (max - min)) * H;
  const path = data.map((d, i) => (i === 0 ? "M" : "L") + x(i).toFixed(1) + " " + y(d.v).toFixed(1)).join(" ");
  const area = path + " L" + x(data.length - 1).toFixed(1) + " " + (PAD.t + H) + " L" + x(0).toFixed(1) + " " + (PAD.t + H) + " Z";
  const last = data[data.length - 1];
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} className="evo-svg" preserveAspectRatio="none">
      <defs>
        <linearGradient id="evoG" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--sv-cyan)" stopOpacity="0.25" />
          <stop offset="100%" stopColor="var(--sv-cyan)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 25, 50, 75, 100].map(g => (
        <g key={g}>
          <line x1={PAD.l} x2={w - PAD.r} y1={y(g)} y2={y(g)} stroke="var(--rule-soft)" strokeWidth="0.6" />
          <text x={PAD.l - 6} y={y(g) + 3} textAnchor="end" className="evo-axis">{g}</text>
        </g>
      ))}
      <path d={area} fill="url(#evoG)" />
      <path d={path} fill="none" stroke="var(--sv-cyan)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      {data.map((d, i) => <circle key={i} cx={x(i)} cy={y(d.v)} r="2.6" fill="var(--sv-cyan)" stroke="var(--bg-elev)" strokeWidth="1" />)}
      <g transform={`translate(${x(data.length - 1) - 32} ${y(last.v) - 22})`}>
        <rect x="0" y="0" width="32" height="16" rx="3" fill="var(--sv-cyan)" />
        <text x="16" y="11" textAnchor="middle" className="evo-tag">{last.v}</text>
      </g>
      {data.map((d, i) => <text key={"l"+i} x={x(i)} y={h - 5} textAnchor="middle" className="evo-axis">{d.m}</text>)}
    </svg>
  );
}

/* ---- COMPOSIÇÃO DO FATO · sub-score wheel ---- */
function ScoreWheel({ entity, composite, onSelect, selected, onSeeDetails }) {
  const ids = entity.apply.slice(0, 7);                  // mockup max 7 around the ring
  const N = ids.length;
  // SVG layout (square viewbox)
  const VB = 380, cx = VB / 2, cy = VB / 2;
  const Rnode = 142, Rdial = 110;
  const ang = (i) => (-90 + (i * 360) / N) * Math.PI / 180;
  const collapse = SKY.collapseOf(composite);
  return (
    <div className="v2-card sw-card brackets">
      <div className="sw-head">
        <div>
          <span className="mono sw-eyebrow">COMPOSIÇÃO DO FATO</span>
          <h3 className="sw-title">{N} sub-scores</h3>
          <p className="sw-sub">Cada dimensão representa um fator de resiliência do asset.</p>
        </div>
        <button className="sw-detail mono" onClick={onSeeDetails}>VER DETALHES <Icon name="scan" size={11} /></button>
      </div>
      <div className="sw-stage">
        <svg viewBox={`0 0 ${VB} ${VB}`} width="100%" className="sw-svg" preserveAspectRatio="xMidYMid meet">
          <defs>
            <radialGradient id="swGlobe" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%"  stopColor="rgba(20,30,60,0.65)" />
              <stop offset="60%" stopColor="rgba(10,16,30,0.85)" />
              <stop offset="100%" stopColor="rgba(6,7,10,0.95)" />
            </radialGradient>
            <linearGradient id="swRing" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%"  stopColor="var(--sv-coral)" />
              <stop offset="50%" stopColor="var(--sv-cyan)" />
              <stop offset="100%" stopColor="var(--risk-low)" />
            </linearGradient>
            <filter id="swGlow" x="-30%" y="-30%" width="160%" height="160%">
              <feGaussianBlur stdDeviation="4" />
            </filter>
          </defs>
          {/* dark globe in the middle */}
          <circle cx={cx} cy={cy} r={Rdial} fill="url(#swGlobe)" stroke="rgba(255,255,255,0.06)" />
          {/* faint meridians */}
          {[0, 30, 60, 90].map(a => (
            <ellipse key={a} cx={cx} cy={cy} rx={Rdial} ry={Rdial * Math.cos(a * Math.PI / 180)} fill="none" stroke="rgba(78,210,210,0.10)" />
          ))}
          {/* big rainbow ring connecting all nodes */}
          <circle cx={cx} cy={cy} r={Rnode} fill="none" stroke="url(#swRing)" strokeWidth="2.5" opacity="0.9" filter="url(#swGlow)" />
          <circle cx={cx} cy={cy} r={Rnode} fill="none" stroke="url(#swRing)" strokeWidth="1" opacity="0.55" />
          {/* connection lines from each node to center */}
          {ids.map((id, i) => {
            const x = cx + Rnode * Math.cos(ang(i));
            const y = cy + Rnode * Math.sin(ang(i));
            return <line key={"L" + id} x1={cx} y1={cy} x2={x} y2={y} stroke="rgba(255,255,255,0.06)" strokeWidth="1" />;
          })}
          {/* center text */}
          <text x={cx} y={cy - 18} textAnchor="middle" className="sw-center-lab">SKYVIDYA SCORE</text>
          <text x={cx} y={cy + 24} textAnchor="middle" className="sw-center-num" style={{ fill: collapse.color }}>{composite}</text>
          <g transform={`translate(${cx} ${cy + 56})`}>
            <rect x="-58" y="-12" width="116" height="22" rx="11" fill="none" stroke={collapse.color} strokeWidth="1" />
            <text textAnchor="middle" y="4" className="sw-center-tag" style={{ fill: collapse.color }}>{collapse.label === "Baixo" ? "ALTA RESILIÊNCIA" : collapse.label === "Médio" ? "RESILIÊNCIA MÉDIA" : "BAIXA RESILIÊNCIA"}</text>
          </g>
        </svg>
        {/* HTML overlay nodes (interactive, easier styling) */}
        <div className="sw-nodes">
          {ids.map((id, i) => {
            const d = SKY.SCORE_BY_ID[id], v = entity.s[id];
            const cat = LEGEND_CAT[id] || "compliance";
            const cls = "sw-cat-" + cat;
            const x = 50 + 50 * Math.cos(ang(i));         // % of stage width
            const y = 50 + 50 * Math.sin(ang(i));
            const isSel = selected === id;
            return (
              <button key={id} className={"sw-node " + cls + (isSel ? " on" : "")}
                style={{ left: x + "%", top: y + "%" }}
                onClick={() => onSelect(id)} title={d.label}>
                <span className="sw-hex"><Icon name={d.icon} size={14} color="currentColor" /></span>
                <span className="sw-lbl">{d.label}</span>
                <span className="sw-val mono">{v}</span>
              </button>
            );
          })}
        </div>
      </div>
      <div className="sw-legend">
        {LEGEND_DEFS.map(l => (
          <span key={l.id} className="sw-leg-item"><i style={{ background: l.color }} />{l.label}</span>
        ))}
      </div>
    </div>
  );
}

/* ---- Insights cards (right column) ---- */
function InsightsPanel({ entity, composite, onAsk }) {
  const s = entity.s;
  const insights = [
    s.agro >= 75 && s.desmate >= 80 && {
      id: "amb", icon: "check", tone: "good", title: "ALTA RESILIÊNCIA AMBIENTAL",
      body: `Destaque para Agroclimático (${s.agro || "—"}) e Desmatamento (${s.desmate || "—"}), indicando forte conformidade ambiental.`,
    },
    s.prod >= 75 && {
      id: "prod", icon: "trendUp", tone: "cyan", title: "DESEMPENHO PRODUTIVO FORTE",
      body: `Produtividade (${s.prod}) acima da média do ecossistema e com tendência de melhoria.`,
    },
    s.green && s.green < 85 && {
      id: "green", icon: "gem", tone: "market", title: "OPORTUNIDADE EM GREEN SOLUTIONS",
      body: `Score ${s.green} indica espaço para ampliar soluções de baixo carbono e captura de valor ESG.`,
    },
    s.credito >= 70 && {
      id: "cred", icon: "dashboard", tone: "financeiro", title: "CRÉDITO SAUDÁVEL",
      body: `Score de Crédito (${s.credito}) indica boa capacidade financeira e baixo risco de inadimplência.`,
    },
  ].filter(Boolean).slice(0, 4);

  const recs = [
    s.green && s.green < 85 ? "Expandir green solutions: adotar práticas de intensificação sustentável e projetos de carbono para elevar o score para >85." : null,
    s.agro >= 80 ? "Monetizar potencial agtech: alta sinergia com soluções de manejo inteligente, irrigação e bioinsumos." : null,
    s.credito >= 70 ? "Acessar novas linhas de crédito: ativo elegível para linhas verdes e programas de incentivo sustentável." : null,
    s.cadastral < 70 ? "Higienização cadastral: completar CAR e cruzar com SICOR para subir o score em até 12 pts." : null,
  ].filter(Boolean).slice(0, 3);

  return (
    <div className="v2-card insight-card">
      <div className="ic-head"><Icon name="sparkles" size={13} color="var(--sv-cyan)" /><span className="mono">INSIGHTS PRINCIPAIS</span></div>
      <div className="ic-list">
        {insights.map((it) => (
          <div key={it.id} className={"ic-item ic-tone-" + it.tone}>
            <span className="ic-ic"><Icon name={it.icon} size={14} color="currentColor" /></span>
            <div className="ic-body">
              <span className="ic-t mono">{it.title}</span>
              <p>{it.body}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="ic-divider" />

      <div className="ic-head"><Icon name="target" size={13} color="var(--sv-cyan)" /><span className="mono">RECOMENDAÇÕES INTELIGENTES</span></div>
      <div className="rec-list">
        {recs.map((r, i) => (
          <button key={i} className="rec-item" onClick={() => onAsk(r)}>
            <span className="rec-n mono">{(i + 1).toString().padStart(2, "0")}</span>
            <span className="rec-t">{r}</span>
            <Icon name="arrowR" size={13} className="rec-go" />
          </button>
        ))}
      </div>

      <button className="ic-cta" onClick={() => onAsk("Quais oportunidades a entidade " + entity.name + " tem no ecossistema?")}>
        Ver oportunidades no ecossistema <Icon name="arrowR" size={13} />
      </button>
    </div>
  );
}

/* ---- main view ---- */
function Entity360View({ chat, access }) {
  const [eid, setEid] = useState(SKY.ENTITIES[0].id);
  const entity = useMemo(() => SKY.ENTITIES.find((e) => e.id === eid), [eid]);
  const fato = useMemo(() => SKY.scoreComposite(entity), [entity]);
  const collapse = SKY.collapseOf(fato);
  const [sel, setSel] = useState(entity.apply[0]);
  const [drillOpen, setDrillOpen] = useState(false);
  useMemo(() => { if (!entity.apply.includes(sel)) setSel(entity.apply[0]); }, [entity]);
  const selDef = SKY.SCORE_BY_ID[sel];
  const series = useMemo(() => SKY.scoreSeries(entity, sel), [entity, sel]);
  const notApply = SKY.SCORE_DEFS.filter((d) => !entity.apply.includes(d.id)).slice(0, 4);

  // sub-stats below the gauge
  const subStats = [
    { lab: "Risco Geral", v: collapse.label.toUpperCase(), tone: collapse.id, icon: "check", note: "Exposição controlada e dentro dos limites." },
    { lab: "Resiliência", v: collapse.label === "Baixo" ? "ALTA" : collapse.label === "Médio" ? "MÉDIA" : "BAIXA", tone: collapse.id, icon: "activity", note: "Asset preparado para eventos adversos." },
    { lab: "Potencial Agtech", v: ((entity.s.agro || 0) + (entity.s.prod || 0)) / 2 >= 75 ? "ALTO" : "MÉDIO", tone: "market", icon: "sparkles", note: "Grande aderência a soluções do ecossistema." },
    { lab: "Sinergia",   v: Math.min(98, Math.round(fato * 1.05)).toString(), tone: "cyan", icon: "layers", note: "Alto potencial de geração de valor." },
  ];

  // 12-month evolution of the composite (deterministic)
  const evoMonths = ["JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ", "JAN", "FEV", "MAR", "ABR", "MAI"];
  const evo = useMemo(() => {
    const base = fato - 6;
    return evoMonths.map((m, i) => {
      const noise = (Math.sin(i * 1.4 + entity.id.length) + 1) * 4;
      const v = Math.max(20, Math.min(98, Math.round(base + (i / (evoMonths.length - 1)) * 8 + noise - 3)));
      return { m, v: i === evoMonths.length - 1 ? fato : v };
    });
  }, [fato, entity]);

  const now = new Date(2026, 4, 24, 10, 42);
  const stamp = `${String(now.getDate()).padStart(2,"0")}/${String(now.getMonth()+1).padStart(2,"0")}/${now.getFullYear()}  ${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`;

  return (
    <div className="v2-pad fade-up score360-v2" data-screen-label="Score 360 · Entidade">
      <ViewHead eyebrow="// FATO · star schema 5W1H" title="Score 360"
        sub="O SkyVidya Score como FATO: a composição dos sub-scores de uma entidade — pessoa, empresa, imóvel ou território — auditável até a fonte." />

      {/* entity selector (WHO) */}
      <div className="ent-pills">
        {SKY.ENTITIES.map((e) => (
          <button key={e.id} className={"ent-pill" + (e.id === eid ? " on" : "")} onClick={() => setEid(e.id)}>
            <span className="ent-who mono">{e.who}</span>
            <b>{e.name}</b>
            <span className="ent-meta mono">{e.whoLabel} · {e.where.cidade}/{e.where.uf}</span>
          </button>
        ))}
      </div>

      {/* MAIN 3-COL */}
      <div className="s360-main">
        <ScoreWheel entity={entity} composite={fato} selected={sel} onSelect={(id) => { setSel(id); setDrillOpen(true); }} onSeeDetails={() => setDrillOpen(true)} />

        {/* center column: gauge + substats + evolution */}
        <div className="s360-center">
          <div className="v2-card sc-gauge brackets">
            <div className="sc-head">
              <div>
                <span className="mono sc-eyebrow">SKYVIDYA SCORE</span>
                <h3 className="sc-title">Visão geral da resiliência do asset</h3>
              </div>
              <span className="sc-stamp mono"><span className="live-dot" /> ATUALIZADO EM<br />{stamp}</span>
            </div>
            <div className="sc-gauge-row">
              <ResilienceGauge value={fato} size={232} compact={false} showLabel={false} showDots={true} badge="" />
              <div className="sc-side">
                <span className="sc-side-l mono">de 100</span>
                <span className="sc-side-tag" style={{ color: collapse.color, borderColor: collapse.color }}>
                  {collapse.label === "Baixo" ? "ALTA RESILIÊNCIA" : collapse.label === "Médio" ? "RESILIÊNCIA MÉDIA" : "BAIXA RESILIÊNCIA"}
                </span>
                <span className="sc-delta up"><Icon name="trendUp" size={12} /> +6 pts <em>vs. avaliação anterior</em></span>
              </div>
            </div>

            <div className="sc-stats">
              {subStats.map((s, i) => (
                <div key={i} className={"sc-stat tone-" + s.tone}>
                  <span className="sc-st-ic"><Icon name={s.icon} size={13} color="currentColor" /></span>
                  <span className="sc-st-lab mono">{s.lab}</span>
                  <b className="sc-st-v">{s.v}</b>
                  <em>{s.note}</em>
                </div>
              ))}
            </div>
          </div>

          <div className="v2-card sc-evo">
            <div className="sc-evo-h">
              <span className="mono">EVOLUÇÃO DO SKYVIDYA SCORE</span>
              <select className="sc-range mono"><option>12 meses</option><option>24 meses</option><option>5 anos</option></select>
            </div>
            <EvolutionChart data={evo} />
          </div>
        </div>

        <InsightsPanel entity={entity} composite={fato} onAsk={(q) => chat.askFree(q)} />
      </div>

      {/* bottom strip: NÃO APLICÁVEL + Compliance/Market tagline + metodologia + atualização */}
      <div className="s360-strip">
        <div className="ss-na">
          <span className="mono ss-l">NÃO APLICÁVEL A ESTA ENTIDADE</span>
          <div className="ss-na-list">
            {notApply.length > 0
              ? notApply.map((d) => <span key={d.id} className="na-chip mono">{d.label}</span>)
              : <span className="mono soft" style={{ fontSize: 9 }}>—</span>}
          </div>
        </div>
        <div className="ss-tag">
          <Icon name="target" size={14} color="var(--sv-coral)" />
          <div><b>COMPLIANCE OR MARKET LEAD SCORE</b><em>Score composto que avalia riscos, conformidade, desempenho produtivo, sustentabilidade e capacidade financeira do asset.</em></div>
        </div>
        <div className="ss-meta">
          <Icon name="share" size={13} color="var(--sv-cyan)" />
          <div><b>Metodologia proprietária TerraVidya</b><em>+ de 200 variáveis analisadas com IA e dados públicos e privados.</em></div>
        </div>
        <div className="ss-meta">
          <Icon name="refresh" size={13} color="var(--sv-cyan)" />
          <div><b>Atualização contínua</b><em>Dados climáticos, fundiários e produtivos em tempo quase real.</em></div>
        </div>
      </div>

      <div className="terravidya-band">
        <span className="tvb-mark mono"><b>TERRA</b>VIDYA</span>
        <span className="tvb-tag">Inteligência para sinergias que regeneram o planeta.</span>
        <span className="tvb-ver mono">TERRAVIDYA 1.0 → 2.0 · DO SCORE DE SINERGIA AO ECOSSISTEMA</span>
      </div>

      {/* drill drawer */}
      {drillOpen && (
        <div className="cb-overlay" onClick={() => setDrillOpen(false)}>
          <div className="up-panel drill-panel fade-up" onClick={(e) => e.stopPropagation()}>
            <div className="ed-top">
              <div className="ed-l">
                <span className="ed-ic"><Icon name={selDef.icon} size={16} color="var(--sv-coral)" /></span>
                <div><b>Score {selDef.label}</b><span className="mono ed-vert">{selDef.vertical} · peso {selDef.weight.toFixed(1)}</span></div>
              </div>
              <div className="ed-gauge"><ResilienceGauge value={entity.s[sel]} size={130} compact showLabel={false} badge="" /></div>
              <button className="hp-close" onClick={() => setDrillOpen(false)}><Icon name="x" size={14} /></button>
            </div>
            <p className="ed-desc">{selDef.desc}</p>

            <div className="ed-body">
              <div className="ed-spark">
                <span className="mono ed-cap">SÉRIE · DECÊNIO {entity.when.decenio}</span>
                <Sparkline data={series} color={SKY.collapseOf(entity.s[sel]).color} />
              </div>
              <div className="ed-sources">
                <span className="mono ed-cap">WITH X ISSUE · CONSULTAS DE ORIGEM</span>
                <div className="src-list">
                  {selDef.sources.map(([q, org], i) => (
                    <div className="src-row" key={i}>
                      <span className="src-led" /><span className="src-q">{q}</span>
                      <span className="mono src-org">{org}</span>
                      <span className="mono src-date">ingest 2026-06-08</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="ed-actions">
              <span className="ed-contrib mono">CONTRIBUI {Math.round(selDef.weight / entity.apply.reduce((a, id) => a + SKY.SCORE_BY_ID[id].weight, 0) * 100)}% DO FATO</span>
              <button className="btn btn-cyan" onClick={() => chat.askFree("Explique o Score " + selDef.label + " da entidade " + entity.name + " e suas fontes")}>
                <Icon name="sparkles" size={13} /> Analisar com IA
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Sparkline({ data, color, w = 240, h = 60 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((d, i) => `${(i / (data.length - 1)) * w},${(h - 6) - ((d - min) / (max - min || 1)) * (h - 14) + 4}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} className="ed-spark-svg" preserveAspectRatio="none">
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      {data.map((d, i) => <circle key={i} cx={(i / (data.length - 1)) * w} cy={(h - 6) - ((d - min) / (max - min || 1)) * (h - 14) + 4} r="1.6" fill={color} />)}
    </svg>
  );
}

Object.assign(window, { Entity360View });
