/* global React */
/* ============================================================
   Forecast.jsx — Custo previsto vs. orçamento + Alertas de budget
   Projeção de gasto com LLM no ciclo, contra o teto orçamentário,
   com limites de alerta configuráveis por responsável.
   ============================================================ */
const IconF = window.Icon, BadgeF = window.Badge;
const useF = React.useState;

const FC_TODAY = 18;      // dia atual do ciclo
const FC_DAYS = 30;       // dias no ciclo
const FC_CYCLE = "Junho · 2026";

// série diária acumulada + projeção em run-rate
function fcSeries(projected, today, days, seed) {
  const rate = projected / days;
  let s = seed;
  const raw = [];
  for (let i = 0; i < today; i++) { s = (s * 9301 + 49297) % 233280; raw.push(0.55 + (s / 233280) * 0.9); }
  const rawSum = raw.reduce((a, b) => a + b, 0) || 1;
  const target = rate * today;
  let cum = 0;
  const actual = [{ d: 0, v: 0 }];
  for (let i = 0; i < today; i++) { cum += (raw[i] / rawSum) * target; actual.push({ d: i + 1, v: cum }); }
  const proj = [{ d: today, v: target }];
  for (let i = today + 1; i <= days; i++) proj.push({ d: i, v: rate * i });
  return { actual, proj, spent: target, projected: rate * days, rate };
}

