// Komponen grafik SVG ringan (tanpa library) untuk halaman Laporan.

// ---- Bar chart (tren pesanan) + line overlay ----
function BarChart({ data, height = 200, color = "var(--pri)" }) {
  const max = Math.max(1, ...data.map((d) => d.value));
  const [hover, setHover] = React.useState(null);
  const W = 760, H = height, padB = 26, padT = 12;
  const n = data.length;
  const gap = n > 40 ? 1 : n > 16 ? 3 : 8;
  const bw = (W - gap * (n - 1)) / n;
  const plotH = H - padB - padT;

  // centre-x and top-y for each bar → used by the line
  const pts = data.map((d, i) => ({
    x: i * (bw + gap) + bw / 2,
    y: padT + plotH - (d.value / max) * plotH,
  }));
  const linePoints = pts.map((p) => `${p.x},${p.y}`).join(" ");

  return (
    <div className="qc-chart-wrap">
      <svg viewBox={`0 0 ${W} ${H}`} className="qc-barchart" preserveAspectRatio="none"
           onMouseLeave={() => setHover(null)}>
        {[0.25, 0.5, 0.75, 1].map((g) => (
          <line key={g} x1="0" x2={W} y1={padT + plotH * (1 - g)} y2={padT + plotH * (1 - g)}
                stroke="var(--line)" strokeWidth="1" strokeDasharray="3 4" />
        ))}
        {/* bars */}
        {data.map((d, i) => {
          const h = (d.value / max) * plotH;
          const x = i * (bw + gap);
          const on = hover === i;
          return (
            <g key={i} onMouseEnter={() => setHover(i)}>
              <rect x={x} y={padT} width={bw} height={plotH} fill="transparent" />
              <rect x={x} y={padT + plotH - h} width={bw} height={Math.max(h, 1)} rx={Math.min(3, bw / 2)}
                    fill={on ? "var(--pri-ink2)" : color} opacity={on ? 0.45 : 0.28}
                    style={{ transition: "fill .1s, opacity .1s" }} />
            </g>
          );
        })}
        {/* trend line */}
        {n > 1 && (
          <polyline points={linePoints} fill="none"
            stroke={color} strokeWidth="2.2" strokeLinejoin="round" strokeLinecap="round"
            opacity="0.9" />
        )}
        {/* dots */}
        {pts.map((p, i) => (
          <circle key={"d" + i} cx={p.x} cy={p.y} r={hover === i ? 5 : 3.2}
            fill={hover === i ? color : "#fff"}
            stroke={color} strokeWidth="2"
            style={{ transition: "r .1s" }}
            onMouseEnter={() => setHover(i)} />
        ))}
        {data.map((d, i) => (n <= 14 || i % Math.ceil(n / 12) === 0) && (
          <text key={"l" + i} x={i * (bw + gap) + bw / 2} y={H - 8} textAnchor="middle"
                className="qc-chart-xlbl">{d.label}</text>
        ))}
      </svg>
      {hover !== null && (
        <div className="qc-chart-tip" style={{ left: `${((hover * (bw + gap) + bw / 2) / W) * 100}%` }}>
          <b>{data[hover].value}</b> pesanan<span>{data[hover].full || data[hover].label}</span>
        </div>
      )}
    </div>
  );
}

// ---- Donut (status QC) ----
function Donut({ segments, size = 168 }) {
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  const r = size / 2 - 16, cx = size / 2, cy = size / 2, C = 2 * Math.PI * r;
  let acc = 0;
  return (
    <div className="qc-donut">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--line)" strokeWidth="20" />
        {segments.map((s, i) => {
          const frac = s.value / total;
          const dash = frac * C;
          const el = (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={s.color} strokeWidth="20"
                    strokeDasharray={`${dash} ${C - dash}`} strokeDashoffset={-acc * C}
                    transform={`rotate(-90 ${cx} ${cy})`} strokeLinecap="butt" />
          );
          acc += frac; return el;
        })}
        <text x={cx} y={cy - 4} textAnchor="middle" className="qc-donut-num">{total}</text>
        <text x={cx} y={cy + 16} textAnchor="middle" className="qc-donut-lbl">total</text>
      </svg>
      <div className="qc-donut-legend">
        {segments.map((s, i) => (
          <div key={i} className="qc-donut-leg">
            <span className="qc-donut-dot" style={{ background: s.color }} />
            <span className="qc-donut-leg-lbl">{s.label}</span>
            <b>{s.value}</b>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- Horizontal bars (kota, provinsi, produk) ----
function HBars({ data, accent = "var(--pri)", showPhoto = false, unit = "" }) {
  const max = Math.max(1, ...data.map((d) => d.value));
  return (
    <div className="qc-hbars">
      {data.map((d, i) => (
        <div key={i} className="qc-hbar-row">
          <div className="qc-hbar-rank">{i + 1}</div>
          {showPhoto && <ProductPhoto cat={d.cat} size={30} radius={6} />}
          <div className="qc-hbar-main">
            <div className="qc-hbar-top">
              <span className="qc-hbar-lbl">{d.label}</span>
              <span className="qc-hbar-val">{d.value.toLocaleString("id-ID")}{unit && <i> {unit}</i>}</span>
            </div>
            <div className="qc-hbar-track">
              <div className="qc-hbar-fill" style={{ width: `${(d.value / max) * 100}%`, background: accent }} />
            </div>
          </div>
          {d.sub && <div className="qc-hbar-sub">{d.sub}</div>}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { BarChart, Donut, HBars });
