// Dashboard charts (inline SVG, themed)

const useTheme = () => {
  const get = () => {
    const c = getComputedStyle(document.documentElement);
    return {
      ink: c.getPropertyValue('--ink').trim() || '#0E1418',
      muted: c.getPropertyValue('--muted').trim() || '#5A6770',
      rule: c.getPropertyValue('--rule').trim() || '#E5E0D6',
      teal: c.getPropertyValue('--teal').trim() || '#2E5762',
      rust: c.getPropertyValue('--rust').trim() || '#B5532E',
      surface: c.getPropertyValue('--surface').trim() || '#FFFFFF',
    };
  };
  const [t, setT] = React.useState(get);
  React.useEffect(() => {
    const ob = new MutationObserver(() => setT(get()));
    ob.observe(document.body, { attributes: true, attributeFilter: ['class'] });
    return () => ob.disconnect();
  }, []);
  return t;
};

const Sparkline = ({ data, color, width = 80, height = 24 }) => {
  const min = Math.min(...data), max = Math.max(...data);
  const x = i => (i * width) / (data.length - 1);
  const y = v => height - ((v - min) / Math.max(0.001, max - min)) * (height - 4) - 2;
  const path = data.map((v, i) => `${i === 0 ? "M" : "L"}${x(i)},${y(v)}`).join(" ");
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
};

const TrafficChart = ({ data, metric = "clicks", compare = true }) => {
  const t = useTheme();
  const W = 800, H = 280, P = 36;
  const max = Math.max(...data.map(d => d[metric])) * 1.15;
  const x = i => P + (i * (W - 2 * P)) / (data.length - 1);
  const y = v => H - P - (v / max) * (H - 2 * P);
  const path = data.map((d, i) => `${i === 0 ? "M" : "L"}${x(i)},${y(d[metric])}`).join(" ");
  const area = `${path} L${x(data.length - 1)},${H - P} L${x(0)},${H - P} Z`;

  // synthesized previous period (for compare)
  const prev = data.map(d => ({ ...d, [metric]: d[metric] * (0.82 + Math.random() * 0.08) }));
  const prevPath = prev.map((d, i) => `${i === 0 ? "M" : "L"}${x(i)},${y(d[metric])}`).join(" ");

  const fmt = n => n >= 1000 ? (n / 1000).toFixed(1) + "k" : Math.round(n);
  const ticks = [0, 0.25, 0.5, 0.75, 1].map(p => max * p);

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto" }}>
      <defs>
        <linearGradient id="trafGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={t.teal} stopOpacity="0.22"/>
          <stop offset="100%" stopColor={t.teal} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {ticks.map((v, i) => (
        <g key={i}>
          <line x1={P} x2={W - P} y1={y(v)} y2={y(v)} stroke={t.rule} strokeDasharray="2 4"/>
          <text x={P - 8} y={y(v) + 3} fontSize="10" fontFamily="var(--mono)" fill={t.muted} textAnchor="end">{fmt(v)}</text>
        </g>
      ))}
      <path d={area} fill="url(#trafGrad)"/>
      {compare && <path d={prevPath} fill="none" stroke={t.muted} strokeWidth="1.2" strokeDasharray="3 3" opacity="0.7"/>}
      <path d={path} fill="none" stroke={t.teal} strokeWidth="2"/>
      {/* anomaly markers */}
      {[14, 22].map(idx => (
        <g key={idx} transform={`translate(${x(idx)}, ${y(data[idx][metric])})`}>
          <circle r="6" fill={t.rust} fillOpacity="0.18"/>
          <circle r="3" fill={t.rust} stroke={t.surface} strokeWidth="1.5"/>
        </g>
      ))}
      {/* x-axis */}
      {[0, 7, 14, 21, 29].map(i => (
        <text key={i} x={x(i)} y={H - P + 16} fontSize="10" fontFamily="var(--mono)" fill={t.muted} textAnchor="middle">
          {`Apr ${i + 1}`}
        </text>
      ))}
    </svg>
  );
};

// Donut gauge (CWV)
const Donut = ({ value, max = 100, size = 96, label, sub, color }) => {
  const t = useTheme();
  const r = size / 2 - 6;
  const c = 2 * Math.PI * r;
  const off = c * (1 - value / max);
  return (
    <div className="gauge" style={{ width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={t.rule} strokeWidth="6"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color || t.teal} strokeWidth="6"
          strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
          transform={`rotate(-90 ${size/2} ${size/2})`}/>
      </svg>
      <div className="gauge__v">
        <strong>{label || value}</strong>
        {sub && <small>{sub}</small>}
      </div>
    </div>
  );
};

const HBar = ({ data, max, accentIdx }) => {
  const t = useTheme();
  const W = 480, rowH = 36, P = 8;
  const H = data.length * rowH + P * 2;
  const xMax = W - 240;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: H }}>
      {data.map((d, i) => {
        const w = (d.value / max) * xMax;
        const isYou = i === accentIdx;
        return (
          <g key={d.label} transform={`translate(0, ${P + i * rowH})`}>
            <text x="0" y="20" fontSize="12" fontFamily="var(--sans)" fontWeight="500" fill={t.ink}>{d.label}</text>
            <rect x="120" y="10" width={xMax} height="14" rx="3" fill={t.rule} opacity="0.5"/>
            <rect x="120" y="10" width={w} height="14" rx="3" fill={isYou ? t.rust : t.teal}/>
            <text x={W} y="20" fontSize="11" fontFamily="var(--mono)" fill={t.muted} textAnchor="end">{d.display}</text>
          </g>
        );
      })}
    </svg>
  );
};

Object.assign(window, { Sparkline, TrafficChart, Donut, HBar, useTheme });
