// Brand-styled charts — monochrome, hard-edged, monospace labels.
// Built for the "Market" section on the homepage. Inputs are arrays; the
// chart computes its own grid + path.

function LineChart({
  data,                  // [{x, y, label}, …]
  width = 600,
  height = 280,
  yTicks = 5,
  highlightIndex = null, // index of point to highlight (amber)
  ariaLabel = 'chart',
}) {
  const padding = { top: 28, right: 36, bottom: 36, left: 56 };

  const highlightPoint = highlightIndex != null ? data[highlightIndex] : null;
  const innerW = width - padding.left - padding.right;
  const innerH = height - padding.top - padding.bottom;

  const xs = data.map(d => d.x);
  const ys = data.map(d => d.y);
  const xMin = Math.min(...xs), xMax = Math.max(...xs);
  const yMin = 0, yMax = Math.max(...ys);

  const xScale = x => padding.left + ((x - xMin) / (xMax - xMin)) * innerW;
  const yScale = y => padding.top + innerH - ((y - yMin) / (yMax - yMin)) * innerH;

  // Path string for the line.
  const path = data.map((d, i) =>
    `${i === 0 ? 'M' : 'L'} ${xScale(d.x).toFixed(1)} ${yScale(d.y).toFixed(1)}`
  ).join(' ');

  // Tick values on the Y axis — evenly spaced.
  const yTickVals = Array.from({ length: yTicks + 1 }, (_, i) =>
    Math.round((yMax * i) / yTicks)
  );

  const fmt = v => {
    if (v >= 1000) return `${(v / 1000).toFixed(v >= 1000 ? 1 : 0)}T`;
    return `$${v}B`;
  };

  return (
    <svg
      role="img" aria-label={ariaLabel}
      viewBox={`0 0 ${width} ${height}`}
      preserveAspectRatio="xMidYMid meet"
      style={{ width: '100%', height: 'auto', display: 'block' }}
    >
      {/* Outer frame */}
      <rect x="0.5" y="0.5" width={width - 1} height={height - 1}
            fill="none" stroke={SP_COL.grayDarker} strokeWidth="1" />

      {/* Y-axis ticks + horizontal grid lines */}
      {yTickVals.map((v, i) => {
        const y = yScale(v);
        const isHi = highlightPoint && Math.abs(v - highlightPoint.y) < (yMax / yTicks) / 2;
        return (
          <g key={`y${i}`}>
            <line x1={padding.left} x2={width - padding.right} y1={y} y2={y}
                  stroke={isHi ? SP_COL.accent : SP_COL.grayDarker} strokeWidth="1"
                  strokeDasharray={i === 0 ? '0' : '2 4'} />
            <text x={padding.left - 10} y={y + 4}
                  fill={isHi ? SP_COL.accent : SP_COL.grayDark} textAnchor="end"
                  style={{
                    fontFamily: SP_MONO_W, fontSize: 10,
                    letterSpacing: '0.1em',
                    fontWeight: isHi ? 700 : 400,
                  }}>{fmt(v)}</text>
          </g>
        );
      })}

      {/* X-axis labels + tick marks */}
      {data.map((d, i) => {
        const x = xScale(d.x);
        const isHi = i === highlightIndex;
        return (
          <g key={`x${i}`}>
            <line x1={x} x2={x}
                  y1={height - padding.bottom}
                  y2={height - padding.bottom + 5}
                  stroke={isHi ? SP_COL.accent : SP_COL.grayDark} strokeWidth="1" />
            <text x={x} y={height - padding.bottom + 20}
                  fill={isHi ? SP_COL.accent : SP_COL.grayLight} textAnchor="middle"
                  style={{
                    fontFamily: SP_MONO_W, fontSize: 10,
                    letterSpacing: '0.25em',
                    fontWeight: isHi ? 700 : 400,
                  }}>{d.label}</text>
          </g>
        );
      })}

      {/* The data line */}
      <path d={path} fill="none" stroke={SP_COL.white} strokeWidth="1.5" />

      {/* Data points */}
      {data.map((d, i) => {
        const isHighlight = i === highlightIndex;
        const color = isHighlight ? SP_COL.accent : SP_COL.white;
        const r = isHighlight ? 5 : 3;
        return (
          <g key={`pt${i}`}>
            <rect
              x={xScale(d.x) - r} y={yScale(d.y) - r}
              width={r * 2} height={r * 2}
              fill={color}
            />
            {isHighlight ? (
              <g>
                {/* Crosshair lines — leader to the X/Y axis labels. */}
                <line x1={xScale(d.x)} y1={yScale(d.y)}
                      x2={xScale(d.x)} y2={height - padding.bottom}
                      stroke={SP_COL.accent} strokeWidth="1"
                      strokeDasharray="2 3" />
                <line x1={xScale(d.x)} y1={yScale(d.y)}
                      x2={padding.left} y2={yScale(d.y)}
                      stroke={SP_COL.accent} strokeWidth="1"
                      strokeDasharray="2 3" />
              </g>
            ) : null}
          </g>
        );
      })}
    </svg>
  );
}

