/* global React */
// Charts — all hand-built SVG, using viz CSS vars so they reflow on theme change.

// Donut with center value
const Donut = ({ data, center, sub, size = 160 }) => {
  const total = data.reduce((s,d) => s + d.v, 0);
  const r = size/2 - 12;
  const cx = size/2, cy = size/2;
  let acc = 0;
  const circ = 2 * Math.PI * r;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--bg-sunk)" strokeWidth="14" />
      {data.map((d, i) => {
        const frac = d.v / total;
        const len = circ * frac;
        const off = -circ * acc / total;
        acc += d.v;
        return (
          <circle key={i} cx={cx} cy={cy} r={r} fill="none"
                  stroke={d.c} strokeWidth="14"
                  strokeDasharray={`${len} ${circ - len}`}
                  strokeDashoffset={off}
                  transform={`rotate(-90 ${cx} ${cy})`} />
        );
      })}
      <text x={cx} y={cy-2} textAnchor="middle" fontFamily="var(--font-display)"
            fontSize="22" fontWeight="600" fill="var(--text-1)" style={{letterSpacing:'-0.02em'}}>
        {center}
      </text>
      {sub && (
        <text x={cx} y={cy+16} textAnchor="middle" fontFamily="var(--font-mono)"
              fontSize="10" fill="var(--text-3)" style={{letterSpacing:'0.12em', textTransform:'uppercase'}}>
          {sub}
        </text>
      )}
    </svg>
  );
};

const Legend = ({ data }) => (
  <div className="chart-legend">
    {data.map((d,i) => (
      <div key={i} className="chart-legend__item" style={{width:'100%'}}>
        <span className="chart-legend__dot" style={{background: d.c}} />
        <span>{d.k}</span>
        <span className="chart-legend__value">{d.v.toFixed(1)}%</span>
      </div>
    ))}
  </div>
);

// Stacked bar (NAV history, 18 months × 4 classes)
const StackedBars = ({ data, keys = ['mining','realestate','commodities','preipo'],
                       colors = ['var(--viz-1)','var(--viz-4)','var(--viz-3)','var(--viz-5)'],
                       height = 200 }) => {
  const max = Math.max(...data.map(d => keys.reduce((s,k) => s + d[k], 0))) * 1.05;
  const pad = { l: 32, r: 8, t: 10, b: 28 };
  const w = 720, h = height;
  const bw = (w - pad.l - pad.r) / data.length;
  const bar = bw * 0.62;
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{display:'block'}}>
      {/* grid */}
      {[0,0.25,0.5,0.75,1].map((p,i) => (
        <g key={i}>
          <line x1={pad.l} x2={w-pad.r} y1={pad.t + (h-pad.t-pad.b)*(1-p)} y2={pad.t + (h-pad.t-pad.b)*(1-p)}
                stroke="var(--border)" strokeDasharray="2 3" />
          <text x={pad.l-6} y={pad.t + (h-pad.t-pad.b)*(1-p) + 3} textAnchor="end"
                fontFamily="var(--font-mono)" fontSize="9" fill="var(--text-3)">
            ${(max*p).toFixed(1)}M
          </text>
        </g>
      ))}
      {data.map((d,i) => {
        let y = h - pad.b;
        const x = pad.l + i*bw + (bw-bar)/2;
        return (
          <g key={i}>
            {keys.map((k, ki) => {
              const v = d[k];
              const seg = (v / max) * (h - pad.t - pad.b);
              const rect = <rect key={ki} x={x} y={y-seg} width={bar} height={seg} fill={colors[ki]}
                                 rx={ki === 0 ? 0 : 0}
                                 ry={ki === 0 ? 0 : 0}
                           />;
              y -= seg;
              return rect;
            })}
            <text x={x + bar/2} y={h - 10} textAnchor="middle" fontFamily="var(--font-mono)"
                  fontSize="9" fill="var(--text-3)">{d.m}</text>
          </g>
        );
      })}
    </svg>
  );
};

// Sparkline
const Sparkline = ({ data, color = 'var(--amber)', area = true, height = 28 }) => {
  const min = Math.min(...data), max = Math.max(...data);
  const w = 120, h = height;
  const pts = data.map((v,i) => {
    const x = (i / (data.length-1)) * w;
    const y = max === min ? h/2 : h - ((v-min)/(max-min)) * (h-4) - 2;
    return [x, y];
  });
  const d = pts.map((p,i) => (i === 0 ? 'M' : 'L') + p[0] + ' ' + p[1]).join(' ');
  const fill = d + ` L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="spark" preserveAspectRatio="none">
      {area && <path d={fill} fill={color} opacity="0.12" />}
      <path d={d} fill="none" stroke={color} strokeWidth="1.5" />
    </svg>
  );
};

// Horizontal bar list (for exposures)
const HBars = ({ rows, color = 'var(--amber)' }) => {
  const max = Math.max(...rows.map(r => r.v));
  return (
    <div style={{display:'flex', flexDirection:'column', gap:6}}>
      {rows.map((r,i) => (
        <div key={i} style={{display:'grid', gridTemplateColumns:'120px 1fr 56px', gap:12, alignItems:'center', fontSize:12}}>
          <span style={{color:'var(--text-2)'}}>{r.k}</span>
          <div style={{height:8, background:'var(--bg-sunk)', borderRadius:999, overflow:'hidden'}}>
            <div style={{height:'100%', width:`${(r.v/max)*100}%`, background: r.c || color, borderRadius:999}} />
          </div>
          <span className="num" style={{color:'var(--text-3)', textAlign:'right'}}>{r.v.toFixed(1)}%</span>
        </div>
      ))}
    </div>
  );
};

// Vesting curve (small area chart, used in partners card)
const VestCurve = ({ vested, height = 48 }) => {
  const w = 120;
  // Curve from 0 to vested fraction over 4 years
  const pts = [];
  const n = 40;
  for (let i = 0; i <= n; i++) {
    const t = i / n;
    // cliff 1yr then linear
    let v = t < 0.25 ? 0 : (t - 0.25) / 0.75;
    v = v * vested;
    pts.push([t*w, height - v*(height-4) - 2]);
  }
  const d = pts.map((p,i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const fill = d + ` L ${w} ${height} L 0 ${height} Z`;
  return (
    <svg width={w} height={height} viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{display:'block'}}>
      <path d={fill} fill="var(--amber)" opacity="0.15" />
      <path d={d} fill="none" stroke="var(--amber)" strokeWidth="1.5" />
    </svg>
  );
};

Object.assign(window, { Donut, Legend, StackedBars, Sparkline, HBars, VestCurve });
