// Primitives.jsx — KpiCard, LineChart, BarChart, DonutChart, HeatmapChart, Alert

function KpiCard({ label, value, sub, delta, deltaDir, icon, variant, accentColor }) {
  const isDanger = variant === 'danger';
  const isBrand = variant === 'brand';
  const isWarning = variant === 'warning';
  const isSuccess = variant === 'success';

  const topBorder = isDanger ? '3px solid var(--danger-500)'
    : isWarning ? '3px solid var(--warning-500)'
    : isSuccess ? '3px solid var(--success-500)'
    : isBrand ? 'none' : '1px solid var(--border-subtle)';

  const bg = isBrand ? 'var(--brand-gradient)' : '#fff';
  const fg = isBrand ? '#fff' : 'var(--fg-1)';
  const fgMuted = isBrand ? 'rgba(255,255,255,0.8)' : 'var(--fg-3)';

  const deltaUp = deltaDir === 'up';
  const deltaDn = deltaDir === 'down';

  return (
    <div style={{
      background: bg,
      border: isBrand ? 'none' : '1px solid var(--border-subtle)',
      borderTop: topBorder,
      borderRadius: 12,
      padding: '18px 20px',
      boxShadow: isBrand ? 'var(--shadow-brand)' : 'var(--shadow-sm)',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: fgMuted }}>{label}</span>
        {icon && <span style={{ color: isBrand ? 'rgba(255,255,255,0.7)' : (accentColor || 'var(--primary-300)') }}><Icon name={icon} size={16} /></span>}
      </div>
      <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 30, lineHeight: '38px', letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums', color: fg, marginTop: 4 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: fgMuted, lineHeight: '18px' }}>{sub}</div>}
      {delta && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
          <span style={{
            background: isBrand ? 'rgba(255,255,255,0.18)' : (deltaUp ? 'var(--success-100)' : deltaDn ? 'var(--danger-100)' : 'var(--gray-100)'),
            color: isBrand ? '#fff' : (deltaUp ? 'var(--success-700)' : deltaDn ? 'var(--danger-700)' : 'var(--gray-600)'),
            fontSize: 11, fontWeight: 600, padding: '2px 7px', borderRadius: 9999,
          }}>{deltaUp ? '↑ ' : deltaDn ? '↓ ' : ''}{delta}</span>
        </div>
      )}
    </div>
  );
}

function LineChart({ series, labels, height = 200 }) {
  const W = 700, H = height;
  const pad = { l: 40, r: 16, t: 12, b: 28 };
  const all = series.flatMap(s => s.data);
  const maxV = Math.max(...all) * 1.12;
  const minV = 0;
  const n = series[0].data.length;
  const xStep = (W - pad.l - pad.r) / Math.max(n - 1, 1);
  const yFn = v => H - pad.b - ((v - minV) / (maxV - minV || 1)) * (H - pad.t - pad.b);
  const xFn = i => pad.l + i * xStep;
  const gridVals = [0, 0.25, 0.5, 0.75, 1].map(t => Math.round(minV + (maxV - minV) * t));

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
      {gridVals.map((g, i) => (
        <g key={i}>
          <line x1={pad.l} x2={W - pad.r} y1={yFn(g)} y2={yFn(g)} stroke="var(--gray-100)" strokeDasharray={i === 0 ? '0' : '4 3'} />
          <text x={pad.l - 6} y={yFn(g) + 4} fontSize="10" fill="var(--fg-4)" textAnchor="end" fontFamily="var(--font-mono)">{g}</text>
        </g>
      ))}
      {labels && labels.map((lab, i) => (
        <text key={i} x={xFn(i)} y={H - pad.b + 16} fontSize="10" fill="var(--fg-3)" textAnchor="middle" fontFamily="var(--font-sans)">{lab}</text>
      ))}
      {series.map((s, si) => {
        const pts = s.data.map((v, i) => `${xFn(i)},${yFn(v)}`);
        const areaD = `M ${xFn(0)},${yFn(0)} L ${pts.join(' L ')} L ${xFn(n - 1)},${yFn(0)} Z`;
        return (
          <g key={si}>
            {si === 0 && <path d={areaD} fill={s.color} opacity="0.07" />}
            <polyline points={pts.join(' ')} fill="none" stroke={s.color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
            {s.data.map((v, i) => <circle key={i} cx={xFn(i)} cy={yFn(v)} r="3.5" fill="#fff" stroke={s.color} strokeWidth="2" />)}
          </g>
        );
      })}
    </svg>
  );
}