// Pie / donut chart — same monochrome treatment as LineChart.
function DonutChart({
  segments,            // [{label, value, accent?: boolean}, …]
  size = 280,
  thickness = 48,
  ariaLabel = 'donut chart',
}) {
  const total = segments.reduce((a, s) => a + s.value, 0);
  const cx = size / 2, cy = size / 2;
  const r = size / 2 - 12;
  const innerR = r - thickness;

  // Build arc path for each segment.
  let cursor = -Math.PI / 2; // start at 12 o'clock
  const arcs = segments.map((s, i) => {
    const portion = s.value / total;
    const angle = portion * Math.PI * 2;
    const a0 = cursor;
    const a1 = cursor + angle;
    cursor = a1;

    const large = angle > Math.PI ? 1 : 0;
    const x0 = cx + Math.cos(a0) * r, y0 = cy + Math.sin(a0) * r;
    const x1 = cx + Math.cos(a1) * r, y1 = cy + Math.sin(a1) * r;
    const ix0 = cx + Math.cos(a1) * innerR, iy0 = cy + Math.sin(a1) * innerR;
    const ix1 = cx + Math.cos(a0) * innerR, iy1 = cy + Math.sin(a0) * innerR;

    const d = [
      `M ${x0} ${y0}`,
      `A ${r} ${r} 0 ${large} 1 ${x1} ${y1}`,
      `L ${ix0} ${iy0}`,
      `A ${innerR} ${innerR} 0 ${large} 0 ${ix1} ${iy1}`,
      'Z',
    ].join(' ');
    return { ...s, d, portion };
  });

  // Color rules: accent segments → amber, others → white outline / gray fill.
  const fillFor = (a, i) =>
    a.accent ? SP_COL.accent : i === 0 ? SP_COL.white : SP_COL.grayDarker;
  const strokeFor = (a, i) =>
    a.accent ? SP_COL.accent : SP_COL.grayDark;

  return (
    <svg role="img" aria-label={ariaLabel}
         viewBox={`0 0 ${size} ${size}`}
         style={{ width: '100%', maxWidth: size, height: 'auto', display: 'block' }}>
      {arcs.map((a, i) => (
        <path key={i} d={a.d} fill={fillFor(a, i)} stroke={strokeFor(a, i)}
              strokeWidth="1" />
      ))}
      {/* Center label */}
      <text x={cx} y={cy - 4} textAnchor="middle" fill={SP_COL.white}
            style={{ fontFamily: SP_MONO_W, fontSize: 32, fontWeight: 600,
                     letterSpacing: '-0.01em' }}>
        {Math.round((arcs[0].portion) * 100)}%
      </text>
      <text x={cx} y={cy + 16} textAnchor="middle" fill={SP_COL.grayDark}
            style={{ fontFamily: SP_MONO_W, fontSize: 10,
                     letterSpacing: '0.3em', textTransform: 'uppercase' }}>
        {arcs[0].label}
      </text>
    </svg>
  );
}

// Legend rows for a chart — paired with DonutChart or any other viz.
function ChartLegend({ items }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {items.map((it, i) => (
        <div key={it.label} style={{
          display: 'flex', alignItems: 'baseline', gap: 12,
          fontFamily: SP_MONO_W, fontSize: 11, letterSpacing: '0.25em',
          textTransform: 'uppercase', color: SP_COL.grayLight,
        }}>
          <span style={{
            width: 10, height: 10, flexShrink: 0,
            background: it.accent ? SP_COL.accent : i === 0 ? SP_COL.white : SP_COL.grayDarker,
            border: `1px solid ${it.accent ? SP_COL.accent : SP_COL.grayDark}`,
            transform: 'translateY(1px)',
          }} />
          <span style={{ flex: 1 }}>{it.label}</span>
          <span style={{ color: SP_COL.white, fontWeight: 600 }}>{it.value}%</span>
        </div>
      ))}
    </div>
  );
}

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