/* ═══════════════════════════════════════════════════════
   AYRA Admin — Chart Components (SVG-based)
   ═══════════════════════════════════════════════════════ */

// ── Line Chart ──────────────────────────────────────────
function AyraLineChart({ data, width = 400, height = 120, color = '#3b72f6', gradient = true, label }) {
  if (!data || data.length < 2) return null;
  const max = Math.max(...data.map(d => d.value));
  const min = Math.min(...data.map(d => d.value));
  const range = max - min || 1;
  const padX = 8; const padY = 12;
  const chartW = width - padX * 2;
  const chartH = height - padY * 2;
  const points = data.map((d, i) => ({
    x: padX + (i / (data.length - 1)) * chartW,
    y: padY + (1 - (d.value - min) / range) * chartH,
    ...d
  }));
  const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');
  const areaD = pathD + ` L${points[points.length-1].x.toFixed(1)},${(padY+chartH).toFixed(1)} L${points[0].x.toFixed(1)},${(padY+chartH).toFixed(1)} Z`;
  const gradId = `lg-${color.replace('#','')}-${Math.random().toString(36).slice(2,6)}`;
  return (
    <svg width={width} height={height} style={{overflow:'visible', display:'block'}}>
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.25"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {gradient && <path d={areaD} fill={`url(#${gradId})`}/>}
      <path d={pathD} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
      {points.map((p, i) => (
        <circle key={i} cx={p.x} cy={p.y} r="2.5" fill={color} fillOpacity={i === points.length-1 ? 1 : 0}/>
      ))}
    </svg>
  );
}

// ── Stacked Bar Chart ────────────────────────────────────
function AyraBarChart({ data, width = 400, height = 120, colors = ['#3b72f6','#e8960d','#16a34a'] }) {
  if (!data || data.length === 0) return null;
  const maxTotal = Math.max(...data.map(d => d.values.reduce((a,b)=>a+b,0)));
  const padX = 8; const padY = 8;
  const chartW = width - padX * 2;
  const chartH = height - padY * 2;
  const barW = Math.max(4, (chartW / data.length) * 0.6);
  const gap = chartW / data.length;
  return (
    <svg width={width} height={height} style={{overflow:'visible', display:'block'}}>
      {data.map((d, i) => {
        const total = d.values.reduce((a,b)=>a+b,0);
        const x = padX + i * gap + (gap - barW) / 2;
        let yOffset = padY + chartH;
        return (
          <g key={i}>
            {d.values.map((v, j) => {
              const barH = (v / maxTotal) * chartH;
              yOffset -= barH;
              return (
                <rect key={j} x={x} y={yOffset} width={barW} height={barH}
                  fill={colors[j % colors.length]} opacity={0.85}
                  rx="1"
                />
              );
            })}
          </g>
        );
      })}
    </svg>
  );
}

// ── Mini Sparkline ───────────────────────────────────────
function AyraMiniLine({ data, width = 80, height = 28, color = '#3b72f6', trend }) {
  if (!data || data.length < 2) return null;
  const max = Math.max(...data); const min = Math.min(...data);
  const range = max - min || 1;
  const points = data.map((v, i) => ({
    x: (i / (data.length - 1)) * width,
    y: height - ((v - min) / range) * height
  }));
  const d = points.map((p,i) => `${i===0?'M':'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');
  const trendColor = trend === 'up' ? '#4ade80' : trend === 'down' ? '#f87171' : color;
  return (
    <svg width={width} height={height} style={{overflow:'visible', display:'block'}}>
      <path d={d} fill="none" stroke={trendColor} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

// ── Donut Chart ──────────────────────────────────────────
function AyraDonut({ value, max = 100, size = 56, strokeWidth = 6, color = '#3b72f6', bg = '#1c2d4a', label }) {
  const r = (size - strokeWidth) / 2;
  const circ = 2 * Math.PI * r;
  const pct = Math.min(value / max, 1);
  const dash = pct * circ;
  const cx = size / 2; const cy = size / 2;
  return (
    <svg width={size} height={size} style={{transform:'rotate(-90deg)', display:'block'}}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={bg} strokeWidth={strokeWidth}/>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={color} strokeWidth={strokeWidth}
        strokeDasharray={`${dash.toFixed(2)} ${circ.toFixed(2)}`}
        strokeLinecap="round"
        style={{transition:'stroke-dasharray 0.6s cubic-bezier(0.2,0,0,1)'}}
      />
    </svg>
  );
}

// ── Progress Bar ─────────────────────────────────────────
function AyraProgress({ value, max = 100, color, height = 4, showLabel = false }) {
  const pct = Math.min((value / max) * 100, 100);
  const barColor = color || (pct >= 90 ? '#ef4444' : pct >= 70 ? '#f59e0b' : '#3b72f6');
  return (
    <div style={{width:'100%'}}>
      {showLabel && (
        <div style={{display:'flex', justifyContent:'space-between', marginBottom:4, fontSize:11, color:'var(--text-secondary)'}}>
          <span className="mono">{value.toLocaleString()}</span>
          <span className="mono">{pct.toFixed(0)}%</span>
        </div>
      )}
      <div style={{height, background:'var(--border-subtle)', borderRadius:height/2, overflow:'hidden'}}>
        <div style={{
          height:'100%', width:`${pct}%`,
          background: barColor,
          borderRadius: height/2,
          transition:'width 0.6s cubic-bezier(0.2,0,0,1)'
        }}/>
      </div>
    </div>
  );
}

// ── Heatmap Calendar ─────────────────────────────────────
function AyraHeatmap({ data, cols = 12, rows = 7 }) {
  const max = Math.max(...(data || [1]));
  const cells = Array.from({length: cols * rows}, (_, i) => data?.[i] ?? 0);
  const colors = ['#141f35','#1a3060','#1e4a96','#2563d8','#3b82f6','#60a5fa'];
  return (
    <svg width={cols * 12 + (cols-1)*2} height={rows * 12 + (rows-1)*2} style={{display:'block'}}>
      {cells.map((v, i) => {
        const col = i % cols; const row = Math.floor(i / cols);
        const tier = max > 0 ? Math.round((v / max) * (colors.length - 1)) : 0;
        return (
          <rect key={i} x={col * 14} y={row * 14} width={12} height={12}
            rx={2} fill={colors[tier]}
          />
        );
      })}
    </svg>
  );
}

// Export all to window for cross-script access
Object.assign(window, {
  AyraLineChart,
  AyraBarChart,
  AyraMiniLine,
  AyraDonut,
  AyraProgress,
  AyraHeatmap
});
