// ============ KPI Dashboard (Phase 3) ============

function kpiMonthData(db, monthEntry, settings) {
  if (!monthEntry) return null;
  const key = monthEntry.key;
  const gpStats = recipeGPStats(db);
  const oh = overheadTotal(db);
  // ใช้ค่าใช้จ่ายจริงของเดือนนั้น ถ้ายังไม่มีให้ใช้ overhead budget แทน
  const actualExp = typeof expenseMonthTotal === 'function' ? expenseMonthTotal(db, key) : 0;
  const effectiveOH = actualExp > 0 ? actualExp : oh;

  // GP
  const realCOGS = (() => {
    const report = (db.menuReports || []).find(r => r.monthKey === key);
    if (!report || !(report.rows || []).length) return null;
    let cogs = 0, covered = 0;
    report.rows.forEach(r => {
      const m = (db.menus || []).find(x => x.id === r.menuId || (r.name && x.name?.toLowerCase() === r.name.toLowerCase()));
      if (!m) return;
      const e = menuEconomics(db, m);
      if (e.hasRecipe && e.total > 0) { cogs += (r.qty || 0) * e.total; covered++; }
    });
    return covered > 0 ? { cogs, covered } : null;
  })();
  const rev = monthEntry.total;
  const effectiveGPpct = gpStats.weightedAvgGPpct > 0 ? gpStats.weightedAvgGPpct : (settings?.estGP || 0.65);
  const grossProfit = realCOGS ? rev - realCOGS.cogs : rev * effectiveGPpct;
  const gpPct = rev > 0 ? grossProfit / rev : 0;
  const net = grossProfit - effectiveOH;

  // Waste this month
  const stockItems = typeof stockBuildItems === 'function' ? stockBuildItems(db) : [];
  const wasteEvs = (db.wasteEvents || []).filter(e => String(e.wastedAt || e.createdAt || '').startsWith(key));
  const wasteValue = wasteEvs.reduce((s, e) => {
    const qty = Math.abs(Number(e.qty) || 0);
    if (!qty) return s;
    if (e.menuId) {
      const cost = typeof computeMenuCost === 'function' ? computeMenuCost(db, e.menuId).total : 0;
      return s + qty * cost;
    }
    const si = stockItems.find(x => x.id === e.stockItemId);
    if (si) {
      let cpu = 0;
      if (si.refType === 'ingredient') { const ing = (db.ingredients || []).find(i => i.id === si.refId); cpu = Number(ing?.costPerUnit) || 0; }
      else if (si.refType === 'package') { const pkg = (db.packages || []).find(p => p.id === si.refId); cpu = Number(pkg?.costPerPiece) || 0; }
      return s + qty * cpu;
    }
    return s;
  }, 0);
  const wastePct = rev > 0 ? wasteValue / rev : 0;

  // Production
  const prodEvs = (db.productionEvents || []).filter(e => String(e.producedAt || '').startsWith(key));
  const prodQty = prodEvs.reduce((s, e) => s + (e.qtyProduced || 0), 0);
  const prodCost = prodEvs.reduce((s, e) => s + (e.totalCost || 0), 0);

  return { key, rev, grossProfit, gpPct, net, oh: effectiveOH, ohBudget: oh, actualExp, wasteValue, wastePct, wasteCount: wasteEvs.length, prodQty, prodCost, prodRounds: prodEvs.length, days: monthEntry.days, gpSource: realCOGS ? 'pos' : gpStats.weightedAvgGPpct > 0 ? 'recipe' : 'est' };
}

function KPITrafficLight({ status }) {
  const cfg = { green: { bg: 'var(--green)', label: 'ดี' }, yellow: { bg: 'var(--orange)', label: 'เฝ้าดู' }, red: { bg: 'var(--red)', label: 'ต้องแก้' } }[status] || { bg: 'var(--ink-3)', label: '—' };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
      <span style={{ width: 10, height: 10, borderRadius: '50%', background: cfg.bg, flexShrink: 0 }} />
      <span style={{ fontSize: 12, color: cfg.bg, fontWeight: 600 }}>{cfg.label}</span>
    </div>
  );
}

