/* ============================================================
   analytics.jsx — instrument analytics (RM-LIS dashboard patterns,
   our data): donut by department, monthly calibration-due trend,
   top instrument types, responsible-owner stats.
   ============================================================ */
function Donut({ data, total }) {
  const size = 188, r = 74, sw = 26, cx = size / 2, cy = size / 2;
  const C = 2 * Math.PI * r;
  let acc = 0;
  return (
    <div style={{ position: 'relative', width: size, height: size, flex: 'none' }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--surface-2)" strokeWidth={sw} />
        {data.map((d, i) => {
          const frac = d.value / total;
          const dash = frac * C;
          const seg = <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={d.color} strokeWidth={sw}
            strokeDasharray={`${dash} ${C - dash}`} strokeDashoffset={-acc * C}
            style={{ transition: 'stroke-dasharray .7s, stroke-dashoffset .7s' }} />;
          acc += frac;
          return seg;
        })}
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
        <div>
          <div className="figure" style={{ fontSize: 34 }}>{total}</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>เครื่องมือ</div>
        </div>
      </div>
    </div>
  );
}

function Analytics({ instruments, go }) {
  const total = instruments.length;

  const byDept = useMemo(() => {
    const m = {};
    instruments.forEach(i => { m[i.dept] = (m[i.dept] || 0) + 1; });
    return Object.entries(m).map(([dept, value]) => ({ dept, value, color: deptColor(dept), short: (DEPT_META[dept] || {}).short || dept }))
      .sort((a, b) => b.value - a.value);
  }, [instruments]);

  // monthly calibration-due over the next 6 months (incl. this month)
  const trend = useMemo(() => {
    const months = [];
    for (let k = 0; k < 6; k++) {
      const d = new Date(TODAY.getFullYear(), TODAY.getMonth() + k, 1);
      months.push({ y: d.getFullYear(), m: d.getMonth(), label: THMONTH[d.getMonth()], count: 0 });
    }
    instruments.forEach(i => {
      if (!i.exp) return;
      const e = parseD(i.exp);
      const hit = months.find(mo => mo.y === e.getFullYear() && mo.m === e.getMonth());
      if (hit) hit.count++;
    });
    return months;
  }, [instruments]);
  const trendMax = Math.max(1, ...trend.map(t => t.count));

  const topTypes = useMemo(() => {
    const m = {};
    instruments.forEach(i => { const key = i.type || i.typeName || '—'; m[key] = m[key] || { name: key, count: 0, dept: i.dept }; m[key].count++; });
    return Object.values(m).sort((a, b) => b.count - a.count).slice(0, 6);
  }, [instruments]);
  const topMax = Math.max(1, ...topTypes.map(t => t.count));

  const owners = useMemo(() => {
    const m = {};
    instruments.forEach(i => { const o = window.instrumentMeta(i).owner; m[o] = (m[o] || 0) + 1; });
    return Object.entries(m).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count).slice(0, 8);
  }, [instruments]);
  const ownerMax = Math.max(1, ...owners.map(o => o.count));

  const kpis = useMemo(() => {
    let ok = 0, warn = 0, danger = 0, none = 0;
    instruments.forEach(i => { const k = statusOf(i).key; if (k === 'ok') ok++; else if (k === 'warn') warn++; else if (k === 'danger') danger++; else none++; });
    return { ok, warn, danger, none, rate: total ? Math.round((ok / total) * 100) : 0 };
  }, [instruments, total]);

  const Card = ({ tag, title, sub, children, style }) => (
    <div className="card card-pad enter" style={style}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 3 }}>
        <span className="tag-h">{tag}</span>
        <span style={{ fontWeight: 600, fontSize: 15 }}>{title}</span>
      </div>
      {sub && <div className="page-sub" style={{ marginBottom: 16 }}>{sub}</div>}
      {children}
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* head */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Instruments · Analytics</div>
          <h2 style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-.02em', margin: '6px 0 2px' }}>ภาพรวมเชิงวิเคราะห์</h2>
          <div className="page-sub">การกระจายตามแผนก แนวโน้มการสอบเทียบ และสถิติเชิงลึกของเครื่องมือ {total} รายการ</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-sm" onClick={() => window.printReport(instruments, { subtitle: 'รายงานวิเคราะห์เครื่องมือ' })}><I.download size={15} /> PDF</button>
          <button className="btn btn-sm" onClick={() => window.exportCSV(instruments, 'lab-analytics')}><I.grid size={15} /> Excel</button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        {[['ความพร้อมรวม', kpis.rate + '%', 'var(--accent)', 'พร้อมใช้ ' + kpis.ok], ['ใกล้ครบกำหนด', kpis.warn, 'var(--warn)', '≤ ' + NEAR_DAYS + ' วัน'], ['เกินกำหนด', kpis.danger, 'var(--danger)', 'ต้องดำเนินการ'], ['ไม่มีข้อมูล', kpis.none, 'var(--ink-3)', 'รอบันทึก']].map(([l, v, c, s], i) => (
          <div key={i} className="card card-pad enter" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>{l}</span>
            <span className="figure" style={{ fontSize: 34, color: c }}>{v}</span>
            <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{s}</span>
          </div>
        ))}
      </div>

      {/* donut + trend */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.15fr 1fr', gap: 18 }} className="dash-grid">
        <Card tag="DEPT" title="สัดส่วนตามแผนก" sub="การกระจายเครื่องมือในแต่ละกลุ่มงาน">
          <div className="donut-wrap">
            <Donut data={byDept} total={total} />
            <div className="donut-legend">
              {byDept.map((d, i) => (
                <div className="dleg" key={i} style={{ cursor: 'pointer' }} onClick={() => go('inventory', { dept: d.dept })}>
                  <span className="sw" style={{ background: d.color }} />
                  <span className="nm">{d.short}</span>
                  <span className="vv">{d.value}</span>
                  <span className="pp">{Math.round((d.value / total) * 100)}%</span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card tag="TREND" title="แนวโน้มครบกำหนดสอบเทียบ" sub="จำนวนเครื่องที่ถึงกำหนด · 6 เดือนข้างหน้า">
          <div className="vbars">
            {trend.map((t, i) => (
              <div className="vbar-col" key={i}>
                <span className="vbar-v">{t.count}</span>
                <div className="vbar" style={{ height: `${Math.max(4, (t.count / trendMax) * 100)}%` }} />
                <span className="vbar-l">{t.label}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}
window.Analytics = Analytics;
