// Chart primitives: sparkline, donut, bar list, funnel, monthly columns
const { useMemo } = React;

const STATUS_COLOR = {
  CLOSED: 'var(--closed)',
  PENDING: 'var(--pending)',
  ACTIVE: 'var(--active)',
  DFT: 'var(--dft)',
};

const PALETTE = ['#2f5d3a', '#c7823a', '#3557a8', '#a3342b', '#6c7a89', '#8e5572', '#417b7d', '#b88118', '#5a6b3e'];

function fmtMoney(n) {
  if (!n && n !== 0) return '–';
  if (n >= 1e6) return '$' + (n/1e6).toFixed(2) + 'M';
  if (n >= 1e3) return '$' + Math.round(n/1e3) + 'K';
  return '$' + Math.round(n);
}
function fmtMoneyFull(n) {
  if (!n && n !== 0) return '–';
  return '$' + Math.round(n).toLocaleString();
}
window.fmtMoney = fmtMoney;
window.fmtMoneyFull = fmtMoneyFull;
window.PALETTE = PALETTE;
window.STATUS_COLOR = STATUS_COLOR;

// ---------- Sparkline ----------
function Sparkline({ data, width = 120, height = 32, color = 'var(--accent)' }) {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data, 1);
  const step = width / Math.max(data.length - 1, 1);
  const pts = data.map((v, i) => [i * step, height - (v / max) * (height - 4) - 2]);
  const d = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ',' + p[1].toFixed(1)).join(' ');
  const areaD = d + ` L ${width},${height} L 0,${height} Z`;
  return (
    <svg className="spark" width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <path d={areaD} fill={color} opacity="0.12" />
      <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.2" fill={color} />
    </svg>
  );
}
window.Sparkline = Sparkline;