function KPICard({ label, value, sub, status, icon, onClick }) {
  const borderColor = { green: 'var(--green)', yellow: 'var(--orange)', red: 'var(--red)', gray: 'var(--line)' }[status] || 'var(--line)';
  return (
    <div onClick={onClick} style={{
      background: 'var(--surface)', borderRadius: 16, padding: '16px 18px',
      boxShadow: 'var(--shadow)', borderLeft: `4px solid ${borderColor}`,
      cursor: onClick ? 'pointer' : 'default', display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <span style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</span>
        <KPITrafficLight status={status} />
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-.5px', color: 'var(--ink)' }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{sub}</div>}
    </div>
  );
}

function KPIPage({ go }) {
  const { fdb: db, settings, THAI_MONTHS, flash } = useData();

  const months = aggregateByMonth(db);
  const last6 = months.slice(-6);
  const cur = last6[last6.length - 1];
  const prev = last6[last6.length - 2];

  const stockItems = typeof stockBuildItems === 'function' ? stockBuildItems(db) : [];
  const emptyCount = stockItems.filter(s => s.emptyAlert).length;
  const lowCount = stockItems.filter(s => !s.emptyAlert && s.lowAlert).length;

  const THAI_MONTHS_LOCAL = ['', 'ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.'];
  const thaiMonthLabel = key => {
    if (!key) return '';
    const [y, m] = key.split('-');
    return `${THAI_MONTHS_LOCAL[+m] || m} ${+y + 543}`;
  };

  if (!cur) {
    return <Empty icon="sales" title="ยังไม่มีข้อมูล" sub="บันทึกยอดขายก่อน แล้ว KPI จะคำนวณให้อัตโนมัติ"
      action={<Button icon="plus" onClick={() => go('sales')}>บันทึกยอดขาย</Button>} />;
  }

  const curData = kpiMonthData(db, cur, settings);
  const prevData = prev ? kpiMonthData(db, prev, settings) : null;

  // Targets
  const targetRev = settings.target || 0;
  const targetGP = settings.estGP > 0 ? settings.estGP : 0.65;
  const wasteThreshold = 0.05; // >5% ของรายได้ = red

  // Traffic light logic
  const revStatus = !targetRev ? 'gray' : curData.rev >= targetRev ? 'green' : curData.rev >= targetRev * 0.8 ? 'yellow' : 'red';
  const gpStatus = curData.gpPct >= targetGP ? 'green' : curData.gpPct >= targetGP * 0.9 ? 'yellow' : 'red';
  const netStatus = curData.net > 0 ? 'green' : curData.net > -targetRev * 0.05 ? 'yellow' : 'red';
  const wasteStatus = curData.wastePct === 0 ? 'gray' : curData.wastePct <= wasteThreshold ? 'green' : curData.wastePct <= wasteThreshold * 1.5 ? 'yellow' : 'red';
  const stockStatus = emptyCount > 0 ? 'red' : lowCount > 0 ? 'yellow' : 'green';

  // Business Health Score (0-5 points → %)
  const scorePoints = [
    revStatus === 'green' ? 1 : revStatus === 'yellow' ? 0.5 : 0,
    gpStatus === 'green' ? 1 : gpStatus === 'yellow' ? 0.5 : 0,
    netStatus === 'green' ? 1 : netStatus === 'yellow' ? 0.5 : 0,
    wasteStatus === 'green' || wasteStatus === 'gray' ? 1 : wasteStatus === 'yellow' ? 0.5 : 0,
    stockStatus === 'green' ? 1 : stockStatus === 'yellow' ? 0.5 : 0,
  ];
  const healthScore = Math.round((scorePoints.reduce((a, b) => a + b, 0) / 5) * 100);
  const healthTone = healthScore >= 80 ? 'var(--green)' : healthScore >= 50 ? 'var(--orange)' : 'var(--red)';
  const healthLabel = healthScore >= 80 ? 'สุขภาพร้านดี' : healthScore >= 50 ? 'พอใช้ได้ ควรดูแล' : 'ต้องให้ความสนใจ';

  // Month-over-month delta helpers
  const delta = (cur, prev) => prev && prev > 0 ? ((cur - prev) / prev * 100) : null;
  const fmtDelta = v => v === null ? null : (v > 0 ? '+' : '') + v.toFixed(1) + '%';

  // Action items
  const actions = [];
  if (emptyCount > 0) actions.push({ tone: 'red', icon: '🔴', text: `วัตถุดิบหมด ${emptyCount} รายการ — เติมสต็อกด่วน`, route: 'stock' });
  if (lowCount > 0) actions.push({ tone: 'orange', icon: '🟡', text: `ใกล้หมด ${lowCount} รายการ — วางแผนสั่งซื้อ`, route: 'stock' });
  if (gpStatus === 'red') actions.push({ tone: 'red', icon: '📉', text: `GP% (${fmtPct(curData.gpPct, 1)}) ต่ำกว่าเป้า ${fmtPct(targetGP, 0)} — ตรวจสูตรต้นทุน`, route: 'pricing' });
  if (wasteStatus === 'red') actions.push({ tone: 'red', icon: '🗑️', text: `ของเสีย ${fmtPct(curData.wastePct, 1)} ของรายได้ — สูงเกิน 5%`, route: 'waste' });
  if (revStatus === 'red' && targetRev > 0) actions.push({ tone: 'orange', icon: '📊', text: `รายได้ต่ำกว่าเป้า ${fmtPct(1 - curData.rev / targetRev, 0)} — ดูช่องทางขาย`, route: 'analytics' });
  if (curData.net < 0) actions.push({ tone: 'red', icon: '💸', text: `กำไรสุทธิติดลบ ${fmtB(Math.abs(curData.net))} — ตรวจค่าใช้จ่าย`, route: 'reports' });
  if (actions.length === 0) actions.push({ tone: 'green', icon: '✅', text: 'ทุก KPI อยู่ในเกณฑ์ดี — ดีมากครับ!', route: null });

  // 6-month scorecard table data
  const tableRows = last6.map(m => kpiMonthData(db, m, settings)).filter(Boolean);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 860, margin: '0 auto', paddingBottom: 80 }}>

      {/* Health Score Header */}
      <div style={{ background: 'var(--surface)', borderRadius: 20, padding: '20px 24px', boxShadow: 'var(--shadow)', display: 'flex', alignItems: 'center', gap: 20 }}>
        <div style={{ position: 'relative', width: 80, height: 80, flexShrink: 0 }}>
          <svg viewBox="0 0 80 80" style={{ transform: 'rotate(-90deg)', width: 80, height: 80 }}>
            <circle cx="40" cy="40" r="32" fill="none" stroke="var(--chip)" strokeWidth="10" />
            <circle cx="40" cy="40" r="32" fill="none" stroke={healthTone} strokeWidth="10"
              strokeDasharray={`${2 * Math.PI * 32}`}
              strokeDashoffset={`${2 * Math.PI * 32 * (1 - healthScore / 100)}`}
              strokeLinecap="round" style={{ transition: 'stroke-dashoffset 1s ease' }} />
          </svg>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <span style={{ fontSize: 18, fontWeight: 800, color: healthTone, lineHeight: 1 }}>{healthScore}</span>
            <span style={{ fontSize: 9, color: 'var(--ink-3)' }}>/ 100</span>
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Business Health Score</div>
          <div style={{ fontSize: 22, fontWeight: 700, color: healthTone, marginTop: 2 }}>{healthLabel}</div>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
            {thaiMonthLabel(curData.key)} · {curData.gpSource === 'pos' ? 'GP จากยอดขาย' : curData.gpSource === 'recipe' ? 'GP จากสูตร' : 'GP ประมาณ'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="secondary" size="sm" icon="download" onClick={() => {
            const header = ['เดือน', 'รายได้ (฿)', 'GP%', 'กำไรขั้นต้น (฿)', 'กำไรสุทธิ (฿)', 'ของเสีย (฿)', 'ของเสีย%', 'ผลิต (ชิ้น)', 'ต้นทุนผลิต (฿)'];
            const rows = tableRows.map(r => [
              thaiMonthLabel(r.key), r.rev.toFixed(2), (r.gpPct * 100).toFixed(1) + '%',
              r.grossProfit.toFixed(2), r.net.toFixed(2), r.wasteValue.toFixed(2),
              (r.wastePct * 100).toFixed(1) + '%', r.prodQty, r.prodCost.toFixed(2),
            ]);
            const csv = '﻿' + [header, ...rows].map(r => r.map(v => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n');
            const a = document.createElement('a');
            a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
            a.download = `kpi-scorecard-${new Date().toISOString().slice(0, 10)}.csv`;
            a.click();
            flash(`ส่งออก KPI ${tableRows.length} เดือนแล้ว`);
          }}>CSV</Button>
        </div>
      </div>

      {/* KPI Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        <KPICard
          label="รายได้เดือนนี้"
          value={fmtB(curData.rev)}
          sub={targetRev > 0 ? `${fmtPct(curData.rev / targetRev, 0)} ของเป้า ${fmtB(targetRev)}` : `${curData.days} วันที่บันทึก`}
          status={revStatus}
          onClick={() => go('sales')}
        />
        <KPICard
          label="GP% เดือนนี้"
          value={fmtPct(curData.gpPct, 1)}
          sub={`เป้า ${fmtPct(targetGP, 0)} · ${curData.gpSource === 'pos' ? 'จาก POS จริง' : curData.gpSource === 'recipe' ? 'จากสูตร' : 'ประมาณ'}`}
          status={gpStatus}
          onClick={() => go('pricing')}
        />
        <KPICard
          label="กำไรสุทธิเดือนนี้"
          value={fmtB(curData.net)}
          sub={`หลังหักโสหุ้ย ${fmtB(curData.oh)}`}
          status={netStatus}
          onClick={() => go('analytics')}
        />
        <KPICard
          label="มูลค่าของเสีย"
          value={curData.wasteValue > 0 ? fmtB(curData.wasteValue) : '—'}
          sub={curData.wasteValue > 0 ? `${fmtPct(curData.wastePct, 1)} ของรายได้ · เป้า < 5%` : 'ยังไม่มีของเสียเดือนนี้'}
          status={wasteStatus}
          onClick={() => go('waste')}
        />
        <KPICard
          label="สต็อกวัตถุดิบ"
          value={emptyCount > 0 ? `หมด ${emptyCount}` : lowCount > 0 ? `ใกล้หมด ${lowCount}` : 'ปกติ'}
          sub={`${stockItems.length} รายการทั้งหมด`}
          status={stockStatus}
          onClick={() => go('stock')}
        />
        <KPICard
          label="การผลิตเดือนนี้"
          value={curData.prodQty > 0 ? `${fmt(curData.prodQty)} ชิ้น` : '—'}
          sub={curData.prodRounds > 0 ? `${curData.prodRounds} รอบ · ต้นทุน ${fmtB(curData.prodCost)}` : 'ยังไม่มีการผลิตเดือนนี้'}
          status={curData.prodQty > 0 ? 'green' : 'gray'}
          onClick={() => go('production')}
        />
      </div>

      {/* Action Items */}
      <div style={{ background: 'var(--surface)', borderRadius: 16, padding: 18, boxShadow: 'var(--shadow)' }}>
        <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 12 }}>สิ่งที่ต้องดำเนินการ</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {actions.map((a, i) => (
            <div key={i} onClick={a.route ? () => go(a.route) : undefined}
              style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px',
                borderRadius: 10, cursor: a.route ? 'pointer' : 'default',
                background: a.tone === 'green' ? 'var(--green-soft, rgba(48,164,108,.08))' : a.tone === 'red' ? 'var(--red-soft, rgba(220,38,38,.07))' : 'rgba(217,122,22,.07)',
              }}>
              <span style={{ fontSize: 18, flexShrink: 0 }}>{a.icon}</span>
              <span style={{ fontSize: 13.5, flex: 1 }}>{a.text}</span>
              {a.route && <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>→</span>}
            </div>
          ))}
        </div>
      </div>

      {/* 6-Month Scorecard Table */}
      {tableRows.length > 1 && (
        <div style={{ background: 'var(--surface)', borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--shadow)' }}>
          <div style={{ padding: '14px 18px 10px', fontWeight: 700, fontSize: 15 }}>Scorecard 6 เดือนย้อนหลัง</div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'var(--surface-2)', color: 'var(--ink-3)', fontSize: 11.5, fontWeight: 700 }}>
                  {['เดือน', 'รายได้', 'GP%', 'กำไรสุทธิ', 'ของเสีย', 'ผลิต (ชิ้น)'].map(h => (
                    <th key={h} style={{ padding: '8px 14px', textAlign: h === 'เดือน' ? 'left' : 'right', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {[...tableRows].reverse().map((row, i) => {
                  const isThis = i === 0;
                  const prevRow = tableRows[tableRows.length - 2 - i];
                  const revD = prevRow ? delta(row.rev, prevRow.rev) : null;
                  const gpD = prevRow ? delta(row.gpPct, prevRow.gpPct) : null;
                  return (
                    <tr key={row.key} style={{ borderTop: '1px solid var(--line-2)', background: isThis ? 'var(--accent-soft)' : 'transparent' }}>
                      <td style={{ padding: '10px 14px', fontWeight: isThis ? 700 : 400, whiteSpace: 'nowrap' }}>
                        {thaiMonthLabel(row.key)}{isThis ? ' ●' : ''}
                      </td>
                      <td className="tnum" style={{ padding: '10px 14px', textAlign: 'right', fontWeight: isThis ? 700 : 400 }}>
                        <div>{fmtB(row.rev)}</div>
                        {revD !== null && <div style={{ fontSize: 10, color: revD >= 0 ? 'var(--green)' : 'var(--red)' }}>{fmtDelta(revD)}</div>}
                      </td>
                      <td className="tnum" style={{ padding: '10px 14px', textAlign: 'right' }}>
                        <div style={{ fontWeight: isThis ? 700 : 400, color: row.gpPct >= targetGP ? 'var(--green)' : 'var(--red)' }}>{fmtPct(row.gpPct, 1)}</div>
                        {gpD !== null && <div style={{ fontSize: 10, color: gpD >= 0 ? 'var(--green)' : 'var(--red)' }}>{fmtDelta(gpD)}</div>}
                      </td>
                      <td className="tnum" style={{ padding: '10px 14px', textAlign: 'right', color: row.net >= 0 ? 'var(--green)' : 'var(--red)', fontWeight: isThis ? 700 : 400 }}>
                        {fmtB(row.net)}
                      </td>
                      <td className="tnum" style={{ padding: '10px 14px', textAlign: 'right', color: row.wasteValue > 0 ? 'var(--orange)' : 'var(--ink-3)' }}>
                        {row.wasteValue > 0 ? fmtB(row.wasteValue) : '—'}
                      </td>
                      <td className="tnum" style={{ padding: '10px 14px', textAlign: 'right', fontWeight: isThis ? 600 : 400 }}>
                        {row.prodQty > 0 ? fmt(row.prodQty) : '—'}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Month-over-month comparison: current vs prev */}
      {prevData && (
        <div style={{ background: 'var(--surface)', borderRadius: 16, padding: 18, boxShadow: 'var(--shadow)' }}>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 14 }}>
            เทียบ {thaiMonthLabel(curData.key)} vs {thaiMonthLabel(prevData.key)}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {[
              { label: 'รายได้', cur: fmtB(curData.rev), prev: fmtB(prevData.rev), d: delta(curData.rev, prevData.rev) },
              { label: 'กำไรขั้นต้น', cur: fmtB(curData.grossProfit), prev: fmtB(prevData.grossProfit), d: delta(curData.grossProfit, prevData.grossProfit) },
              { label: 'GP%', cur: fmtPct(curData.gpPct, 1), prev: fmtPct(prevData.gpPct, 1), d: delta(curData.gpPct, prevData.gpPct) },
              { label: 'กำไรสุทธิ', cur: fmtB(curData.net), prev: fmtB(prevData.net), d: delta(curData.net, prevData.net) },
              { label: 'มูลค่าของเสีย', cur: curData.wasteValue > 0 ? fmtB(curData.wasteValue) : '—', prev: prevData.wasteValue > 0 ? fmtB(prevData.wasteValue) : '—', d: prevData.wasteValue > 0 ? delta(curData.wasteValue, prevData.wasteValue) : null, invertGood: true },
              { label: 'ผลิต (ชิ้น)', cur: curData.prodQty > 0 ? fmt(curData.prodQty) : '—', prev: prevData.prodQty > 0 ? fmt(prevData.prodQty) : '—', d: prevData.prodQty > 0 ? delta(curData.prodQty, prevData.prodQty) : null },
            ].map((row, i, arr) => (
              <div key={row.label} style={{
                display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 80px', gap: 0,
                padding: '10px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--line-2)' : 'none',
                alignItems: 'center',
              }}>
                <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>{row.label}</span>
                <span className="tnum" style={{ fontSize: 13.5, fontWeight: 600, textAlign: 'right' }}>{row.cur}</span>
                <span className="tnum" style={{ fontSize: 13, color: 'var(--ink-3)', textAlign: 'right' }}>{row.prev}</span>
                <span style={{ textAlign: 'right' }}>
                  {row.d !== null && row.d !== undefined ? (
                    <span style={{
                      fontSize: 12, fontWeight: 600,
                      color: row.invertGood ? (row.d <= 0 ? 'var(--green)' : 'var(--red)') : (row.d >= 0 ? 'var(--green)' : 'var(--red)'),
                    }}>{fmtDelta(row.d)}</span>
                  ) : <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>—</span>}
                </span>
              </div>
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 80px', gap: 0, marginTop: 6, paddingTop: 4 }}>
            <span style={{ fontSize: 11, color: 'var(--ink-3)' }} />
            <span style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'right' }}>{thaiMonthLabel(curData.key)}</span>
            <span style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'right' }}>{thaiMonthLabel(prevData.key)}</span>
            <span style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'right' }}>เปลี่ยนแปลง</span>
          </div>
        </div>
      )}

    </div>
  );
}

Object.assign(window, { KPIPage });
