/* ============================================================
   Bizia — Lightweight SVG charts (no external deps)
   Sparkline, AreaChart, BarChart, DonutChart, HBars
   ============================================================ */
(function () {
  const { useState, useMemo } = React;

  function smoothPath(pts) {
    if (pts.length < 2) return '';
    let d = 'M ' + pts[0][0] + ' ' + pts[0][1];
    for (let i = 0; i < pts.length - 1; i++) {
      const [x0, y0] = pts[i], [x1, y1] = pts[i + 1];
      const cx = (x0 + x1) / 2;
      d += ' C ' + cx + ' ' + y0 + ', ' + cx + ' ' + y1 + ', ' + x1 + ' ' + y1;
    }
    return d;
  }

  function Sparkline({ data, w = 120, h = 36, color = 'var(--primary)', fill = true, strokeWidth = 2 }) {
    const id = useMemo(() => 'sp' + Math.random().toString(36).slice(2, 6), []);
    const max = Math.max(...data), min = Math.min(...data);
    const rng = max - min || 1;
    const pts = data.map((v, i) => [(i / (data.length - 1)) * w, h - 4 - ((v - min) / rng) * (h - 8)]);
    const line = smoothPath(pts);
    return React.createElement('svg', { width: w, height: h, style: { display: 'block', overflow: 'visible' } },
      React.createElement('defs', null,
        React.createElement('linearGradient', { id, x1: '0', y1: '0', x2: '0', y2: '1' },
          React.createElement('stop', { offset: '0', stopColor: color, stopOpacity: 0.22 }),
          React.createElement('stop', { offset: '1', stopColor: color, stopOpacity: 0 }),
        ),
      ),
      fill ? React.createElement('path', { d: line + ' L ' + w + ' ' + h + ' L 0 ' + h + ' Z', fill: 'url(#' + id + ')' }) : null,
      React.createElement('path', { d: line, fill: 'none', stroke: color, strokeWidth, strokeLinecap: 'round' }),
    );
  }

  function AreaChart({ series, labels, w = 560, h = 220, colors, showGrid = true, yFormat }) {
    colors = colors || ['var(--primary)', 'var(--secondary)'];
    const padL = 36, padB = 26, padT = 14, padR = 8;
    const iw = w - padL - padR, ih = h - padB - padT;
    const allVals = series.flatMap(s => s.data);
    const max = Math.max(...allVals) * 1.12 || 1;
    const ids = useMemo(() => series.map((_, i) => 'ar' + i + Math.random().toString(36).slice(2, 5)), [series.length]);
    const [hover, setHover] = useState(null);
    const xAt = i => padL + (i / (labels.length - 1)) * iw;
    const yAt = v => padT + ih - (v / max) * ih;
    const gridY = [0, 0.25, 0.5, 0.75, 1];
    return React.createElement('svg', {
      viewBox: '0 0 ' + w + ' ' + h, width: '100%', style: { display: 'block', overflow: 'visible' },
      onMouseLeave: () => setHover(null),
      onMouseMove: (e) => {
        const rect = e.currentTarget.getBoundingClientRect();
        const x = (e.clientX - rect.left) / rect.width * w;
        const i = Math.round(((x - padL) / iw) * (labels.length - 1));
        if (i >= 0 && i < labels.length) setHover(i);
      },
    },
      React.createElement('defs', null, series.map((s, i) =>
        React.createElement('linearGradient', { key: i, id: ids[i], x1: '0', y1: '0', x2: '0', y2: '1' },
          React.createElement('stop', { offset: '0', stopColor: colors[i], stopOpacity: 0.26 }),
          React.createElement('stop', { offset: '1', stopColor: colors[i], stopOpacity: 0.02 }),
        ),
      )),
      showGrid ? gridY.map((g, i) =>
        React.createElement('g', { key: i },
          React.createElement('line', { x1: padL, x2: w - padR, y1: padT + ih * g, y2: padT + ih * g, stroke: 'var(--border-soft)', strokeWidth: 1 }),
          React.createElement('text', { x: padL - 8, y: padT + ih * g + 4, textAnchor: 'end', fontSize: 10, fill: 'var(--muted-2)' },
            yFormat ? yFormat(Math.round(max * (1 - g))) : Math.round(max * (1 - g))),
        )) : null,
      series.map((s, i) => {
        const pts = s.data.map((v, j) => [xAt(j), yAt(v)]);
        const line = smoothPath(pts);
        return React.createElement('g', { key: i },
          React.createElement('path', { d: line + ' L ' + xAt(labels.length - 1) + ' ' + (padT + ih) + ' L ' + padL + ' ' + (padT + ih) + ' Z', fill: 'url(#' + ids[i] + ')' }),
          React.createElement('path', { d: line, fill: 'none', stroke: colors[i], strokeWidth: 2.4, strokeLinecap: 'round' }),
        );
      }),
      labels.map((l, i) => (i % Math.ceil(labels.length / 7) === 0) ?
        React.createElement('text', { key: i, x: xAt(i), y: h - 6, textAnchor: 'middle', fontSize: 10, fill: 'var(--muted-2)' }, l) : null),
      hover != null ? React.createElement('g', null,
        React.createElement('line', { x1: xAt(hover), x2: xAt(hover), y1: padT, y2: padT + ih, stroke: 'var(--border-strong)', strokeWidth: 1, strokeDasharray: '3 3' }),
        series.map((s, i) => React.createElement('circle', { key: i, cx: xAt(hover), cy: yAt(s.data[hover]), r: 4, fill: colors[i], stroke: 'var(--surface)', strokeWidth: 2 })),
      ) : null,
      hover != null ? React.createElement('foreignObject', { x: Math.min(xAt(hover) + 8, w - 130), y: padT, width: 130, height: 70 },
        React.createElement('div', {
          style: { background: 'var(--text)', color: 'var(--surface)', borderRadius: 8, padding: '7px 10px', fontSize: 11, boxShadow: 'var(--sh-md)' },
        },
          React.createElement('div', { style: { fontWeight: 600, marginBottom: 4, opacity: 0.7 } }, labels[hover]),
          series.map((s, i) => React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 5, marginTop: 2 } },
            React.createElement('span', { style: { width: 7, height: 7, borderRadius: 9, background: colors[i] } }),
            React.createElement('span', { style: { opacity: 0.8 } }, s.name + ': '),
            React.createElement('strong', null, (yFormat ? yFormat(s.data[hover]) : s.data[hover])),
          )),
        ),
      ) : null,
    );
  }

  function BarChart({ data, labels, w = 560, h = 220, color = 'var(--primary)', color2, yFormat }) {
    const padL = 36, padB = 26, padT = 14, padR = 8;
    const iw = w - padL - padR, ih = h - padB - padT;
    const max = Math.max(...data) * 1.15 || 1;
    const bw = iw / data.length;
    const id = useMemo(() => 'bc' + Math.random().toString(36).slice(2, 6), []);
    const [hover, setHover] = useState(null);
    return React.createElement('svg', { viewBox: '0 0 ' + w + ' ' + h, width: '100%', style: { display: 'block', overflow: 'visible' } },
      React.createElement('defs', null,
        React.createElement('linearGradient', { id, x1: '0', y1: '0', x2: '0', y2: '1' },
          React.createElement('stop', { offset: '0', stopColor: color2 || color }),
          React.createElement('stop', { offset: '1', stopColor: color, stopOpacity: 0.65 }),
        ),
      ),
      [0, 0.5, 1].map((g, i) =>
        React.createElement('line', { key: i, x1: padL, x2: w - padR, y1: padT + ih * g, y2: padT + ih * g, stroke: 'var(--border-soft)', strokeWidth: 1 })),
      data.map((v, i) => {
        const bh = (v / max) * ih, x = padL + i * bw + bw * 0.18, bwid = bw * 0.64;
        return React.createElement('g', { key: i, onMouseEnter: () => setHover(i), onMouseLeave: () => setHover(null) },
          React.createElement('rect', { x, y: padT + ih - bh, width: bwid, height: bh, rx: Math.min(6, bwid / 2), fill: 'url(#' + id + ')', opacity: hover == null || hover === i ? 1 : 0.45, style: { transition: 'opacity .15s' } }),
          hover === i ? React.createElement('text', { x: x + bwid / 2, y: padT + ih - bh - 7, textAnchor: 'middle', fontSize: 11, fontWeight: 700, fill: 'var(--text)' }, yFormat ? yFormat(v) : v) : null,
          React.createElement('text', { x: x + bwid / 2, y: h - 7, textAnchor: 'middle', fontSize: 10, fill: 'var(--muted-2)' }, labels[i]),
        );
      }),
    );
  }

  function DonutChart({ data, size = 160, stroke = 22, gap = 0.02 }) {
    // data: [{label, value, color}]
    const total = data.reduce((a, d) => a + d.value, 0) || 1;
    const r = (size - stroke) / 2, c = 2 * Math.PI * r;
    let acc = 0;
    return React.createElement('div', { style: { position: 'relative', width: size, height: size } },
      React.createElement('svg', { width: size, height: size, style: { transform: 'rotate(-90deg)' } },
        React.createElement('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--surface-3)', strokeWidth: stroke }),
        data.map((d, i) => {
          const frac = d.value / total;
          const dash = Math.max(0, (frac - gap)) * c;
          const el = React.createElement('circle', {
            key: i, cx: size / 2, cy: size / 2, r, fill: 'none', stroke: d.color, strokeWidth: stroke,
            strokeDasharray: dash + ' ' + (c - dash), strokeDashoffset: -acc * c, strokeLinecap: 'round',
            style: { transition: 'stroke-dasharray .8s var(--ease)' },
          });
          acc += frac;
          return el;
        }),
      ),
    );
  }

  function HBars({ data, valueFormat, max: maxProp, color = 'var(--primary)' }) {
    const max = maxProp || Math.max(...data.map(d => d.value)) || 1;
    return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 13 } },
      data.map((d, i) => React.createElement('div', { key: i },
        React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 6 } },
          React.createElement('span', { style: { color: 'var(--text-2)', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 } },
            d.icon ? React.createElement(window.Icon, { name: d.icon, size: 14, style: { color: 'var(--muted)' } }) : null,
            React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, d.label)),
          React.createElement('span', { style: { fontWeight: 650, color: 'var(--text)' } }, valueFormat ? valueFormat(d.value) : d.value),
        ),
        React.createElement('div', { style: { height: 8, borderRadius: 999, background: 'var(--surface-3)', overflow: 'hidden' } },
          React.createElement('div', { style: { width: (d.value / max * 100) + '%', height: '100%', borderRadius: 999, background: d.color || color, transition: 'width .7s var(--ease)' } }),
        ),
      )),
    );
  }

  Object.assign(window, { Sparkline, AreaChart, BarChart, DonutChart, HBars });
})();