function BarChart({ data, height = 200, horizontal = false }) {
  if (horizontal) {
    const W = 360, H = Math.max(height, data.length * 36 + 20);
    const pad = { l: 140, r: 40, t: 8, b: 8 };
    const maxV = Math.max(...data.map(d => d.value)) * 1.1;
    const barH = 18;
    const step = (H - pad.t - pad.b) / data.length;
    return (
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
        {data.map((d, i) => {
          const y = pad.t + i * step + (step - barH) / 2;
          const bw = ((d.value / maxV) * (W - pad.l - pad.r));
          const color = d.color || 'var(--primary-600)';
          return (
            <g key={i}>
              <text x={pad.l - 8} y={y + barH / 2 + 4} fontSize="11" fill="var(--fg-2)" textAnchor="end" fontFamily="var(--font-sans)" fontWeight="500">{d.label}</text>
              <rect x={pad.l} y={y} width={bw} height={barH} fill={color} opacity="0.85" rx="4" />
              <text x={pad.l + bw + 6} y={y + barH / 2 + 4} fontSize="11" fill="var(--fg-2)" fontFamily="var(--font-mono)" fontWeight="600">{d.value}</text>
            </g>
          );
        })}
      </svg>
    );
  }

  const W = 400, H = height;
  const pad = { l: 36, r: 12, t: 12, b: 32 };
  const maxV = Math.max(...data.map(d => d.value)) * 1.15;
  const bw = (W - pad.l - pad.r) / data.length * 0.62;
  const sw = (W - pad.l - pad.r) / data.length;
  const yFn = v => H - pad.b - (v / (maxV || 1)) * (H - pad.t - pad.b);

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
      {[0, 0.5, 1].map((t, i) => {
        const val = maxV * t;
        return (
          <g key={i}>
            <line x1={pad.l} x2={W - pad.r} y1={yFn(val)} y2={yFn(val)} stroke="var(--gray-100)" strokeDasharray={i === 0 ? '0' : '4 3'} />
            <text x={pad.l - 5} y={yFn(val) + 4} fontSize="10" fill="var(--fg-4)" textAnchor="end" fontFamily="var(--font-mono)">{Math.round(val)}</text>
          </g>
        );
      })}
      {data.map((d, i) => {
        const cx = pad.l + sw * i + sw / 2;
        const color = d.color || 'var(--primary-600)';
        const barTop = yFn(d.value);
        return (
          <g key={i}>
            <rect x={cx - bw / 2} y={barTop} width={bw} height={H - pad.b - barTop} fill={color} opacity="0.85" rx="4" />
            <text x={cx} y={H - pad.b + 17} fontSize="10" fill="var(--fg-3)" textAnchor="middle" fontFamily="var(--font-sans)">{d.label}</text>
          </g>
        );
      })}
    </svg>
  );
}

function DonutChart({ segments, size = 160, label, sub }) {
  const total = segments.reduce((a, s) => a + s.value, 0);
  let angle = -Math.PI / 2;
  const cx = size / 2, cy = size / 2;
  const R = size * 0.38, r = size * 0.24;

  const paths = segments.map(seg => {
    const sweep = (seg.value / total) * Math.PI * 2;
    const x1 = cx + R * Math.cos(angle);
    const y1 = cy + R * Math.sin(angle);
    const x2 = cx + R * Math.cos(angle + sweep);
    const y2 = cy + R * Math.sin(angle + sweep);
    const xi1 = cx + r * Math.cos(angle);
    const yi1 = cy + r * Math.sin(angle);
    const xi2 = cx + r * Math.cos(angle + sweep);
    const yi2 = cy + r * Math.sin(angle + sweep);
    const large = sweep > Math.PI ? 1 : 0;
    const d = `M ${xi1} ${yi1} L ${x1} ${y1} A ${R} ${R} 0 ${large} 1 ${x2} ${y2} L ${xi2} ${yi2} A ${r} ${r} 0 ${large} 0 ${xi1} ${yi1} Z`;
    angle += sweep;
    return { d, color: seg.color };
  });

  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
      {paths.map((p, i) => <path key={i} d={p.d} fill={p.color} opacity="0.9" />)}
      <text x={cx} y={cy - 6} textAnchor="middle" fontSize={size * 0.13} fontWeight="800" fontFamily="var(--font-sans)" fill="var(--fg-1)" letterSpacing="-0.02em">{label}</text>
      {sub && <text x={cx} y={cy + 12} textAnchor="middle" fontSize={size * 0.08} fill="var(--fg-3)" fontFamily="var(--font-sans)">{sub}</text>}
    </svg>
  );
}

