// WiseTokens — micro-charts (sparkline, bar chart, donut)

function Sparkline({ data, height = 40, stroke = 'var(--accent)', fill = true }) {
  const w = 200, h = height;
  if (!data || data.length === 0) return null;
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * (h - 6) - 3;
    return [x, y];
  });
  const line = pts.map(([x,y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(' ');
  const area = line + ` L${w},${h} L0,${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height, display: 'block' }}>
      {fill && <path d={area} fill={stroke} opacity="0.12"/>}
      <path d={line} fill="none" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function Bars({ data, height = 120, color = 'var(--accent)', labels }) {
  const max = Math.max(...data) || 1;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height }}>
        {data.map((v, i) => (
          <div key={i} style={{
            flex: 1,
            height: `${Math.max(2, (v / max) * height)}px`,
            background: color,
            borderRadius: '2px 2px 0 0',
            opacity: 0.85,
            transition: 'height 0.2s',
          }} title={v}/>
        ))}
      </div>
      {labels && (
        <div style={{ display: 'flex', gap: 3, marginTop: 6, fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
          {labels.map((l, i) => (
            <div key={i} style={{ flex: 1, textAlign: 'center' }}>{i % Math.ceil(labels.length/6) === 0 ? l : ''}</div>
          ))}
        </div>
      )}
    </div>
  );
}

function StackedBars({ series, labels, height = 160, colors }) {
  // series: [{name, data[]}, ...], stacked
  const total = labels.map((_, i) => series.reduce((s, sr) => s + sr.data[i], 0));
  const max = Math.max(...total) || 1;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height }}>
        {labels.map((lab, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column-reverse', height: '100%', gap: 1 }}>
            {series.map((sr, si) => {
              const h = (sr.data[i] / max) * height;
              if (h < 0.5) return null;
              return <div key={si} style={{ height: h + 'px', background: colors[si], borderRadius: si === series.length-1 ? '2px 2px 0 0' : 0 }}/>;
            })}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 4, marginTop: 8, fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
        {labels.map((l, i) => (
          <div key={i} style={{ flex: 1, textAlign: 'center' }}>{i % Math.max(1, Math.ceil(labels.length/8)) === 0 ? l : ''}</div>
        ))}
      </div>
    </div>
  );
}

function Donut({ segments, size = 120, stroke = 18, label, sub }) {
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke}/>
        {segments.map((seg, i) => {
          const len = (seg.value / total) * c;
          const el = (
            <circle key={i}
              cx={size/2} cy={size/2} r={r}
              fill="none"
              stroke={seg.color}
              strokeWidth={stroke}
              strokeDasharray={`${len} ${c - len}`}
              strokeDashoffset={-offset}
              transform={`rotate(-90 ${size/2} ${size/2})`}
              strokeLinecap="butt"
            />
          );
          offset += len;
          return el;
        })}
      </svg>
      {label && (
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 20, fontWeight: 600, letterSpacing: '-0.02em' }}>{label}</div>
            {sub && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{sub}</div>}
          </div>
        </div>
      )}
    </div>
  );
}

// World map sparkline - simple rows
function RegionBar({ regions }) {
  const max = Math.max(...regions.map(r => r.pct));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {regions.map(r => (
        <div key={r.name}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
            <span>{r.name}</span>
            <span className="mono tabular dim">{r.pct}%</span>
          </div>
          <div style={{ height: 6, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ width: `${(r.pct/max)*100}%`, height: '100%', background: r.color || 'var(--accent)' }}/>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Sparkline, Bars, StackedBars, Donut, RegionBar });
