/* ============================================================
   JIT BATCH — Custom SVG charts (tecnici, on-brand)
   Exposes window.Charts = { LineChart, BarChart, HBars, Donut, MiniSpark }
   ============================================================ */
const { useState: useStateC, useRef: useRefC, useEffect: useEffectC } = React;

/* ---- Vertical bar chart (produzione per giorno) ----------- */
function BarChart({ data, height = 190, target = null, unit = "m³" }) {
  const [hover, setHover] = useStateC(null);
  const max = Math.max(...data.map(d => d.v), target || 0) * 1.12 || 1;
  const W = 100, padB = 18, padT = 8;
  const bw = 100 / data.length;
  const targetY = target != null ? padT + (1 - target / max) * (height - padB - padT) : null;
  return (
    <div style={{ position: "relative" }}>
      <svg viewBox={`0 0 100 ${height}`} preserveAspectRatio="none" style={{ width: "100%", height, display: "block", overflow: "visible" }}>
        {[0.25, 0.5, 0.75, 1].map((g, i) => {
          const y = padT + (1 - g) * (height - padB - padT);
          return <line key={i} x1="0" x2="100" y1={y} y2={y} stroke="var(--border)" strokeWidth="0.4" vectorEffect="non-scaling-stroke" />;
        })}
        {target != null && <line x1="0" x2="100" y1={targetY} y2={targetY} stroke="var(--jit-orange)" strokeWidth="1" strokeDasharray="3 2" vectorEffect="non-scaling-stroke" />}
        {data.map((d, i) => {
          const h = (d.v / max) * (height - padB - padT);
          const x = i * bw + bw * 0.22;
          const w = bw * 0.56;
          const y = height - padB - h;
          const isHi = hover === i;
          return (
            <g key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
              <rect x={i * bw} y={padT} width={bw} height={height - padB - padT} fill="transparent" />
              <rect x={x} y={y} width={w} height={Math.max(h, 0)} rx="1.2"
                fill={isHi ? "var(--jit-orange)" : (d.v === 0 ? "var(--gray-300)" : "var(--navy-500)")}
                style={{ transition: "fill 140ms, y 500ms cubic-bezier(0.2,0,0,1), height 500ms cubic-bezier(0.2,0,0,1)" }} />
            </g>
          );
        })}
      </svg>
      <div style={{ display: "flex", marginTop: 4 }}>
        {data.map((d, i) => (
          <div key={i} style={{ flex: 1, textAlign: "center", fontSize: 11, fontWeight: 600, color: hover === i ? "var(--fg-accent)" : "var(--fg-3)", fontFamily: "var(--font-mono)" }}>{d.g || d.d}</div>
        ))}
      </div>
      {hover != null && (
        <div style={{ position: "absolute", top: -6, left: `${(hover + 0.5) * bw}%`, transform: "translate(-50%,-100%)", background: "var(--navy-900)", color: "#fff", padding: "4px 8px", borderRadius: 6, fontSize: 11.5, fontFamily: "var(--font-mono)", whiteSpace: "nowrap", pointerEvents: "none", boxShadow: "var(--shadow-md)", zIndex: 5 }}>
          {data[hover].v} {unit}
        </div>
      )}
    </div>
  );
}