// ---------- Donut ----------
function Donut({ segments, size = 160, stroke = 22, centerLabel, centerValue }) {
  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 className="donut-wrap">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--rule-2)" strokeWidth={stroke} />
        {segments.map((s, i) => {
          const len = (s.value / total) * c;
          const dashArr = `${len} ${c - len}`;
          const dashOff = c - offset;
          offset += len;
          return (
            <circle
              key={i}
              cx={size/2} cy={size/2} r={r}
              fill="none" stroke={s.color || PALETTE[i % PALETTE.length]}
              strokeWidth={stroke}
              strokeDasharray={dashArr}
              strokeDashoffset={dashOff}
              transform={`rotate(-90 ${size/2} ${size/2})`}
              style={{ transition: 'stroke-dasharray 0.5s ease' }}
            />
          );
        })}
        <text x={size/2} y={size/2 - 4} textAnchor="middle" fontSize="11" fill="var(--ink-3)" fontFamily="var(--font-sans)" letterSpacing="0.08em">{(centerLabel || '').toUpperCase()}</text>
        <text x={size/2} y={size/2 + 16} textAnchor="middle" fontSize="22" fill="var(--ink)" fontFamily="var(--font-serif)" fontWeight="600">{centerValue}</text>
      </svg>
      <div className="donut-legend" style={{flex: 1}}>
        {segments.map((s, i) => (
          <div className="donut-legend-row" key={i}>
            <span className="sw" style={{background: s.color || PALETTE[i % PALETTE.length]}}></span>
            <span>{s.label}</span>
            <span className="val">
              {s.value}
              {s.volume != null && <span style={{color:'var(--ink-3)', marginLeft:6, fontSize:11}}>({fmtMoney(s.volume)})</span>}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}
window.Donut = Donut;

// ---------- Horizontal bar list ----------
function BarList({ rows, format = 'num', max, subFormat }) {
  const m = max || Math.max(...rows.map(r => r.value), 1);
  return (
    <div className="chart-wrap">
      {rows.map((r, i) => (
        <div key={i} style={{padding:'4px 0'}}>
          <div className="bar-row">
            <div className="bar-label">{r.label}</div>
            <div className="bar-track">
              <div className="bar-fill" style={{ width: (r.value / m * 100) + '%', background: r.color || 'var(--accent)' }}></div>
            </div>
            <div className="bar-value">
              {format === 'money' ? fmtMoney(r.value) : r.value}
              {r.count != null && <span style={{color:'var(--ink-3)', marginLeft:4, fontWeight:400}}>({r.count})</span>}
            </div>
          </div>
          {r.sub != null && (
            <div className="bar-row" style={{padding:'0 0 4px', opacity:0.7}}>
              <div className="bar-label" style={{fontSize:10.5, color:'var(--ink-3)', letterSpacing:'0.04em'}}>{r.subLabel || 'Prior YTD'}</div>
              <div className="bar-track" style={{height:4, opacity:0.55}}>
                <div className="bar-fill" style={{ width: (r.sub / m * 100) + '%', background: 'var(--ink-3)' }}></div>
              </div>
              <div className="bar-value" style={{fontSize:11, color:'var(--ink-3)'}}>
                {(subFormat || format) === 'money' ? fmtMoney(r.sub) : r.sub}
                {r.subCount != null && <span style={{marginLeft:4}}>({r.subCount})</span>}
              </div>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
window.BarList = BarList;

// ---------- Funnel ----------
function Funnel({ rows }) {
  const max = Math.max(...rows.map(r => r.value), 1);
  return (
    <div className="funnel">
      {rows.map((r, i) => (
        <div className="funnel-row" key={i}>
          <div className="funnel-label">{r.label}</div>
          <div className="funnel-bar">
            <div className="funnel-fill" style={{ width: (r.value / max * 100) + '%', background: r.color || PALETTE[i % PALETTE.length] }}>
              {r.value}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
window.Funnel = Funnel;

// ---------- Monthly column chart (Volume compare) ----------
function ColumnChart({ series, labels, height = 180, showValues = false, valueFormat = 'num' }) {
  // series: [{name, color, data[12]}...]
  const max = Math.max(...series.flatMap(s => s.data), 1);
  const W = 560, pad = 24;
  const topPad = showValues ? 16 : 4;
  const innerW = W - pad * 2;
  const groupW = innerW / labels.length;
  const barW = Math.max((groupW - 6) / series.length - 2, 4);
  const fmt = (v) => !v ? '' : (valueFormat === 'money' ? fmtMoney(v) : v);
  return (
    <div>
      <svg width="100%" viewBox={`0 0 ${W} ${height + 28}`} preserveAspectRatio="xMidYMid meet">
        {[0, 0.5, 1].map((t, i) => (
          <line key={i}
            x1={pad} x2={W - pad}
            y1={height - height * t + topPad} y2={height - height * t + topPad}
            stroke="var(--rule-2)" strokeWidth="1" />
        ))}
        {series.map((s, si) => (
          s.data.map((v, i) => {
            const h = (v / max) * (height - topPad - 4);
            const x = pad + i * groupW + 3 + si * (barW + 2);
            const y = height - h + topPad;
            return (
              <g key={si+'-'+i}>
                <rect x={x} y={y} width={barW} height={h} rx="1.5" fill={s.color} opacity={v ? 1 : 0.25} />
                {showValues && v > 0 && (
                  <text x={x + barW/2} y={y - 3} textAnchor="middle" fontSize="9"
                    fill={s.color} fontFamily="var(--font-mono)" fontWeight="600">
                    {fmt(v)}
                  </text>
                )}
              </g>
            );
          })
        ))}
        {labels.map((l, i) => (
          <text key={i}
            x={pad + i * groupW + groupW/2}
            y={height + 20}
            textAnchor="middle" fontSize="10" fill="var(--ink-3)"
            fontFamily="var(--font-mono)" letterSpacing="0.05em">
            {l}
          </text>
        ))}
      </svg>
      <div style={{display:'flex', gap:14, justifyContent:'center', marginTop:4, fontSize:12}}>
        {series.map((s, i) => (
          <div key={i} style={{display:'flex', alignItems:'center', gap:6, color:'var(--ink-2)'}}>
            <span style={{display:'inline-block', width:10, height:10, borderRadius:2, background:s.color}}></span>
            {s.name}
          </div>
        ))}
      </div>
    </div>
  );
}
window.ColumnChart = ColumnChart;
