/* ============================================================
   dashboard.jsx — overview: readiness, alerts, department health
   ============================================================ */
function StatCard({ label, value, sub, tone, icon, onClick, labomniq = false }) {
  const Ico = icon;
  const toneColor = { ok: 'var(--ok)', warn: 'var(--warn)', danger: 'var(--danger)', none: 'var(--ink-3)', accent: 'var(--accent)' }[tone] || 'var(--ink)';
  const toneSoft = { ok: 'var(--ok-soft)', warn: 'var(--warn-soft)', danger: 'var(--danger-soft)', none: 'var(--none-soft)', accent: 'var(--accent-soft)' }[tone] || 'var(--surface-2)';
  if (labomniq) return (
    <button className={`card card-pad enter lab-stat lab-stat-${tone}`} onClick={onClick}>
      <span className="lab-stat-icon">{Ico && <Ico size={19} />}</span>
      <div className="lab-stat-content"><span className="lab-stat-label">{label}</span><div className="lab-stat-bottom"><span className="figure">{value}</span>{sub && <span className="lab-stat-sub">{sub}</span>}</div></div>
      {onClick && <I.chevR size={14} className="lab-stat-chevron" />}
    </button>
  );
  return (
    <button className="card card-pad enter" onClick={onClick} style={{
      textAlign: 'left', cursor: onClick ? 'pointer' : 'default', display: 'flex', flexDirection: 'column', gap: 14,
      border: '1px solid var(--line)', background: 'var(--surface)', transition: 'transform .12s, box-shadow .15s, border-color .15s',
    }}
    onMouseEnter={e => { if (onClick) { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = 'var(--shadow)'; } }}
    onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-2)' }}>{label}</span>
        <span style={{ width: 32, height: 32, borderRadius: 9, background: toneSoft, color: statusInk(toneColor), display: 'grid', placeItems: 'center' }}>
          {Ico && <Ico size={17} />}
        </span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span className="figure" style={{ fontSize: 38, color: statusInk(tone === 'accent' ? 'var(--ink)' : toneColor === 'var(--ink)' ? 'var(--ink)' : toneColor) }}>{value}</span>
        {sub && <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{sub}</span>}
      </div>
    </button>
  );
}

