/* global React */
/* ============================================================================
   T1 Management Dashboard — editorial SVG charts.
   SUBSTITUTION FLAG: charts are hand-authored SVG (no external chart lib).
   Restrained per brand: hairline gridlines, muted forest/oxblood/gold,
   IBM Plex Mono tabular labels. No neon, no 3D, no gradient fills.
   All chart surfaces sit on the "evening" ink panels.
   ============================================================================ */

const EV = {
  hi: "#F2ECDD", lo: "#B0A691", mute: "#837A6E",
  line: "#322D24", line2: "#423B2F",
  gold: "#C5A572", goldDim: "#9C7C4A",
  pos: "#6FA86B", posDim: "#3E6B3A",
  neg: "#C57A6E", negDim: "#8F4A3E",
  warn: "#CBA24E", info: "#79A0AE",
};

const TH_MONTHS = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
const fmtM = (n) => (n / 1e6).toFixed(1);
const fmtK = (n) => Math.round(n / 1e3).toLocaleString("en-US");
const fmtComma = (n) => n.toLocaleString("en-US", { maximumFractionDigits: 0 });

/* ---- Revenue / Expense bars + Net-profit line --------------------------- */
function TrendChart({ rev, exp, net, labels = TH_MONTHS }) {
  const W = 660, H = 250, padL = 38, padR = 12, padT = 14, padB = 26;
  const iw = W - padL - padR, ih = H - padT - padB;
  const max = Math.max(...rev, ...exp) * 1.12;
  const n = rev.length;
  const slot = iw / n;
  const bw = slot * 0.30;
  const y = (v) => padT + ih - (v / max) * ih;
  const ticks = 4;
  const netPts = net.map((v, i) => [padL + slot * i + slot / 2, y(v)]);
  const netPath = netPts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  return (
    <div className="chart">
      <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label="รายได้ ค่าใช้จ่าย และกำไรสุทธิรายเดือน">
        {Array.from({ length: ticks + 1 }).map((_, i) => {
          const v = (max / ticks) * i, yy = y(v);
          return (
            <g key={i}>
              <line className="grid-l" x1={padL} y1={yy} x2={W - padR} y2={yy} stroke={EV.line} />
              <text className="axis-lab" x={padL - 8} y={yy + 3} textAnchor="end" fill={EV.mute}>{fmtM(v)}</text>
            </g>
          );
        })}
        {rev.map((v, i) => {
          const cx = padL + slot * i + slot / 2;
          return (
            <g key={i}>
              <rect x={cx - bw - 1.5} y={y(v)} width={bw} height={padT + ih - y(v)} fill={EV.goldDim} rx="1" />
              <rect x={cx + 1.5} y={y(exp[i])} width={bw} height={padT + ih - y(exp[i])} fill={EV.negDim} rx="1" opacity="0.85" />
              <text className="axis-lab" x={cx} y={H - 8} textAnchor="middle" fill={EV.mute}>{labels[i]}</text>
            </g>
          );
        })}
        <path d={netPath} fill="none" stroke={EV.pos} strokeWidth="2" strokeLinejoin="round" />
        {netPts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="2.6" fill="#1B1812" stroke={EV.pos} strokeWidth="1.6" />)}
      </svg>
    </div>
  );
}

/* ---- Dual percentage lines (gross / net margin) ------------------------- */
function MarginLines({ gross, net, labels = TH_MONTHS }) {
  const W = 320, H = 200, padL = 30, padR = 10, padT = 12, padB = 24;
  const iw = W - padL - padR, ih = H - padT - padB;
  const max = 50, n = gross.length;
  const x = (i) => padL + (iw / (n - 1)) * i;
  const y = (v) => padT + ih - (v / max) * ih;
  const toPath = (arr) => arr.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
  const ticks = [0, 25, 50];
  return (
    <div className="chart">
      <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label="อัตรากำไรขั้นต้นและกำไรสุทธิ">
        {ticks.map((v, i) => (
          <g key={i}>
            <line className="grid-l" x1={padL} y1={y(v)} x2={W - padR} y2={y(v)} stroke={EV.line} />
            <text className="axis-lab" x={padL - 7} y={y(v) + 3} textAnchor="end" fill={EV.mute}>{v}</text>
          </g>
        ))}
        <path d={toPath(gross)} fill="none" stroke={EV.gold} strokeWidth="2" strokeLinejoin="round" />
        <path d={toPath(net)} fill="none" stroke={EV.pos} strokeWidth="2" strokeLinejoin="round" />
        {[0, n - 1].map(i => <text key={"l"+i} className="axis-lab" x={x(i)} y={H - 6} textAnchor={i ? "end" : "start"} fill={EV.mute}>{labels[i]}</text>)}
      </svg>
    </div>
  );
}

