/* ANISAN — reusable chart primitives (no chart library; brand-styled SVG/CSS).
   All use the accent family. Shared via window for the babel-transpiled screens. */

function Donut({ pct, label, sub, size = 132, color = "var(--brass)" }) {
  const deg = Math.round(Math.min(100, pct) * 3.6);
  const inner = size - 32;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "4px 0" }}>
      <div style={{ width: size, height: size, borderRadius: "50%", background: `conic-gradient(${color} ${deg}deg, var(--hairline) ${deg}deg)`, display: "grid", placeItems: "center" }}>
        <div style={{ width: inner, height: inner, borderRadius: "50%", background: "var(--surface)", display: "grid", placeItems: "center" }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: size * 0.2, fontWeight: 500, color }}>{pct}%</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--muted-2)", letterSpacing: "0.06em" }}>da meta</div>
          </div>
        </div>
      </div>
      {label && <div style={{ fontFamily: "var(--font-display)", fontSize: 17, color: "var(--paper)", marginTop: 14 }}>{label}</div>}
      {sub && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)", marginTop: 3 }}>{sub}</div>}
    </div>
  );
}

function BarChart({ data, labels, color = "var(--brass)", height = 160, highlight = [], max: maxOverride, mutedBars = [] }) {
  const max = maxOverride || Math.max(...data, 1);
  const [hover, setHover] = React.useState(null);
  const fmt = (v) => (window.BRL ? window.BRL(v) : v);
  return (
    <div style={{ position: "relative" }}>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height }}>
        {data.map((v, i) => {
          const isHot = hover === i;
          const lit = isHot || highlight.includes(i);
          return (
            <div
              key={i}
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover((h) => (h === i ? null : h))}
              style={{ position: "relative", flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, height: "100%", justifyContent: "flex-end", cursor: "default" }}
            >
              {isHot && (
                <div style={{
                  position: "absolute", bottom: "100%", left: "50%", transform: "translateX(-50%)", marginBottom: 6,
                  background: "var(--ink)", border: "1px solid var(--hairline-strong)", borderRadius: 7,
                  padding: "5px 9px", whiteSpace: "nowrap", zIndex: 20, pointerEvents: "none",
                  boxShadow: "var(--shadow-raised)",
                }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--muted)" }}>{labels[i]}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--paper)", marginTop: 1 }}>{fmt(v)}</div>
                </div>
              )}
              <div style={{ width: "100%", maxWidth: 38, height: `${(v / max) * (height - 26)}px`, background: lit ? color : (mutedBars.includes(i) ? "var(--hairline)" : "var(--surface-2)"), borderRadius: 5, transition: "height .5s ease, background .15s ease" }}></div>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: mutedBars.includes(i) ? "var(--muted-2)" : (lit ? "var(--paper)" : "var(--muted)") }}>{labels[i]}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function GroupedBars({ labels, a, b, aColor = "var(--brass)", bColor = "var(--surface-2)", aLabel = "Realizado", bLabel = "Planejado", height = 180 }) {
  const max = Math.max(...a, ...b, 1);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 10, height }}>
        {labels.map((lb, i) => (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, height: "100%", justifyContent: "flex-end" }}>
            <div style={{ display: "flex", alignItems: "flex-end", gap: 3, width: "100%", maxWidth: 40, height: "100%", justifyContent: "center" }}>
              <div style={{ flex: 1, height: `${((b[i] || 0) / max) * (height - 24)}px`, background: bColor, borderRadius: "4px 4px 0 0", transition: "height .5s ease" }}></div>
              <div style={{ flex: 1, height: `${((a[i] || 0) / max) * (height - 24)}px`, background: aColor, borderRadius: "4px 4px 0 0", transition: "height .5s ease" }}></div>
            </div>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--muted-2)" }}>{lb}</span>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 18, marginTop: 14, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 7 }}><i style={{ width: 9, height: 9, borderRadius: 2, background: aColor }}></i>{aLabel}</span>
        <span style={{ display: "flex", alignItems: "center", gap: 7 }}><i style={{ width: 9, height: 9, borderRadius: 2, background: bColor }}></i>{bLabel}</span>
      </div>
    </div>
  );
}

/* A filled area/line chart for trends (saldo devedor, etc). */
function AreaChart({ values, labels, color = "var(--brass)", height = 200, baseline = 0 }) {
  const W = 640, H = 200, pad = 14;
  const all = values.concat([baseline]);
  const max = Math.max(...all), min = Math.min(...all);
  const range = (max - min) || 1;
  const x = (i) => pad + (i / (values.length - 1)) * (W - 2 * pad);
  const y = (v) => H - pad - ((v - min) / range) * (H - 2 * pad);
  const line = values.map((v, i) => `${i ? "L" : "M"}${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(" ");
  const area = `${line} L ${x(values.length - 1).toFixed(1)} ${H - pad} L ${x(0).toFixed(1)} ${H - pad} Z`;
  const gid = "g" + Math.random().toString(36).slice(2, 8);
  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: "100%", height, display: "block" }}>
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.30" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d={area} fill={`url(#${gid})`} />
        <path d={line} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
        {values.map((v, i) => <circle key={i} cx={x(i)} cy={y(v)} r="3" fill="var(--surface)" stroke={color} strokeWidth="2" />)}
      </svg>
      {labels && (
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--muted-2)" }}>
          {labels.map((l, i) => <span key={i}>{l}</span>)}
        </div>
      )}
    </div>
  );
}

