// aerOS — real SVG charts. Exports to window. All responsive via viewBox.
const { useState: _cS, useId: _cId } = React;

function useUid() { return React.useId ? React.useId().replace(/:/g, '') : Math.random().toString(36).slice(2); }

/* ----------------------------- LineChart (area) ----------------------------- */
function LineChart({ data, height = 220, color = 'var(--brand)', labels, valueFmt = v => v, showDots = true, area = true }) {
  const [hover, setHover] = _cS(null);
  const uid = useUid();
  const W = 600, H = height, padL = 8, padR = 8, padT = 16, padB = 28;
  const xs = data.length;
  const max = Math.max(...data, 1) * 1.12;
  const min = Math.min(...data, 0);
  const range = max - min || 1;
  const px = i => padL + (i * (W - padL - padR)) / Math.max(1, xs - 1);
  const py = v => padT + (1 - (v - min) / range) * (H - padT - padB);
  const pts = data.map((v, i) => [px(i), py(v)]);
  const line = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const areaPath = line + ` L${px(xs - 1).toFixed(1)} ${H - padB} L${padL} ${H - padB} Z`;
  const gy = [0, 0.25, 0.5, 0.75, 1].map(f => padT + f * (H - padT - padB));
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height, display: 'block', overflow: 'visible' }} onMouseLeave={() => setHover(null)}>
      <defs>
        <linearGradient id={`lg-${uid}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.20" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {gy.map((y, i) => <line key={i} x1={padL} y1={y} x2={W - padR} y2={y} stroke="var(--border)" strokeWidth="1" strokeDasharray={i === 4 ? '0' : '3 4'} opacity={i === 4 ? 1 : 0.6} />)}
      {area && <path d={areaPath} fill={`url(#lg-${uid})`} />}
      <path d={line} fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
      {showDots && pts.map((p, i) => (
        <g key={i}>
          <rect x={px(i) - (W / xs) / 2} y={0} width={W / xs} height={H} fill="transparent" onMouseEnter={() => setHover(i)} />
          <circle cx={p[0]} cy={p[1]} r={hover === i ? 5 : 3} fill="var(--bg-0)" stroke={color} strokeWidth="2.2" style={{ transition: 'r 120ms' }} />
        </g>
      ))}
      {labels && labels.map((l, i) => (i % Math.ceil(xs / 8) === 0 || i === xs - 1) && (
        <text key={i} x={px(i)} y={H - 8} fontSize="11" fill="var(--fg-3)" textAnchor={i === 0 ? 'start' : i === xs - 1 ? 'end' : 'middle'} fontFamily="var(--font)">{l}</text>
      ))}
      {hover != null && (
        <g style={{ pointerEvents: 'none' }}>
          <line x1={pts[hover][0]} y1={padT} x2={pts[hover][0]} y2={H - padB} stroke={color} strokeWidth="1" strokeDasharray="3 3" opacity="0.5" />
          <g transform={`translate(${Math.min(Math.max(pts[hover][0], 36), W - 36)}, ${Math.max(pts[hover][1] - 14, 14)})`}>
            <rect x={-34} y={-22} width={68} height={22} rx={5} fill="var(--fg-1)" />
            <text x={0} y={-7} fontSize="11.5" fontWeight="600" fill="var(--bg-0)" textAnchor="middle" fontFamily="var(--font)">{valueFmt(data[hover])}</text>
          </g>
        </g>
      )}
    </svg>
  );
}