function Dashboard({ instruments, go, setFilter, labomniq = false }) {
  // headline figures count only ACTIVE instruments (retired ones are excluded)
  const activeInstruments = useMemo(() => instruments.filter(i => !window.isDecommissioned(i)), [instruments]);
  const decommTotal = instruments.length - activeInstruments.length;
  const stats = useMemo(() => {
    let ok = 0, warn = 0, danger = 0, none = 0;
    activeInstruments.forEach(i => { const s = statusOf(i).key; if (s === 'ok') ok++; else if (s === 'warn') warn++; else if (s === 'danger') danger++; else none++; });
    return { total: activeInstruments.length, ok, warn, danger, none };
  }, [activeInstruments]);

  // "available" = currently usable = valid (ปกติ) + due-soon (ใกล้ครบ, still
  // within validity). Only overdue (เกิน) and no-data reduce readiness.
  const readyCount = stats.ok + stats.warn;
  const readiness = stats.total ? Math.round((readyCount / stats.total) * 100) : 0;

  const deptRows = useMemo(() => {
    const map = {};
    activeInstruments.forEach(i => {
      const d = i.dept || '—';
      map[d] = map[d] || { dept: d, total: 0, ok: 0, warn: 0, danger: 0, none: 0 };
      map[d].total++;
      const s = statusOf(i).key; map[d][s]++;
    });
    // same meaning as the headline figure: usable now = valid + due soon (still within validity)
    return Object.values(map).map(r => ({ ...r, pct: Math.round(((r.ok + r.warn) / r.total) * 100) }))
      .sort((a, b) => a.pct - b.pct);
  }, [instruments]);

  const upcoming = useMemo(() => {
    return activeInstruments
      .map(i => ({ i, s: statusOf(i) }))
      .filter(x => x.s.days != null && x.s.days <= NEAR_DAYS)
      .sort((a, b) => a.s.days - b.s.days)
      .slice(0, 7);
  }, [instruments]);

  const topTypes = useMemo(() => {
    const m = {};
    activeInstruments.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));

  // ---- auditor-readiness (ISO 15189) ----
  // required register fields only (model/serial/asset are optional → blank = N/A, not a gap);
  // calibration completeness is driven by the calResult status field (4 states).
  const FIELD_LABEL = { brand: 'ยี่ห้อ', calStatus: 'สถานะ/ผลสอบเทียบ' };
  const calState = (i) => {
    const r = String(i.calResult || '').trim();
    if (window.isDecommissioned(i)) return 'decomm';
    // not required to calibrate (calPerYear blank/-/N/A) → N/A, not a data gap
    const cpy = String(i.calPerYear == null ? '' : i.calPerYear).trim();
    if (!cpy || cpy === '-' || /n\/?a/i.test(cpy) || /ไม่ต้อง/.test(cpy)) return 'na';
    if (/ไม่ผ่าน|fail/i.test(r)) return 'fail';   // check fail before pass (ไม่ผ่าน contains ผ่าน)
    if (/ผ่าน|pass/i.test(r)) return 'pass';
    if (/n\/?a|ไม่ต้อง/i.test(r)) return 'na';
    if (/รอ|pending/i.test(r)) return 'pending';
    return 'unset';   // no calibration status recorded yet → a real gap
  };
  const audit = useMemo(() => {
    const filled = (v) => v != null && v !== '' && v !== '-';
    let complete = 0, pass = 0, pending = 0, na = 0, decomm = 0;
    const incomplete = [], outService = [], pm = [];
    instruments.forEach(i => {
      const cs = calState(i);
      if (cs === 'decomm') { decomm++; return; }            // retired → out of the active register count
      if (cs === 'pass') pass++; else if (cs === 'pending') pending++; else if (cs === 'na') na++;
      const missing = [];
      if (!filled(i.brand)) missing.push('brand');
      if (cs === 'unset') missing.push('calStatus');
      if (missing.length === 0) complete++;
      else incomplete.push({ i, missing });
      const meta = window.instrumentMeta(i);
      if (meta.op.key === 'repair' || meta.op.key === 'down') outService.push({ i, op: meta.op });
      if (meta.pmNext) { const d = daysUntil(meta.pmNext); if (d != null && d <= NEAR_DAYS) pm.push({ i, d, pmNext: meta.pmNext }); }
    });
    pm.sort((a, b) => a.d - b.d);
    outService.sort((a, b) => (a.op.key === 'down' ? -1 : 1));
    const activeTotal = instruments.length - decomm;
    return {
      completePct: activeTotal ? Math.round((complete / activeTotal) * 100) : 100,
      fullyComplete: complete, incompleteCount: incomplete.length, incomplete: incomplete.slice(0, 6),
      activeTotal, pass, pending, na, decomm,
      outService, outCount: outService.length, pm: pm.slice(0, 6), pmCount: pm.length,
    };
  }, [instruments]);

  return (
    <div className={labomniq ? 'lab-dashboard' : undefined} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* hero readiness banner */}
      <div className="card enter dash-hero" style={{ overflow: 'hidden' }}>
        {labomniq && <div className="lab-hero-photo" aria-hidden="true" />}
        <div className="lab-hero-body" style={{ padding: '26px 28px' }}>
          <div className="lab-hero-heading">{labomniq && <span className="lab-hero-symbol"><I.shield size={25} /></span>}<div><h2 className="sec-title" style={{ fontWeight: 600, fontSize: 16 }}>{labomniq ? 'Laboratory Overview' : 'ความพร้อมใช้งานของเครื่องมือ'}</h2>{labomniq && <p>ภาพรวมความพร้อมเครื่องมือของห้องปฏิบัติการ</p>}</div>{labomniq && <span className="lab-hero-motto">SMART ASSETS<br />SAFER LABS<br />BETTER CARE</span>}</div>
          <div className="lab-readiness-main" style={{ display: 'flex', alignItems: 'baseline', gap: 16, marginTop: 10 }}>
            <span className="figure" style={{ fontSize: 64, lineHeight: 1, color: 'var(--ink)', flex: 'none' }}>{readiness}<span style={{ fontSize: 30, color: 'var(--ink-3)' }}>%</span></span>
            <div className="lab-readiness-description" style={{ fontSize: 14 }}>
              <div style={{ color: 'var(--ink-2)' }}>เครื่องมือพร้อมใช้งาน <b className="tnum" style={{ color: 'var(--ink)' }}>{readyCount}</b> จาก <b className="tnum" style={{ color: 'var(--ink)' }}>{stats.total}</b> เครื่อง</div>
              <div style={{ color: 'var(--ink-4)', fontSize: 13, marginTop: 3 }}>ณ {fmtDateFull(TODAY_ISO)}{decommTotal ? ` · ไม่รวมเครื่องปลดระวาง ${decommTotal} เครื่อง` : ''}</div>
            </div>
          </div>
          {/* stacked status bar */}
          <div className="lab-readiness-track" style={{ display: 'flex', height: 12, borderRadius: 99, overflow: 'hidden', marginTop: 20, gap: 2, background: 'var(--surface-2)' }}>
            {[['ok', stats.ok, 'var(--ok)'], ['warn', stats.warn, 'var(--warn)'], ['none', stats.none, 'var(--none)'], ['danger', stats.danger, 'var(--danger)']].map(([k, v, c]) =>
              v > 0 && <div key={k} title={`${v}`} style={{ width: `${(v / stats.total) * 100}%`, background: c }} />)}
          </div>
          <div className="lab-readiness-legend" style={{ display: 'flex', gap: 18, marginTop: 14, flexWrap: 'wrap' }}>
            {[['ปกติ', stats.ok, 'var(--ok)'], ['ใกล้ครบกำหนด', stats.warn, 'var(--warn)'], ['ไม่มีข้อมูล', stats.none, 'var(--none)'], ['เกินกำหนด', stats.danger, 'var(--danger)']].map(([l, v, c]) =>
              <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--ink-2)' }}>
                <span style={{ width: 9, height: 9, borderRadius: 3, background: c }} /> {l} <b className="tnum" style={{ color: 'var(--ink)' }}>{v}</b>
              </span>)}
          </div>
        </div>
      </div>

      {/* stat cards */}
      <div className="kpi-grid">
        <StatCard labomniq={labomniq} label="เครื่องมือที่ใช้งาน" value={stats.total} sub={decommTotal ? `ปลดระวาง ${decommTotal}` : 'รายการ'} tone="accent" icon={I.beaker} onClick={() => { setFilter && setFilter('all'); go('inventory'); }} />
        <StatCard labomniq={labomniq} label="ใกล้ครบกำหนด" value={stats.warn} sub={`ภายใน ${NEAR_DAYS} วัน`} tone="warn" icon={I.clock} onClick={() => { setFilter && setFilter('warn'); go('alerts'); }} />
        <StatCard labomniq={labomniq} label="เกินกำหนดสอบเทียบ / PM" value={stats.danger} sub="ต้องดำเนินการ" tone="danger" icon={I.warning} onClick={() => { setFilter && setFilter('danger'); go('alerts'); }} />
        <StatCard labomniq={labomniq} label="ไม่มีข้อมูลครบกำหนด" value={stats.none} sub="รอบันทึก" tone="none" icon={I.tag} onClick={() => { setFilter && setFilter('none'); go('inventory'); }} />
      </div>
      {labomniq && <p className="lab-status-note">สถานะใช้กำหนดสอบเทียบเป็นหลัก · เครื่องที่ไม่ต้องสอบเทียบใช้กำหนด PM แทน</p>}

      <div className="dash-two">
        {/* department readiness */}
        <div className="card enter">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px 12px' }}>
            <div style={{ minWidth: 0 }}>
              <h2 className="sec-title" style={{ fontWeight: 600, fontSize: 16 }}>ความพร้อมรายแผนก</h2>
              <div className="page-sub">% พร้อมใช้งาน (ปกติ + ใกล้ครบกำหนด) · เรียงจากแผนกที่ต้องดูแลก่อน</div>
            </div>
            <span className="chip" style={{ flex: 'none' }} {...pressable(() => go('inventory'))}>ดูทั้งหมด <I.chevR size={14} /></span>
          </div>
          <hr className="divider" />
          <div style={{ padding: '8px 22px 18px' }}>
            {deptRows.map((r, idx) => (
              <div key={r.dept} className="dept-health-row" style={{ display: 'grid', gridTemplateColumns: '188px 1fr 52px', gap: 14, alignItems: 'center', padding: '11px 0', borderBottom: idx < deptRows.length - 1 ? '1px solid var(--line-soft)' : 'none', cursor: 'pointer' }}
                {...pressable(() => { setFilter && setFilter('all'); go('inventory', { dept: r.dept }); })}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
                  {labomniq ? <span className="lab-dept-icon" style={{ color: deptColor(r.dept) }}>{(() => { const DI = (typeof deptIcon === 'function' ? deptIcon(r.dept) : null) || I.building; return <DI size={23} />; })()}</span> : <DeptDot dept={r.dept} />}
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{(DEPT_META[r.dept] || {}).short || r.dept}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }} className="tnum">{r.total} เครื่อง</div>
                  </div>
                </div>
                <div className="bar dh-bar" style={{ background: 'var(--surface-2)' }}>
                  <span style={{ width: `${r.pct}%`, background: r.pct >= 80 ? 'var(--ok)' : r.pct >= 55 ? 'var(--warn)' : 'var(--danger)' }} />
                </div>
                <div className="figure tnum" style={{ fontSize: 17, textAlign: 'right', color: 'var(--ink)' }}>{r.pct}%</div>
              </div>
            ))}
          </div>
        </div>

        {/* upcoming / due */}
        <div className="card enter">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px 12px' }}>
            <div style={{ minWidth: 0 }}>
              <h2 className="sec-title" style={{ fontWeight: 600, fontSize: 16 }}>คิวงานที่ต้องดำเนินการ</h2>
              <div className="page-sub">7 รายการเร่งด่วนที่สุด รวมงานเกินกำหนด · ใช้กำหนดสอบเทียบเป็นหลัก เครื่องที่ไม่ต้องสอบเทียบใช้กำหนด PM · PM ของเครื่องอื่นดูการ์ด PM</div>
            </div>
            <span className="chip" style={{ flex: 'none' }} {...pressable(() => go('alerts'))}>การแจ้งเตือน <I.chevR size={14} /></span>
          </div>
          <hr className="divider" />
          <div>
            {upcoming.length === 0 && <EmptyState icon={I.check} title="ไม่มีงานในคิว" sub={`ไม่มีเครื่องเกินกำหนดหรือครบกำหนดภายใน ${NEAR_DAYS} วัน`} />}
            {upcoming.map((x, idx) => {
              const s = x.s;
              return (
                <div key={x.i.code} {...pressable(() => go('detail', { code: x.i.code }))}
                  style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 22px', borderBottom: idx < upcoming.length - 1 ? '1px solid var(--line-soft)' : 'none', cursor: 'pointer' }}
                  className="upcoming-row">
                  <div style={{ width: 44, textAlign: 'center', flex: 'none' }}>
                    <div className="figure" style={{ fontSize: 22, lineHeight: 1, color: s.key === 'danger' ? 'var(--danger-ink)' : 'var(--warn-ink)' }}>{Math.abs(s.days)}</div>
                    <div style={{ fontSize: 'var(--fs-xs)', color: 'var(--ink-3)' }}>{s.days < 0 ? 'เกิน(วัน)' : 'วัน'}</div>
                  </div>
                  <div style={{ width: 1, height: 30, background: 'var(--line)' }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.i.type}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span className="code" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{x.i.code}</span>
                      <DeptDot dept={x.i.dept} />
                    </div>
                  </div>
                  <Pill status={s} />
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* top instrument types */}
      <div className="card enter card-pad">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ minWidth: 0 }}>
            <h2 className="sec-title" style={{ fontWeight: 600, fontSize: 16 }}>ชนิดเครื่องมือที่มีมากที่สุด</h2>
            <div className="page-sub">6 อันดับแรกตามจำนวนในทะเบียน</div>
          </div>
          <span className="chip" style={{ flex: 'none' }} {...pressable(() => go('analytics'))}>วิเคราะห์เชิงลึก <I.chevR size={14} /></span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 36px' }} className="dash-grid">
          {topTypes.map((tp, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 80px 32px', gap: 12, alignItems: 'center', padding: '8px 0' }}>
              <span style={{ fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={tp.name}>{tp.name}</span>
              <div className="bar" style={{ background: 'var(--surface-2)' }}><span style={{ width: `${(tp.count / topMax) * 100}%`, background: deptColor(tp.dept) }} /></div>
              <span className="figure tnum" style={{ fontSize: 16, textAlign: 'right' }}>{tp.count}</span>
            </div>
          ))}
        </div>
      </div>

      {/* ===== auditor readiness (ISO 15189) ===== */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 4 }}>
        <span style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--accent-soft)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center', flex: 'none' }}><I.shield size={18} /></span>
        <div style={{ minWidth: 0 }}>
          <h2 className="sec-title" style={{ fontWeight: 600, fontSize: 16, whiteSpace: 'nowrap' }}>พร้อมสำหรับการตรวจประเมิน (ISO 15189)</h2>
          <div className="page-sub">หลักฐานการควบคุมเครื่องมือที่ผู้ตรวจประเมินมักขอดู</div>
        </div>
      </div>

      <div className="dash-three">
        {/* data completeness */}
        <div className="card enter card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <h3 className="sec-title" style={{ fontWeight: 600, fontSize: 15 }}>ความครบถ้วนของทะเบียน</h3>
            <div className="page-sub">Master list completeness</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <Ring pct={audit.completePct} size={92} stroke={9} label={`${audit.completePct}%`} sub="ครบถ้วน"
              color={audit.completePct >= 85 ? 'var(--ok)' : audit.completePct >= 60 ? 'var(--warn)' : 'var(--danger)'} />
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.7 }}>
              <div>ทะเบียนครบถ้วน <b className="tnum" style={{ color: 'var(--ink)' }}>{audit.fullyComplete}</b>/{audit.activeTotal} เครื่องที่ใช้งาน</div>
              <div>ต้องเติมข้อมูล <b className="tnum" style={{ color: audit.incompleteCount ? 'var(--warn-ink)' : 'var(--ok-ink)' }}>{audit.incompleteCount}</b> เครื่อง{audit.decomm ? <span style={{ color: 'var(--ink-4)' }}> · ปลดระวาง {audit.decomm}</span> : null}</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, fontSize: 11.5 }}>
            <span className="pill ok" style={{ fontSize: 11 }}><span className="dot" /> ผ่านสอบเทียบ {audit.pass}</span>
            <span className="pill warn" style={{ fontSize: 11 }}><span className="dot" /> รอสอบเทียบ {audit.pending}</span>
            <span className="pill none" style={{ fontSize: 11 }}><span className="dot" /> ไม่ต้องสอบเทียบ {audit.na}</span>
          </div>
          {audit.incomplete.length > 0 && (
            <div style={{ borderTop: '1px solid var(--line-soft)', paddingTop: 10, display: 'flex', flexDirection: 'column', gap: 2 }}>
              {audit.incomplete.map(x => (
                <div key={x.i.code} {...pressable(() => go('detail', { code: x.i.code }))} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, minHeight: 24 }}>
                  <span className="code" style={{ color: 'var(--ink-2)', fontWeight: 600, whiteSpace: 'nowrap' }}>{x.i.code}</span>
                  <span style={{ color: 'var(--ink-4)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>ขาด {x.missing.map(f => FIELD_LABEL[f]).join(', ')}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* out of service */}
        <div className="card enter">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px 12px' }}>
            <div style={{ minWidth: 0 }}>
              <h3 className="sec-title" style={{ fontWeight: 600, fontSize: 15, whiteSpace: 'nowrap' }}>เครื่องงดใช้ / รอซ่อม</h3>
              <div className="page-sub">หลักฐานการกันเครื่องที่ชำรุดออกจากการใช้งาน</div>
            </div>
            <span className="figure" style={{ fontSize: 24, color: audit.outCount ? 'var(--danger-ink)' : 'var(--ok-ink)', flex: 'none' }}>{audit.outCount}</span>
          </div>
          <hr className="divider" />
          {audit.outService.length === 0 ? <EmptyState icon={I.check} title="ไม่มีเครื่องงดใช้" sub="เครื่องมือทุกเครื่องพร้อมใช้งาน" /> : (
            <div>
              {audit.outService.slice(0, 6).map((x, idx) => (
                <div key={x.i.code} {...pressable(() => go('detail', { code: x.i.code }))} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 22px', borderBottom: idx < Math.min(audit.outService.length, 6) - 1 ? '1px solid var(--line-soft)' : 'none', cursor: 'pointer' }}>
                  <span style={{ width: 8, height: 8, borderRadius: 99, background: x.op.key === 'down' ? 'var(--danger)' : 'var(--warn)', flex: 'none' }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.i.type}</div>
                    <span className="code" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{x.i.code}</span>
                  </div>
                  <span style={{ fontSize: 11.5, fontWeight: 600, color: x.op.key === 'down' ? 'var(--danger-ink)' : 'var(--warn-ink)' }}>{x.op.label}</span>
                </div>
              ))}
              <div style={{ padding: '10px 22px' }}><span className="chip" {...pressable((e) => { e.stopPropagation(); go('repair'); })}>ไปที่งานแจ้งซ่อม <I.chevR size={14} /></span></div>
            </div>
          )}
        </div>

        {/* PM near due */}
        <div className="card enter">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px 12px' }}>
            <div style={{ minWidth: 0 }}>
              <h3 className="sec-title" style={{ fontWeight: 600, fontSize: 15, whiteSpace: 'nowrap' }}>บำรุงรักษา (PM) ใกล้ถึง</h3>
              <div className="page-sub">แผน PM ที่เกินกำหนดหรือครบกำหนดภายใน {NEAR_DAYS} วัน</div>
            </div>
            <span className="figure" style={{ fontSize: 24, color: audit.pmCount ? 'var(--warn-ink)' : 'var(--ok-ink)', flex: 'none' }}>{audit.pmCount}</span>
          </div>
          <hr className="divider" />
          {audit.pm.length === 0 ? <EmptyState icon={I.check} title="ไม่มี PM ใกล้ถึง" sub="แผนบำรุงรักษาเป็นปัจจุบัน" /> : (
            <div>
              {audit.pm.map((x, idx) => (
                <div key={x.i.code} {...pressable(() => go('detail', { code: x.i.code }))} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 22px', borderBottom: idx < audit.pm.length - 1 ? '1px solid var(--line-soft)' : 'none', cursor: 'pointer' }}>
                  <div style={{ width: 40, textAlign: 'center', flex: 'none' }}>
                    <div className="figure" style={{ fontSize: 20, lineHeight: 1, color: x.d < 0 ? 'var(--danger-ink)' : 'var(--accent)' }}>{Math.abs(x.d)}</div>
                    <div style={{ fontSize: 'var(--fs-xs)', color: 'var(--ink-3)' }}>{x.d < 0 ? 'เกิน(วัน)' : 'วัน'}</div>
                  </div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.i.type}</div>
                    <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>PM {fmtDate(x.pmNext)}</span>
                  </div>
                  <DeptDot dept={x.i.dept} />
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
window.Dashboard = Dashboard;
