/* ============================================
   VELOX — Icons + chart components
   ============================================ */

// Lucide-style stroke icons. Single component, takes name prop.
const Icon = ({ name, size = 18, stroke = 2 }) => {
  const props = {
    width: size, height: size, viewBox: "0 0 24 24",
    fill: "none", stroke: "currentColor",
    strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round",
  };
  const paths = {
    dashboard:   <><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></>,
    chart:       <><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-7"/></>,
    options:     <><path d="M3 12h4l3-9 4 18 3-9h4"/></>,
    positions:   <><rect x="3" y="6" width="18" height="14" rx="2"/><path d="M3 10h18"/><path d="M8 6V4h8v2"/></>,
    bot:         <><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M12 4v4"/><circle cx="9" cy="14" r="1.2"/><circle cx="15" cy="14" r="1.2"/><path d="M2 14h2M20 14h2"/></>,
    activity:    <><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></>,
    list:        <><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="3.5" cy="6" r="1.2"/><circle cx="3.5" cy="12" r="1.2"/><circle cx="3.5" cy="18" r="1.2"/></>,
    history:     <><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 2"/></>,
    backtest:    <><path d="M4 20V8"/><path d="M10 20V4"/><path d="M16 20v-9"/><path d="M22 20H2"/></>,
    book:        <><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></>,
    bell:        <><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a2 2 0 0 0 3.4 0"/></>,
    search:      <><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></>,
    sun:         <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>,
    moon:        <><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79"/></>,
    settings:    <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></>,
    plus:        <><path d="M12 5v14M5 12h14"/></>,
    arrowUp:     <><path d="M12 19V5M5 12l7-7 7 7"/></>,
    arrowDown:   <><path d="M12 5v14M19 12l-7 7-7-7"/></>,
    play:        <><polygon points="6 4 20 12 6 20 6 4"/></>,
    pause:       <><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></>,
    eye:         <><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7"/><circle cx="12" cy="12" r="3"/></>,
    x:           <><path d="M18 6 6 18M6 6l12 12"/></>,
    trend:       <><path d="M23 6l-9.5 9.5-5-5L1 18"/><path d="M17 6h6v6"/></>,
    shield:      <><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/></>,
    chevronRight:<><path d="m9 18 6-6-6-6"/></>,
    info:        <><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></>,
    check:       <><path d="m20 6-11 11-5-5"/></>,
    layers:      <><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></>,
    refresh:     <><path d="M21 12a9 9 0 0 1-9 9 9 9 0 0 1-6.7-3L3 15"/><path d="M3 12a9 9 0 0 1 9-9 9 9 0 0 1 6.7 3L21 9"/><path d="M21 3v6h-6M3 21v-6h6"/></>,
    filter:      <><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></>,
    download:    <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    lock:        <><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>,
    user:        <><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></>,
    flash:       <><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></>,
    target:      <><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></>,
  };
  return <svg {...props}>{paths[name] || null}</svg>;
};

/* ============================================
   Sparkline
   ============================================ */
const Sparkline = ({ data, width = 64, height = 22, color }) => {
  if (!data || data.length < 2) return null;
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const step = width / (data.length - 1);
  const pts = data.map((v, i) => `${(i * step).toFixed(1)},${(height - ((v - min) / range) * height).toFixed(1)}`).join(" ");
  const up = data[data.length - 1] >= data[0];
  const c = color || (up ? "var(--up)" : "var(--down)");
  return (
    <svg width={width} height={height} className="spark" style={{display:"block"}}>
      <polyline points={pts} fill="none" stroke={c} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
};

/* ============================================
   Area chart (P&L curve)
   ============================================ */
const AreaChart = ({ data, height = 220, valueKey = "cumul", labelKey = "date" }) => {
  if (!data || !data.length) return null;
  const W = 800, H = height, pad = { l: 50, r: 12, t: 12, b: 28 };
  const xs = data.map((_, i) => i);
  const ys = data.map(d => d[valueKey]);
  const minY = Math.min(0, ...ys), maxY = Math.max(...ys);
  const rangeY = (maxY - minY) || 1;
  const sx = i => pad.l + (i / (data.length - 1)) * (W - pad.l - pad.r);
  const sy = v => pad.t + (1 - (v - minY) / rangeY) * (H - pad.t - pad.b);
  const linePts = data.map((d, i) => `${sx(i)},${sy(d[valueKey])}`).join(" ");
  const areaPts = `${sx(0)},${sy(minY)} ${linePts} ${sx(data.length - 1)},${sy(minY)}`;
  // grid: 4 horizontal lines
  const ticks = 4;
  const gridLines = [];
  for (let i = 0; i <= ticks; i++) {
    const y = pad.t + (i / ticks) * (H - pad.t - pad.b);
    const v = maxY - (i / ticks) * rangeY;
    gridLines.push({ y, v });
  }
  const lastUp = ys[ys.length - 1] >= 0;
  const stroke = lastUp ? "var(--up)" : "var(--down)";
  const fill   = lastUp ? "var(--up-soft)" : "var(--down-soft)";
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{display:"block"}}>
      {gridLines.map((g, i) => (
        <g key={i}>
          <line x1={pad.l} x2={W - pad.r} y1={g.y} y2={g.y} stroke="var(--border)" strokeWidth="1" strokeDasharray="2 4"/>
          <text x={pad.l - 6} y={g.y + 3} fontSize="10" fill="var(--text-3)" textAnchor="end" fontFamily="var(--font-mono)">
            {g.v >= 1000 ? (g.v / 1000).toFixed(1) + "k" : g.v.toFixed(0)}
          </text>
        </g>
      ))}
      <polygon points={areaPts} fill={fill} />
      <polyline points={linePts} fill="none" stroke={stroke} strokeWidth="2" strokeLinejoin="round"/>
      {data.length <= 30 && data.map((d, i) => {
        if (!d[labelKey] || i % Math.ceil(data.length / 8) !== 0) return null;
        const date = d[labelKey];
        const lbl = date instanceof Date ? `${date.getDate()}/${date.getMonth()+1}` : String(date);
        return <text key={i} x={sx(i)} y={H - 8} fontSize="10" fill="var(--text-3)" textAnchor="middle">{lbl}</text>;
      })}
    </svg>
  );
};