/* ----------------------------- BarChart ----------------------------- */
function BarChart({ data, height = 220, color = 'var(--brand)', labels, valueFmt = v => v, horizontal = false }) {
  const [hover, setHover] = _cS(null);
  const max = Math.max(...data.map(d => typeof d === 'object' ? d.value : d), 1) * 1.1;
  const vals = data.map(d => typeof d === 'object' ? d : { value: d });
  if (horizontal) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {vals.map((d, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 120, fontSize: 12.5, color: 'var(--fg-2)', textAlign: 'right', flexShrink: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{labels ? labels[i] : d.label}</div>
            <div style={{ flex: 1, height: 22, background: 'var(--bg-3)', borderRadius: 5, overflow: 'hidden', position: 'relative' }}>
              <div style={{ width: (d.value / max * 100) + '%', height: '100%', background: d.color || color, borderRadius: 5, transition: 'width 500ms cubic-bezier(0.16,1,0.3,1)', minWidth: 3 }} />
            </div>
            <div className="tnum" style={{ width: 56, fontSize: 12.5, fontWeight: 600, color: 'var(--fg-1)', textAlign: 'right', flexShrink: 0 }}>{valueFmt(d.value)}</div>
          </div>
        ))}
      </div>
    );
  }
  const W = 600, H = height, padB = 28, padT = 12, gap = 0.34;
  const n = vals.length;
  const bw = (W / n) * (1 - gap);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height, display: 'block' }} onMouseLeave={() => setHover(null)}>
      {[0.25, 0.5, 0.75, 1].map((f, i) => <line key={i} x1={0} y1={padT + f * (H - padT - padB)} x2={W} y2={padT + f * (H - padT - padB)} stroke="var(--border)" strokeDasharray="3 4" opacity="0.6" />)}
      {vals.map((d, i) => {
        const h = (d.value / max) * (H - padT - padB);
        const x = (i + 0.5) * (W / n) - bw / 2;
        const y = H - padB - h;
        return (
          <g key={i} onMouseEnter={() => setHover(i)}>
            <rect x={(i) * (W / n)} y={0} width={W / n} height={H} fill="transparent" />
            <rect x={x} y={y} width={bw} height={h} rx={5} fill={d.color || color} opacity={hover == null || hover === i ? 1 : 0.45} style={{ transition: 'opacity 120ms' }} />
            {hover === i && <text x={x + bw / 2} y={y - 6} fontSize="11.5" fontWeight="700" fill="var(--fg-1)" textAnchor="middle" fontFamily="var(--font)">{valueFmt(d.value)}</text>}
            {labels && <text x={x + bw / 2} y={H - 9} fontSize="11" fill="var(--fg-3)" textAnchor="middle" fontFamily="var(--font)">{labels[i]}</text>}
          </g>
        );
      })}
    </svg>
  );
}

/* ----------------------------- DonutChart ----------------------------- */
function DonutChart({ data, size = 180, thickness = 26, centerLabel, centerValue }) {
  const [hover, setHover] = _cS(null);
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const R = size / 2, r = R - thickness / 2;
  const C = 2 * Math.PI * r;
  let offset = 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 22, flexWrap: 'wrap' }}>
      <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
        <svg viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size, transform: 'rotate(-90deg)' }}>
          <circle cx={R} cy={R} r={r} fill="none" stroke="var(--bg-3)" strokeWidth={thickness} />
          {data.map((d, i) => {
            const frac = d.value / total;
            const dash = frac * C;
            const seg = <circle key={i} cx={R} cy={R} r={r} fill="none" stroke={d.color} strokeWidth={hover === i ? thickness + 4 : thickness} strokeDasharray={`${dash} ${C - dash}`} strokeDashoffset={-offset} strokeLinecap="butt" onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} style={{ transition: 'stroke-width 120ms', cursor: 'pointer' }} />;
            offset += dash;
            return seg;
          })}
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
          <div className="tnum" style={{ fontSize: size * 0.18, fontWeight: 700, color: 'var(--fg-1)', lineHeight: 1 }}>{hover != null ? data[hover].value : (centerValue ?? total)}</div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 3 }}>{hover != null ? data[hover].label : centerLabel}</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, minWidth: 0 }}>
        {data.map((d, i) => (
          <div key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} style={{ display: 'flex', alignItems: 'center', gap: 9, cursor: 'pointer', opacity: hover == null || hover === i ? 1 : 0.5, transition: 'opacity 120ms' }}>
            <span style={{ width: 11, height: 11, borderRadius: 3, background: d.color, flexShrink: 0 }} />
            <span style={{ fontSize: 13, color: 'var(--fg-2)', flex: 1 }}>{d.label}</span>
            <span className="tnum" style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' }}>{Math.round(d.value / total * 100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ----------------------------- Sparkline ----------------------------- */
function Sparkline({ data, width = 90, height = 30, color = 'var(--brand)' }) {
  const max = Math.max(...data, 1), min = Math.min(...data, 0), range = max - min || 1;
  const px = i => (i * width) / Math.max(1, data.length - 1);
  const py = v => height - ((v - min) / range) * (height - 4) - 2;
  const line = data.map((v, i) => (i === 0 ? 'M' : 'L') + px(i).toFixed(1) + ' ' + py(v).toFixed(1)).join(' ');
  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width, height, display: 'block' }}>
      <path d={`${line} L${width} ${height} L0 ${height} Z`} fill={color} opacity="0.12" />
      <path d={line} fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

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