/* ---- Line / area chart ------------------------------------ */
function LineChart({ data, height = 190, unit = "m³", color = "var(--jit-orange)" }) {
  const [hover, setHover] = useStateC(null);
  const max = Math.max(...data.map(d => d.v)) * 1.12 || 1;
  const min = 0;
  const W = 100, padB = 18, padT = 8, padX = 4;
  const n = data.length;
  const xAt = (i) => padX + (i / (n - 1)) * (W - padX * 2);
  const yAt = (v) => padT + (1 - (v - min) / (max - min)) * (height - padB - padT);
  const pts = data.map((d, i) => `${xAt(i)},${yAt(d.v)}`).join(" ");
  const area = `${padX},${height - padB} ${pts} ${W - padX},${height - padB}`;
  return (
    <div style={{ position: "relative" }}>
      <svg viewBox={`0 0 100 ${height}`} preserveAspectRatio="none" style={{ width: "100%", height, display: "block", overflow: "visible" }}>
        <defs>
          <linearGradient id="lcfill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.22" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        {[0.25, 0.5, 0.75, 1].map((g, i) => {
          const y = padT + (1 - g) * (height - padB - padT);
          return <line key={i} x1="0" x2="100" y1={y} y2={y} stroke="var(--border)" strokeWidth="0.4" vectorEffect="non-scaling-stroke" />;
        })}
        <polygon points={area} fill="url(#lcfill)" />
        <polyline points={pts} fill="none" stroke={color} strokeWidth="2" vectorEffect="non-scaling-stroke" strokeLinejoin="round" strokeLinecap="round" />
        {data.map((d, i) => (
          <g key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
            <rect x={xAt(i) - (W / n) / 2} y={0} width={W / n} height={height} fill="transparent" />
            <circle cx={xAt(i)} cy={yAt(d.v)} r={hover === i ? 3 : 2} fill="var(--bg-surface)" stroke={color} strokeWidth="2" vectorEffect="non-scaling-stroke" />
          </g>
        ))}
      </svg>
      <div style={{ display: "flex", marginTop: 4 }}>
        {data.map((d, i) => (
          <div key={i} style={{ flex: 1, textAlign: "center", fontSize: 11, fontWeight: 600, color: hover === i ? "var(--fg-accent)" : "var(--fg-3)", fontFamily: "var(--font-mono)" }}>{d.g || d.d}</div>
        ))}
      </div>
      {hover != null && (
        <div style={{ position: "absolute", top: -6, left: `${xAt(hover)}%`, transform: "translate(-50%,-100%)", background: "var(--navy-900)", color: "#fff", padding: "4px 8px", borderRadius: 6, fontSize: 11.5, fontFamily: "var(--font-mono)", whiteSpace: "nowrap", pointerEvents: "none", boxShadow: "var(--shadow-md)", zIndex: 5 }}>
          {data[hover].v} {unit}
        </div>
      )}
    </div>
  );
}

/* ---- Horizontal bars (per cliente / consumo) -------------- */
function HBars({ data, unit = "", money = false }) {
  const max = Math.max(...data.map(d => d.v)) || 1;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
      {data.map((d, i) => (
        <div key={i}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}>
            <span style={{ color: "var(--fg-2)", fontWeight: 600 }}>{d.cliente || d.mat || d.label}</span>
            <span className="data" style={{ color: "var(--fg-1)" }}>{d.v}{unit ? " " + unit : (d.um ? " " + d.um : "")}</span>
          </div>
          <div style={{ height: 9, background: "var(--bg-sunken)", borderRadius: 99, overflow: "hidden" }}>
            <div style={{ width: `${(d.v / max) * 100}%`, height: "100%", borderRadius: 99, background: d.col || "var(--navy-500)", transition: "width 600ms cubic-bezier(0.2,0,0,1)" }} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---- Donut ------------------------------------------------- */
function Donut({ segments, size = 140, thickness = 18, center }) {
  const total = segments.reduce((s, x) => s + x.v, 0) || 1;
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let acc = 0;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flex: "none" }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--bg-sunken)" strokeWidth={thickness} />
        {segments.map((s, i) => {
          const len = (s.v / total) * c;
          const el = <circle key={i} cx={size / 2} cy={size / 2} r={r} fill="none" stroke={s.col} strokeWidth={thickness}
            strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-acc} transform={`rotate(-90 ${size / 2} ${size / 2})`}
            style={{ transition: "stroke-dasharray 600ms cubic-bezier(0.2,0,0,1)" }} strokeLinecap="butt" />;
          acc += len;
          return el;
        })}
        {center && <text x="50%" y="48%" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 22, fill: "var(--fg-1)" }}>{center.v}</text>}
        {center && <text x="50%" y="62%" textAnchor="middle" style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 9, fill: "var(--fg-3)" }}>{center.label}</text>}
      </svg>
      <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
        {segments.map((s, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: s.col, flex: "none" }} />
            <span style={{ color: "var(--fg-2)", flex: 1 }}>{s.label}</span>
            <span className="data" style={{ color: "var(--fg-1)" }}>{s.v}{s.um ? " " + s.um : ""}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Mini sparkline --------------------------------------- */
function MiniSpark({ data, color = "var(--status-run)", height = 34, width = 90 }) {
  const max = Math.max(...data) * 1.1 || 1, min = Math.min(...data) * 0.9;
  const n = data.length;
  const pts = data.map((v, i) => `${(i / (n - 1)) * width},${height - ((v - min) / (max - min)) * height}`).join(" ");
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ overflow: "visible" }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

window.Charts = { BarChart, LineChart, HBars, Donut, MiniSpark };