/* Bar chart for daily P&L */
const BarChart = ({ data, height = 200, valueKey = "pnl" }) => {
  if (!data || !data.length) return null;
  const W = 800, H = height, pad = { l: 44, r: 8, t: 8, b: 24 };
  const ys = data.map(d => d[valueKey]);
  const minY = Math.min(0, ...ys), maxY = Math.max(0, ...ys);
  const rangeY = (maxY - minY) || 1;
  const bw = (W - pad.l - pad.r) / data.length;
  const sy = v => pad.t + (1 - (v - minY) / rangeY) * (H - pad.t - pad.b);
  const zeroY = sy(0);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{display:"block"}}>
      <line x1={pad.l} x2={W - pad.r} y1={zeroY} y2={zeroY} stroke="var(--border)" strokeWidth="1"/>
      {[0.25, 0.5, 0.75, 1].map((p, i) => {
        const v = maxY - p * rangeY;
        const y = sy(v);
        return (
          <g key={i}>
            <line x1={pad.l} x2={W-pad.r} y1={y} y2={y} stroke="var(--border)" strokeDasharray="2 4" strokeWidth="1"/>
            <text x={pad.l - 6} y={y+3} fontSize="10" fill="var(--text-3)" textAnchor="end" fontFamily="var(--font-mono)">
              {v >= 1000 ? (v/1000).toFixed(1)+"k" : v.toFixed(0)}
            </text>
          </g>
        );
      })}
      {data.map((d, i) => {
        const v = d[valueKey];
        const x = pad.l + i * bw + bw * 0.18;
        const w = bw * 0.64;
        const y = v >= 0 ? sy(v) : zeroY;
        const h = Math.abs(sy(v) - zeroY);
        return <rect key={i} x={x} y={y} width={w} height={h} fill={v >= 0 ? "var(--up)" : "var(--down)"} rx="2"/>;
      })}
    </svg>
  );
};

/* Candlestick chart */
const Candlestick = ({ candles, height = 280 }) => {
  if (!candles || !candles.length) return null;
  const W = 880, H = height, pad = { l: 50, r: 8, t: 8, b: 22 };
  const highs = candles.map(c => c.h), lows = candles.map(c => c.l);
  const maxY = Math.max(...highs), minY = Math.min(...lows);
  const range = (maxY - minY) || 1;
  const cw = (W - pad.l - pad.r) / candles.length;
  const sy = v => pad.t + (1 - (v - minY) / range) * (H - pad.t - pad.b);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{display:"block"}}>
      {[0.2, 0.4, 0.6, 0.8].map((p, i) => {
        const v = maxY - p * range;
        const y = sy(v);
        return (
          <g key={i}>
            <line x1={pad.l} x2={W-pad.r} y1={y} y2={y} stroke="var(--border)" strokeDasharray="2 4" strokeWidth="1"/>
            <text x={pad.l - 6} y={y+3} fontSize="10" fill="var(--text-3)" textAnchor="end" fontFamily="var(--font-mono)">{v.toFixed(0)}</text>
          </g>
        );
      })}
      {candles.map((c, i) => {
        const x = pad.l + i * cw + cw * 0.5;
        const up = c.c >= c.o;
        const color = up ? "var(--up)" : "var(--down)";
        const yHi = sy(c.h), yLo = sy(c.l);
        const yOpen = sy(c.o), yClose = sy(c.c);
        const top = Math.min(yOpen, yClose), bot = Math.max(yOpen, yClose);
        const bw = Math.max(2, cw * 0.65);
        return (
          <g key={i}>
            <line x1={x} x2={x} y1={yHi} y2={yLo} stroke={color} strokeWidth="1"/>
            <rect x={x - bw/2} y={top} width={bw} height={Math.max(1, bot - top)} fill={color}/>
          </g>
        );
      })}
    </svg>
  );
};

/* Donut chart */
const Donut = ({ segments, size = 180, thickness = 22 }) => {
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  const r = size / 2 - thickness / 2;
  const cx = size / 2, cy = size / 2;
  let acc = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--surface-2)" strokeWidth={thickness}/>
      {segments.map((s, i) => {
        const frac = s.value / total;
        const len = 2 * Math.PI * r;
        const dash = len * frac;
        const offset = len * acc;
        acc += frac;
        return (
          <circle key={i} cx={cx} cy={cy} r={r} fill="none"
            stroke={s.color} strokeWidth={thickness}
            strokeDasharray={`${dash} ${len - dash}`}
            strokeDashoffset={-offset}
            transform={`rotate(-90 ${cx} ${cy})`}
            strokeLinecap="butt"
          />
        );
      })}
    </svg>
  );
};

Object.assign(window, { Icon, Sparkline, AreaChart, BarChart, Candlestick, Donut });
