/* Dashboard view + Chart + Sparkline + Donut */

const { useMemo, useState } = React;

function getGreeting() {
  const h = new Date().getHours();
  if (h < 12) return 'สวัสดีตอนเช้า';
  if (h < 17) return 'สวัสดีตอนบ่าย';
  if (h < 19) return 'สวัสดีตอนเย็น';
  return 'สวัสดีตอนค่ำ';
}

function Sparkline({ points, color = 'var(--ink)', w = 84, h = 28 }) {
  if (!points || points.length === 0) return null;
  const max = Math.max(1, ...points);
  const step = points.length > 1 ? w / (points.length - 1) : 0;
  const path = points.map((v, i) => `${i === 0 ? 'M' : 'L'} ${i * step} ${h - (v / max) * h}`).join(' ');
  const area = `M 0 ${h} L ` + points.map((v, i) => `${i * step} ${h - (v / max) * h}`).join(' L ') + ` L ${w} ${h} Z`;
  return (
    <svg width={w} height={h} className="kpi-spark">
      <defs>
        <linearGradient id={'sparkg-' + color} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.3"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#sparkg-${color})`}/>
      <path d={path} fill="none" stroke={color} strokeWidth="1.6"/>
    </svg>
  );
}

function MonthlyChart({ purchases, issues }) {
  const data = MONTHS.map(m => {
    const buyQty = purchases.filter(t => monthKey(t.date) === m.key).reduce((s,t) => s + t.qty, 0);
    const useQty = issues.filter(t => monthKey(t.date) === m.key).reduce((s,t) => s + t.qty, 0);
    return { ...m, buy: buyQty, use: useQty };
  });
  const max = Math.max(20, ...data.map(d => Math.max(d.buy, d.use))) * 1.18;
  const W = 640, H = 220;
  const pad = { l: 36, r: 16, t: 14, b: 32 };
  const innerW = W - pad.l - pad.r;
  const innerH = H - pad.t - pad.b;
  const groupW = innerW / data.length;
  const barW = Math.min(22, (groupW - 18) / 2);
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => Math.round(max * t / 5) * 5);
  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{width: '100%', height: 'auto', display: 'block'}}>
        <defs>
          <linearGradient id="g-buy" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#4a9ee0"/><stop offset="100%" stopColor="#1a78c2"/>
          </linearGradient>
          <linearGradient id="g-use" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#f0a967"/><stop offset="100%" stopColor="#d97a1f"/>
          </linearGradient>
        </defs>
        {yTicks.map(v => {
          const y = pad.t + innerH - (v / max) * innerH;
          return (
            <g key={v}>
              <line x1={pad.l} y1={y} x2={W - pad.r} y2={y} stroke="var(--border)" strokeDasharray="2 3"/>
              <text x={pad.l - 8} y={y + 3.5} textAnchor="end" className="chart-axis-text">{v}</text>
            </g>
          );
        })}
        {data.map((d, i) => {
          const cx = pad.l + groupW * i + groupW / 2;
          const buyH = (d.buy / max) * innerH;
          const useH = (d.use / max) * innerH;
          return (
            <g key={d.key}>
              <rect x={cx - barW - 1} y={pad.t + innerH - buyH} width={barW} height={buyH} rx={3} fill="url(#g-buy)">
                <title>{d.label}: รับเข้า {d.buy}</title>
              </rect>
              <rect x={cx + 1} y={pad.t + innerH - useH} width={barW} height={useH} rx={3} fill="url(#g-use)">
                <title>{d.label}: จ่ายออก {d.use}</title>
              </rect>
              <text x={cx} y={H - 12} textAnchor="middle" className="chart-axis-text">{d.label}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function MiniDonut({ data, total, size = 150 }) {
  const R = size/2 - 14, sw = 18, cx = size/2, cy = size/2;
  const C = 2 * Math.PI * R;
  let acc = 0;
  if (total === 0) return <svg width={size} height={size}><circle cx={cx} cy={cy} r={R} fill="none" stroke="var(--border)" strokeWidth={sw}/></svg>;
  return (
    <svg width={size} height={size}>
      <circle cx={cx} cy={cy} r={R} fill="none" stroke="var(--surface-2)" strokeWidth={sw}/>
      {data.filter(d => d.value > 0).map(d => {
        const frac = d.value / total;
        const dash = frac * C;
        const offset = acc;
        acc += dash;
        return (
          <circle key={d.id || d.label}
            cx={cx} cy={cy} r={R} fill="none" stroke={d.color} strokeWidth={sw}
            strokeDasharray={`${dash} ${C - dash}`}
            strokeDashoffset={-offset}
            transform={`rotate(-90 ${cx} ${cy})`}
            strokeLinecap="butt"
          />
        );
      })}
      <text x={cx} y={cy + 2} textAnchor="middle" className="mono" style={{fontSize: 18, fontWeight: 600, fill: 'var(--text)'}}>{fmtNum(total)}</text>
      <text x={cx} y={cy + 18} textAnchor="middle" style={{fontSize: 10, fill: 'var(--text-3)'}}>ตลับ</text>
    </svg>
  );
}

Object.assign(window, { Sparkline, MonthlyChart, MiniDonut, getGreeting });