function CostForecast({ agents, t, dark }) {
  const { fmtBRL, fmtNum } = window.AgentData;
  const [scope, setScope] = useF("all");
  const [threshold, setThreshold] = useF(90);
  const [chMail, setChMail] = useF(true);
  const [chWpp, setChWpp] = useF(false);

  // ---- entidades projetáveis ----
  const entities = React.useMemo(() => {
    const per = agents.map((a, i) => ({
      id: a.id, name: a.name, accent: a.accent, seed: 7 + i * 13,
      projected: a.metrics.costMonth + (a.infraCost || 0),
      budget: a.budgetMonth || 0,
    }));
    const all = {
      id: "all", name: "Toda a operação", accent: "var(--brand-teal-600)", seed: 3,
      projected: per.reduce((s, e) => s + e.projected, 0),
      budget: per.reduce((s, e) => s + e.budget, 0),
    };
    return { all, per };
  }, [agents]);

  const cur = scope === "all" ? entities.all : entities.per.find((e) => e.id === scope);
  const ser = fcSeries(cur.projected, FC_TODAY, FC_DAYS, cur.seed);
  const pctBudget = cur.budget ? (cur.projected / cur.budget) * 100 : 0;
  const over = pctBudget >= 100;
  const warn = pctBudget >= threshold;
  const line = over ? "#ef4444" : warn ? "#e0a800" : "var(--brand-teal-600)";
  const lineHex = over ? "#ef4444" : warn ? "#e0a800" : "#8fb3d4";
  // dia projetado de estouro do teto
  const breachDay = cur.budget && ser.rate ? cur.budget / ser.rate : Infinity;
  const breachInCycle = breachDay <= FC_DAYS;

  // ---- agentes que cruzam o limite de alerta ----
  const flagged = entities.per
    .map((e) => ({ ...e, pct: e.budget ? (e.projected / e.budget) * 100 : 0, day: e.budget && (e.projected / FC_DAYS) ? e.budget / (e.projected / FC_DAYS) : Infinity }))
    .filter((e) => e.pct >= threshold)
    .sort((a, b) => b.pct - a.pct);

  // ---- geometria do gráfico ----
  const W = 920, H = 290, padL = 60, padR = 18, padT = 14, padB = 30;
  const plotW = W - padL - padR, plotH = H - padT - padB;
  const yMax = Math.max(cur.projected, cur.budget) * 1.15 || 1;
  const X = (d) => padL + (d / FC_DAYS) * plotW;
  const Y = (v) => padT + plotH - (v / yMax) * plotH;
  const toPath = (pts) => pts.map((p, i) => (i ? "L" : "M") + X(p.d).toFixed(1) + " " + Y(p.v).toFixed(1)).join(" ");
  const areaPath = toPath(ser.actual) + ` L ${X(FC_TODAY).toFixed(1)} ${Y(0).toFixed(1)} L ${X(0).toFixed(1)} ${Y(0).toFixed(1)} Z`;

  const gid = "fcGrad-" + (dark ? "d" : "l");
  const grid = [0, 0.25, 0.5, 0.75, 1].map((f) => f * yMax);
  const axisCol = dark ? "rgba(180,210,210,.16)" : "rgba(0,0,0,.10)";
  const tickCol = t.ink3;

  const Seg = ({ val }) => (
    <button onClick={() => setThreshold(val)} className={threshold === val ? "on" : ""}>{val}%</button>
  );

  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12, marginBottom: 12 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: t.ink }}>Custo previsto vs. orçamento</div>
        <div style={{ fontSize: 10.5, color: t.ink3, fontFamily: "var(--font-mono)" }}>Ciclo {FC_CYCLE} · dia {FC_TODAY}/{FC_DAYS}</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.62fr 1fr", gap: 14, alignItems: "stretch" }}>
        {/* ---------- CARD GRÁFICO ---------- */}
        <div style={{ background: t.cardBg, border: `1px solid ${t.cardBorder}`, borderRadius: 16, boxShadow: t.cardShadow, padding: "16px 18px 14px", minWidth: 0 }}>
          {/* seletor de escopo */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
            {[entities.all, ...entities.per].map((e) => {
              const on = scope === e.id;
              return (
                <button key={e.id} onClick={() => setScope(e.id)} style={{
                  display: "inline-flex", alignItems: "center", gap: 6, border: `1px solid ${on ? "var(--brand-teal-600)" : t.chipBorder}`,
                  background: on ? (dark ? "rgba(174,203,224,.20)" : "#e6f4f5") : t.statBg, color: on ? (dark ? "#aecbe0" : "var(--brand-teal-700)") : t.ink2,
                  borderRadius: 999, padding: "5px 11px", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap",
                }}>
                  <span style={{ width: 7, height: 7, borderRadius: 7, background: e.accent, flex: "0 0 7px" }} />
                  {e.id === "all" ? "Toda a operação" : e.name}
                </button>
              );
            })}
          </div>

          {/* SVG */}
          <div className="fc-draw" style={{ width: "100%" }}>
            <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", overflow: "visible" }}>
              <defs>
                <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={lineHex} stopOpacity={dark ? 0.42 : 0.26} />
                  <stop offset="100%" stopColor={lineHex} stopOpacity="0" />
                </linearGradient>
              </defs>

              {/* gridlines + labels R$ */}
              {grid.map((g, i) => (
                <g key={i}>
                  <line x1={padL} y1={Y(g)} x2={W - padR} y2={Y(g)} stroke={axisCol} strokeWidth="1" strokeDasharray={i === 0 ? "0" : "3 4"} />
                  <text x={padL - 9} y={Y(g) + 3.5} textAnchor="end" fontSize="10.5" fontFamily="var(--font-mono)" fill={tickCol}>
                    {g >= 1000 ? (g / 1000).toFixed(g >= 10000 ? 0 : 1).replace(".", ",") + "k" : Math.round(g)}
                  </text>
                </g>
              ))}

              {/* eixo X: dias */}
              {[1, 6, 12, 18, 24, 30].map((d) => (
                <text key={d} x={X(d)} y={H - padB + 17} textAnchor="middle" fontSize="10" fontFamily="var(--font-mono)" fill={tickCol}>{d}</text>
              ))}

              {/* linha de orçamento (teto) */}
              <line x1={padL} y1={Y(cur.budget)} x2={W - padR} y2={Y(cur.budget)} stroke="#ef4444" strokeWidth="1.5" strokeDasharray="6 4" opacity="0.85" />
              <rect x={W - padR - 116} y={Y(cur.budget) - 19} width="116" height="15" rx="4" fill={dark ? "rgba(239,68,68,.18)" : "#fef2f2"} />
              <text x={W - padR - 58} y={Y(cur.budget) - 8} textAnchor="middle" fontSize="9.5" fontWeight="700" fill="#ef4444" fontFamily="var(--font-mono)">TETO {fmtBRL(cur.budget)}</text>

              {/* linha de limite de alerta */}
              {threshold < 100 && (
                <line x1={padL} y1={Y(cur.budget * threshold / 100)} x2={W - padR} y2={Y(cur.budget * threshold / 100)} stroke="#e0a800" strokeWidth="1.25" strokeDasharray="2 5" opacity="0.8" />
              )}

              {/* área + linha real */}
              <path d={areaPath} fill={`url(#${gid})`} className="fc-fill" />
              <path d={toPath(ser.actual)} fill="none" stroke={lineHex} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" className="fc-stroke" />

              {/* linha de projeção (tracejada) */}
              <path d={toPath(ser.proj)} fill="none" stroke={lineHex} strokeWidth="2.2" strokeDasharray="5 5" strokeLinecap="round" opacity="0.92" className="fc-stroke" />

              {/* marcador HOJE */}
              <line x1={X(FC_TODAY)} y1={padT} x2={X(FC_TODAY)} y2={H - padB} stroke={tickCol} strokeWidth="1" strokeDasharray="2 4" opacity="0.55" />
              <circle cx={X(FC_TODAY)} cy={Y(ser.spent)} r="4.5" fill={dark ? "#141416" : "#fff"} stroke={lineHex} strokeWidth="2.4" />
              <text x={X(FC_TODAY)} y={padT - 2} textAnchor="middle" fontSize="9.5" fontWeight="700" fill={tickCol} fontFamily="var(--font-mono)">HOJE</text>

              {/* ponto projetado fim do ciclo */}
              <circle cx={X(FC_DAYS)} cy={Y(cur.projected)} r="5" fill={lineHex} />
              <circle cx={X(FC_DAYS)} cy={Y(cur.projected)} r="9" fill="none" stroke={lineHex} strokeWidth="1.5" opacity="0.4" />
            </svg>
          </div>

          {/* mini-stats sob o gráfico */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10, marginTop: 12, paddingTop: 13, borderTop: `1px solid ${t.cardBorder}` }}>
            {[
              ["Gasto até hoje", fmtBRL(ser.spent), t.ink, "dia " + FC_TODAY + " de " + FC_DAYS],
              ["Projeção fim do ciclo", fmtBRL(cur.projected), lineHex, Math.round(pctBudget) + "% do orçamento"],
              ["Saldo do orçamento", fmtBRL(Math.max(0, cur.budget - cur.projected)), cur.budget - cur.projected < 0 ? "#ef4444" : "#15803d", cur.budget - cur.projected < 0 ? "estouro previsto" : "folga prevista"],
            ].map(([l, v, c, s]) => (
              <div key={l}>
                <div style={{ fontSize: 8.5, textTransform: "uppercase", letterSpacing: ".07em", color: t.ink3, fontWeight: 700 }}>{l}</div>
                <div style={{ fontSize: 17, fontWeight: 700, color: c, fontFamily: "var(--font-mono)", marginTop: 3, letterSpacing: "-.01em" }}>{v}</div>
                <div style={{ fontSize: 10, color: t.ink3, marginTop: 2 }}>{s}</div>
              </div>
            ))}
          </div>
        </div>

        {/* ---------- CARD ALERTAS ---------- */}
        <div style={{ background: t.cardBg, border: `1px solid ${t.cardBorder}`, borderRadius: 16, boxShadow: t.cardShadow, padding: "16px 18px", display: "flex", flexDirection: "column", minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 4 }}>
            <span style={{ width: 32, height: 32, borderRadius: 9, background: dark ? "rgba(224,168,0,.14)" : "#fffbeb", color: "#b8860b", display: "grid", placeItems: "center", flex: "0 0 32px" }}><IconF name="bell" size={16} /></span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: t.ink }}>Alertas de orçamento</div>
              <div style={{ fontSize: 10.5, color: t.ink3 }}>Aviso automático quando a projeção atinge o limite.</div>
            </div>
          </div>

          {/* limite */}
          <div style={{ marginTop: 16 }}>
            <div style={{ fontSize: 9.5, textTransform: "uppercase", letterSpacing: ".07em", color: t.ink3, fontWeight: 700, marginBottom: 7 }}>Disparar em</div>
            <div className="seg" style={{ display: "inline-flex" }}>
              <Seg val={75} /><Seg val={90} /><Seg val={100} />
            </div>
          </div>

          {/* canais */}
          <div style={{ marginTop: 16 }}>
            <div style={{ fontSize: 9.5, textTransform: "uppercase", letterSpacing: ".07em", color: t.ink3, fontWeight: 700, marginBottom: 5 }}>Notificar por</div>
            <label className="twk-toggle" style={{ color: t.ink2 }} onClick={(e) => e.stopPropagation()}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><IconF name="mail" size={13} stroke={2} /> E-mail do responsável</span>
              <input type="checkbox" checked={chMail} onChange={(e) => setChMail(e.target.checked)} />
            </label>
            <label className="twk-toggle" style={{ color: t.ink2 }} onClick={(e) => e.stopPropagation()}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><IconF name="message-circle" size={13} stroke={2} /> WhatsApp · gestor</span>
              <input type="checkbox" checked={chWpp} onChange={(e) => setChWpp(e.target.checked)} />
            </label>
          </div>

          {/* lista de agentes em risco */}
          <div style={{ marginTop: 14, paddingTop: 13, borderTop: `1px solid ${t.cardBorder}`, flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 9 }}>
              <span style={{ fontSize: 9.5, textTransform: "uppercase", letterSpacing: ".07em", color: t.ink3, fontWeight: 700 }}>No limite ({threshold}%)</span>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: flagged.length ? "#b8860b" : "#15803d", fontFamily: "var(--font-mono)" }}>{flagged.length} agente{flagged.length === 1 ? "" : "s"}</span>
            </div>
            {flagged.length === 0 ? (
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11.5, color: "#15803d", background: dark ? "rgba(25,179,107,.10)" : "#ecfdf3", border: `1px solid ${dark ? "transparent" : "#bbf7d0"}`, borderRadius: 10, padding: "10px 12px" }}>
                <IconF name="shield-check" size={15} /> Nenhum agente acima de {threshold}% do orçamento.
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                {flagged.map((e) => {
                  const eo = e.pct >= 100, col = eo ? "#ef4444" : "#e0a800";
                  return (
                    <div key={e.id} onClick={() => setScope(e.id)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", borderRadius: 10, background: t.statBg, border: `1px solid ${t.chipBorder}`, cursor: "pointer" }}>
                      <span style={{ width: 8, height: 8, borderRadius: 8, background: e.accent, flex: "0 0 8px" }} />
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div style={{ fontSize: 11.5, fontWeight: 600, color: t.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e.name}</div>
                        <div style={{ fontSize: 9.5, color: t.ink3, fontFamily: "var(--font-mono)" }}>{fmtBRL(e.projected)} / {fmtBRL(e.budget)}{e.day <= FC_DAYS ? ` · estoura dia ${Math.ceil(e.day)}` : ""}</div>
                      </div>
                      <span style={{ fontSize: 11, fontWeight: 700, color: col, fontFamily: "var(--font-mono)" }}>{Math.round(e.pct)}%</span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.CostForecast = CostForecast;
