/* AAU CRM — lightweight SVG charts. Exposes on window. */
(function () {
  const GREEN = '#008060', INK = '#303030', GRID = '#ebebeb', SUB = '#8a8a8a';

  function LineChart({ data, height = 220, color = INK, markers = [], fmt }) {
    const w = 640, h = height, pad = { l: 44, r: 16, t: 16, b: 28 };
    const max = Math.max(...data.map(d => d.v)) * 1.1 || 1;
    const min = 0;
    const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
    const x = i => pad.l + (i / (data.length - 1)) * iw;
    const y = v => pad.t + ih - ((v - min) / (max - min)) * ih;
    const path = data.map((d, i) => (i ? 'L' : 'M') + x(i) + ',' + y(d.v)).join(' ');
    const area = path + ` L${x(data.length - 1)},${pad.t + ih} L${x(0)},${pad.t + ih} Z`;
    const ticks = 4;
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height }}>
        <defs><linearGradient id="lg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={color} stopOpacity="0.14" /><stop offset="1" stopColor={color} stopOpacity="0" /></linearGradient></defs>
        {Array.from({ length: ticks + 1 }).map((_, i) => { const v = min + (max - min) * (i / ticks); const yy = y(v); return <g key={i}><line x1={pad.l} y1={yy} x2={w - pad.r} y2={yy} stroke={GRID} /><text x={pad.l - 8} y={yy + 3} textAnchor="end" fontSize="10" fill={SUB}>{fmt ? fmt(v) : Math.round(v)}</text></g>; })}
        <path d={area} fill="url(#lg)" />
        <path d={path} fill="none" stroke={color} strokeWidth="2.2" strokeLinejoin="round" strokeLinecap="round" />
        {data.map((d, i) => i % Math.ceil(data.length / 8) === 0 && <text key={i} x={x(i)} y={h - 8} textAnchor="middle" fontSize="10" fill={SUB}>{d.l}</text>)}
        {markers.map((m, i) => <g key={i}><circle cx={x(m.i)} cy={y(data[m.i].v)} r="5" fill="#fff" stroke="#d97706" strokeWidth="2.5"><title>{m.note}</title></circle></g>)}
      </svg>
    );
  }

  function BarChart({ data, height = 220, color = GREEN, fmt, target }) {
    const w = 640, h = height, pad = { l: 44, r: 16, t: 16, b: 28 };
    const max = Math.max(...data.map(d => d.v), target || 0) * 1.15 || 1;
    const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
    const bw = iw / data.length * 0.6;
    const x = i => pad.l + (i + 0.5) / data.length * iw;
    const y = v => pad.t + ih - (v / max) * ih;
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height }}>
        {[0, 0.25, 0.5, 0.75, 1].map((t, i) => { const yy = pad.t + ih - t * ih; return <g key={i}><line x1={pad.l} y1={yy} x2={w - pad.r} y2={yy} stroke={GRID} /><text x={pad.l - 8} y={yy + 3} textAnchor="end" fontSize="10" fill={SUB}>{fmt ? fmt(max * t) : Math.round(max * t)}</text></g>; })}
        {target != null && <line x1={pad.l} y1={y(target)} x2={w - pad.r} y2={y(target)} stroke="#d97706" strokeWidth="1.5" strokeDasharray="5 4" />}
        {data.map((d, i) => <g key={i}><rect x={x(i) - bw / 2} y={y(d.v)} width={bw} height={pad.t + ih - y(d.v)} rx="4" fill={d.color || color} /><text x={x(i)} y={h - 8} textAnchor="middle" fontSize="10" fill={SUB}>{d.l}</text></g>)}
      </svg>
    );
  }

  function StackedBar({ data, keys, height = 220, fmt }) {
    const w = 640, h = height, pad = { l: 44, r: 16, t: 16, b: 28 };
    const max = Math.max(...data.map(d => keys.reduce((s, k) => s + (d[k.key] || 0), 0))) * 1.15 || 1;
    const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b, bw = iw / data.length * 0.6;
    const x = i => pad.l + (i + 0.5) / data.length * iw;
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height }}>
        {[0, 0.5, 1].map((t, i) => { const yy = pad.t + ih - t * ih; return <line key={i} x1={pad.l} y1={yy} x2={w - pad.r} y2={yy} stroke={GRID} />; })}
        {data.map((d, i) => { let acc = 0; return <g key={i}>{keys.map(k => { const v = d[k.key] || 0; const hh = (v / max) * ih; const yy = pad.t + ih - acc - hh; acc += hh; return <rect key={k.key} x={x(i) - bw / 2} y={yy} width={bw} height={hh} fill={k.color} />; })}<text x={x(i)} y={h - 8} textAnchor="middle" fontSize="10" fill={SUB}>{d.l}</text></g>; })}
      </svg>
    );
  }

  function Donut({ data, size = 180, thickness = 28, center }) {
    const r = size / 2, ir = r - thickness, total = data.reduce((s, d) => s + d.v, 0) || 1;
    let a0 = -Math.PI / 2;
    const arc = (a0, a1) => { const x0 = r + r * Math.cos(a0), y0 = r + r * Math.sin(a0), x1 = r + r * Math.cos(a1), y1 = r + r * Math.sin(a1); const xi0 = r + ir * Math.cos(a1), yi0 = r + ir * Math.sin(a1), xi1 = r + ir * Math.cos(a0), yi1 = r + ir * Math.sin(a0); const large = a1 - a0 > Math.PI ? 1 : 0; return `M${x0},${y0} A${r},${r} 0 ${large} 1 ${x1},${y1} L${xi0},${yi0} A${ir},${ir} 0 ${large} 0 ${xi1},${yi1} Z`; };
    return (
      <svg viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size }}>
        {data.map((d, i) => { const a1 = a0 + (d.v / total) * Math.PI * 2; const p = arc(a0, a1); a0 = a1; return <path key={i} d={p} fill={d.color}><title>{d.l}: {d.v}</title></path>; })}
        {center && <text x={r} y={r - 2} textAnchor="middle" fontSize="22" fontWeight="700" fill={INK}>{center.v}</text>}
        {center && <text x={r} y={r + 16} textAnchor="middle" fontSize="11" fill={SUB}>{center.l}</text>}
      </svg>
    );
  }

  function Funnel({ steps, height }) {
    // steps: [{l, v, color}]
    const max = steps[0].v || 1;
    return (
      <div className="col g8">
        {steps.map((s, i) => {
          const pct = Math.round((s.v / max) * 100);
          const conv = i > 0 ? Math.round((s.v / steps[i - 1].v) * 100) : 100;
          return (
            <div key={i}>
              <div className="row aic jcsb t12" style={{ marginBottom: 4 }}><span className="fw6">{s.l}</span><span className="muted">{AAU.fmtNum(s.v)} {i > 0 && <span className="subtle">· {conv}% từ bước trước</span>}</span></div>
              <div style={{ height: 30, borderRadius: 7, background: '#f1f1f1', overflow: 'hidden' }}><div style={{ width: pct + '%', height: '100%', background: s.color || GREEN, borderRadius: 7, display: 'flex', alignItems: 'center', paddingLeft: 10, color: '#fff', fontSize: 12, fontWeight: 700 }}>{pct}%</div></div>
            </div>
          );
        })}
      </div>
    );
  }

  function Radar({ data, size = 240 }) {
    // data: [{l, v}] v 0-10
    const r = size / 2 - 30, cx = size / 2, cy = size / 2, n = data.length, maxV = 10;
    const pt = (i, val) => { const a = -Math.PI / 2 + (i / n) * Math.PI * 2; const rr = (val / maxV) * r; return [cx + rr * Math.cos(a), cy + rr * Math.sin(a)]; };
    const poly = data.map((d, i) => pt(i, d.v).join(',')).join(' ');
    return (
      <svg viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size }}>
        {[0.25, 0.5, 0.75, 1].map((t, i) => <polygon key={i} points={data.map((_, j) => pt(j, maxV * t).join(',')).join(' ')} fill="none" stroke={GRID} />)}
        {data.map((d, i) => { const [x, y] = pt(i, maxV); return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke={GRID} />; })}
        <polygon points={poly} fill={GREEN + '33'} stroke={GREEN} strokeWidth="2" />
        {data.map((d, i) => { const [x, y] = pt(i, maxV + 0.1); const a = -Math.PI / 2 + (i / n) * Math.PI * 2; return <text key={i} x={cx + (r + 16) * Math.cos(a)} y={cy + (r + 16) * Math.sin(a) + 3} textAnchor="middle" fontSize="9.5" fill={SUB}>{d.l}</text>; })}
        {data.map((d, i) => { const [x, y] = pt(i, d.v); return <circle key={i} cx={x} cy={y} r="3" fill={GREEN} />; })}
      </svg>
    );
  }

  function Legend({ items }) {
    return <div className="row wrap g12">{items.map((it, i) => <span key={i} className="row aic g6 t12"><span style={{ width: 10, height: 10, borderRadius: 3, background: it.color }} /><span className="muted">{it.l}</span></span>)}</div>;
  }

  Object.assign(window, { LineChart, BarChart, StackedBar, Donut, Funnel, Radar, Legend });
})();