function HeatmapChart({ data, days, hours }) {
  // data: array of {day, hour, value}
  const cellW = 28, cellH = 22, padL = 52, padT = 28;
  const W = padL + hours.length * cellW + 10;
  const H = padT + days.length * cellH + 10;
  const maxV = Math.max(...data.map(d => d.value));

  function cellColor(v) {
    if (v === 0) return 'var(--gray-100)';
    const t = v / maxV;
    if (t < 0.2) return '#e9d5f5';
    if (t < 0.4) return '#c084d4';
    if (t < 0.6) return '#9a3f90';
    if (t < 0.8) return '#7d2574';
    return '#4a1545';
  }

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
      {hours.map((h, hi) => (
        <text key={hi} x={padL + hi * cellW + cellW / 2} y={padT - 8} fontSize="9" fill="var(--fg-4)" textAnchor="middle" fontFamily="var(--font-mono)">{h}</text>
      ))}
      {days.map((d, di) => (
        <text key={di} x={padL - 6} y={padT + di * cellH + cellH / 2 + 4} fontSize="10" fill="var(--fg-3)" textAnchor="end" fontFamily="var(--font-sans)" fontWeight="500">{d}</text>
      ))}
      {data.map((cell, i) => {
        const di = days.indexOf(cell.day);
        const hi = hours.indexOf(cell.hour);
        if (di < 0 || hi < 0) return null;
        return (
          <rect key={i}
            x={padL + hi * cellW + 1} y={padT + di * cellH + 1}
            width={cellW - 2} height={cellH - 2}
            fill={cellColor(cell.value)} rx="3"
          />
        );
      })}
    </svg>
  );
}

function Alert({ level, title, body, action }) {
  const cfg = {
    danger:  { bg: 'var(--danger-50)',   border: 'var(--danger-200)',  icon: 'alert-triangle', color: 'var(--danger-700)',   iconBg: 'var(--danger-100)' },
    warning: { bg: 'var(--warning-50)',  border: 'var(--warning-200)', icon: 'alert-circle',   color: 'var(--warning-700)',  iconBg: 'var(--warning-100)' },
    info:    { bg: 'var(--info-50)',     border: 'var(--info-100)',    icon: 'info',           color: 'var(--info-700)',     iconBg: 'var(--info-100)' },
    success: { bg: 'var(--success-50)',  border: 'var(--success-100)', icon: 'check-circle-2', color: 'var(--success-700)',  iconBg: 'var(--success-100)' },
    reco:    { bg: 'var(--primary-50)',  border: 'var(--primary-200)', icon: 'sparkles',       color: 'var(--primary-700)',  iconBg: 'var(--primary-100)' },
  }[level] || {};
  return (
    <div style={{ display: 'flex', gap: 12, padding: '14px 16px', background: cfg.bg, border: `1px solid ${cfg.border}`, borderRadius: 10, alignItems: 'flex-start' }}>
      <div style={{ width: 32, height: 32, borderRadius: 8, background: cfg.iconBg, color: cfg.color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={cfg.icon} size={15} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: cfg.color, lineHeight: '20px' }}>{title}</div>
        {body && <div style={{ fontSize: 12, color: 'var(--fg-2)', marginTop: 3, lineHeight: '18px' }}>{body}</div>}
        {action && (
          <button style={{ marginTop: 8, fontSize: 12, fontWeight: 600, padding: '5px 12px', borderRadius: 6, border: 'none', cursor: 'pointer', background: cfg.color, color: '#fff', fontFamily: 'var(--font-sans)' }}>{action}</button>
        )}
      </div>
    </div>
  );
}

function SectionCard({ title, subtitle, children, style, action }) {
  return (
    <div style={{ background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 12, boxShadow: 'var(--shadow-sm)', ...style }}>
      <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>{title}</div>
          {subtitle && <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>{subtitle}</div>}
        </div>
        {action}
      </div>
      <div style={{ padding: '16px 20px' }}>{children}</div>
    </div>
  );
}

function Badge({ label, color = 'var(--primary-600)', bg = 'var(--primary-50)' }) {
  return (
    <span style={{ display: 'inline-block', fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 9999, background: bg, color: color }}>{label}</span>
  );
}

function StatRow({ label, value, sub, bar, barColor = 'var(--primary-500)', total }) {
  const pct = total ? (value / total) * 100 : bar;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, paddingBottom: 10, borderBottom: '1px solid var(--border-subtle)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 13, color: 'var(--fg-2)', fontWeight: 500 }}>{label}</span>
        <span style={{ fontSize: 13, fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: 'var(--fg-1)' }}>{typeof value === 'number' ? value.toLocaleString('es-AR') : value}</span>
      </div>
      {sub && <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{sub}</div>}
      {pct !== undefined && (
        <div style={{ height: 4, background: 'var(--gray-100)', borderRadius: 9999, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${Math.min(100, pct)}%`, background: barColor, borderRadius: 9999, transition: 'width 600ms var(--ease-out)' }} />
        </div>
      )}
    </div>
  );
}

Object.assign(window, { KpiCard, LineChart, BarChart, DonutChart, HeatmapChart, Alert, SectionCard, Badge, StatRow });