/* ---- Cash position area ------------------------------------------------- */
function CashArea({ data, labels = TH_MONTHS }) {
  const W = 320, H = 200, padL = 32, padR = 10, padT = 12, padB = 24;
  const iw = W - padL - padR, ih = H - padT - padB;
  const max = Math.max(...data) * 1.15, n = data.length;
  const x = (i) => padL + (iw / (n - 1)) * i;
  const y = (v) => padT + ih - (v / max) * ih;
  const line = data.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
  const area = `M ${x(0)} ${padT + ih} ` + data.map((v, i) => "L " + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ") + ` L ${x(n-1)} ${padT + ih} Z`;
  const ticks = 3;
  return (
    <div className="chart">
      <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label="กระแสเงินสดคงเหลือ">
        {Array.from({ length: ticks + 1 }).map((_, i) => {
          const v = (max / ticks) * i;
          return (
            <g key={i}>
              <line className="grid-l" x1={padL} y1={y(v)} x2={W - padR} y2={y(v)} stroke={EV.line} />
              <text className="axis-lab" x={padL - 7} y={y(v) + 3} textAnchor="end" fill={EV.mute}>{fmtM(v)}</text>
            </g>
          );
        })}
        <path d={area} fill={EV.info} opacity="0.12" />
        <path d={line} fill="none" stroke={EV.info} strokeWidth="2" strokeLinejoin="round" />
        {[0, n - 1].map(i => <text key={i} className="axis-lab" x={x(i)} y={H - 6} textAnchor={i ? "end" : "start"} fill={EV.mute}>{labels[i]}</text>)}
      </svg>
    </div>
  );
}

/* ---- Current-ratio gauge (semicircle) ----------------------------------- */
function Gauge({ value, min = 0, max = 3, healthyFrom = 1.5 }) {
  const W = 150, H = 90, cx = W / 2, cy = H - 6, r = 62;
  const a0 = Math.PI, a1 = 0;
  const polar = (ang) => [cx + r * Math.cos(ang), cy + r * Math.sin(-ang === 0 ? 0 : -ang)];
  // map value to angle (pi -> 0)
  const frac = Math.max(0, Math.min(1, (value - min) / (max - min)));
  const ang = a0 - frac * (a0 - a1);
  const p = (an) => [cx + r * Math.cos(an), cy - r * Math.sin(an)];
  const arc = (start, end, color, wdt) => {
    const [x1, y1] = p(start), [x2, y2] = p(end);
    const large = (start - end) > Math.PI ? 1 : 0;
    return <path d={`M ${x1.toFixed(1)} ${y1.toFixed(1)} A ${r} ${r} 0 ${large} 1 ${x2.toFixed(1)} ${y2.toFixed(1)}`}
      fill="none" stroke={color} strokeWidth={wdt} strokeLinecap="round" />;
  };
  const healthyFrac = (healthyFrom - min) / (max - min);
  const healthyAng = a0 - healthyFrac * (a0 - a1);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="150" style={{ overflow: "visible" }}>
      {arc(a0, a1, EV.line2, 7)}
      {arc(healthyAng, a1, "rgba(111,168,107,.35)", 7)}
      {arc(a0, ang, EV.pos, 7)}
      {(() => { const [px, py] = p(ang); return <circle cx={px} cy={py} r="4.5" fill="#1B1812" stroke={EV.pos} strokeWidth="2" />; })()}
    </svg>
  );
}

/* ---- Sparkline (KPI cards) ---------------------------------------------- */
function Sparkline({ data, color = EV.gold, width = 150, height = 34 }) {
  const max = Math.max(...data), min = Math.min(...data), n = data.length;
  const x = (i) => (width / (n - 1)) * i;
  const y = (v) => height - 3 - ((v - min) / (max - min || 1)) * (height - 6);
  const d = data.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
  const area = `M ${x(0)} ${height} ` + data.map((v, i) => "L " + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ") + ` L ${x(n-1)} ${height} Z`;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} width="100%" height={height} preserveAspectRatio="none" style={{ display: "block" }}>
      <path d={area} fill={color} opacity="0.10" />
      <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

Object.assign(window, { EV, TH_MONTHS, fmtM, fmtK, fmtComma, TrendChart, MarginLines, CashArea, Gauge, Sparkline });