/* A pill-tab period/segment switcher used across screens. */
function SegTabs({ options, value, onChange }) {
  return (
    <div style={{ display: "inline-flex", flexWrap: "wrap", gap: 6, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-pill)", padding: 4 }}>
      {options.map((o) => {
        const active = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            border: "none", cursor: "pointer", borderRadius: "var(--radius-pill)", padding: "7px 15px",
            background: active ? "var(--brass)" : "transparent",
            color: active ? "var(--ink)" : "var(--muted)",
            fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: "0.03em",
            transition: "background .15s ease, color .15s ease",
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

/* A bare card wrapper with a Fraunces title + optional action. */
function Panel({ title, action, children, style }) {
  const narrow = typeof window !== "undefined" && window.innerWidth <= 760;
  const merged = { background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius)", padding: narrow ? "16px 16px" : "20px 22px", ...style };
  if (narrow) { merged.minWidth = 0; merged.flex = "1 1 100%"; merged.flexBasis = "100%"; }
  return (
    <div style={merged}>
      {(title || action) && (
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 16 }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500, color: "var(--paper)" }}>{title}</span>
          {action}
        </div>
      )}
      <div style={{ overflowX: narrow ? "auto" : "visible" }}>{children}</div>
    </div>
  );
}

/* Multi-line chart — séries históricas (uma linha por ano, p/ tendências). */
function LineSeries({ series, labels, height = 220, format }) {
  const W = 680, H = height, padR = 8, padT = 10, padB = 8;
  const fmt = format || ((v) => (window.BRLk ? window.BRLk(v) : Math.round(v)));
  const [hover, setHover] = React.useState(null);
  const all = series.flatMap((s) => s.values).filter((v) => typeof v === "number");
  let dMax = Math.max(...all, 0), dMin = Math.min(...all, 0);
  if (dMax === dMin) dMax = dMin + 1;
  // headroom: 8% acima/abaixo, ancorando em 0 quando todos os valores são ≥ 0
  const span = dMax - dMin;
  const hi = dMax + span * 0.08;
  const lo = dMin >= 0 ? 0 : dMin - span * 0.08;
  const range = (hi - lo) || 1;
  const n = labels.length;
  const x = (i) => (n > 1 ? (i / (n - 1)) * (W - padR) : 0);
  const y = (v) => padT + (1 - (v - lo) / range) * (H - padT - padB);
  const ticks = [hi, lo + range / 2, lo];   // topo, meio, base
  return (
    <div>
      <div style={{ display: "flex", alignItems: "stretch", gap: 8 }}>
        {/* eixo Y (rótulos de valor) */}
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: H, paddingTop: padT, paddingBottom: padB, textAlign: "right", flexShrink: 0 }}>
          {ticks.map((t, k) => <span key={k} style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--muted-2)", lineHeight: 1, whiteSpace: "nowrap" }}>{fmt(t)}</span>)}
        </div>
        {/* área do gráfico */}
        <div style={{ position: "relative", flex: 1, minWidth: 0 }}>
          <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: "100%", height: H, display: "block" }}
            onMouseLeave={() => setHover(null)}
            onMouseMove={(e) => { const r = e.currentTarget.getBoundingClientRect(); const px = (e.clientX - r.left) / r.width * W; const i = Math.round(px / ((W - padR) / Math.max(1, n - 1))); setHover(Math.max(0, Math.min(n - 1, i))); }}>
            {ticks.map((t, k) => <line key={k} x1={0} x2={W} y1={y(t)} y2={y(t)} stroke="var(--hairline)" strokeWidth="1" strokeDasharray={k === 2 ? "none" : "3 4"} />)}
            {hover != null && <line x1={x(hover)} x2={x(hover)} y1={padT} y2={H - padB} stroke="var(--hairline-strong)" strokeWidth="1" />}
            {series.map((s, si) => {
              const d = s.values.map((v, i) => `${i ? "L" : "M"}${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(" ");
              return <path key={si} d={d} fill="none" stroke={s.color} strokeWidth={s.width || 2.4} strokeLinejoin="round" strokeLinecap="round" strokeDasharray={s.dashed ? "5 4" : "none"} opacity={s.dashed ? 0.65 : 1} vectorEffect="non-scaling-stroke" />;
            })}
            {hover != null && series.map((s, si) => <circle key={si} cx={x(hover)} cy={y(s.values[hover])} r="3.5" fill="var(--surface)" stroke={s.color} strokeWidth="2" vectorEffect="non-scaling-stroke" />)}
          </svg>
          {hover != null && (
            <div style={{ position: "absolute", top: 0, left: `${(x(hover) / W) * 100}%`, transform: x(hover) > W * 0.6 ? "translateX(-100%)" : "none", pointerEvents: "none", background: "var(--ink)", border: "1px solid var(--hairline-strong)", borderRadius: 8, padding: "7px 10px", whiteSpace: "nowrap", zIndex: 3 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--muted)", marginBottom: 4 }}>{labels[hover]}</div>
              {series.map((s, si) => <div key={si} style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--paper)" }}><i style={{ width: 8, height: 8, borderRadius: 2, background: s.color, display: "inline-block" }}></i>{s.name}: {fmt(s.values[hover])}</div>)}
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--muted-2)" }}>
            {labels.map((l, i) => <span key={i}>{l}</span>)}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", gap: 16, flexWrap: "wrap", marginTop: 12 }}>
        {series.map((s, si) => <span key={si} style={{ display: "flex", alignItems: "center", gap: 7, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)" }}><i style={{ width: 14, height: 3, borderRadius: 2, background: s.color, display: "inline-block", opacity: s.dashed ? 0.7 : 1 }}></i>{s.name}</span>)}
      </div>
    </div>
  );
}

Object.assign(window, { Donut, BarChart, GroupedBars, AreaChart, LineSeries, SegTabs, Panel });
