/* ============================================================
   alerts.jsx — actionable list of due-soon / overdue instruments
   ============================================================ */
function Alerts({ instruments, go, initial }) {
  const [seg, setSeg] = useState(initial === 'danger' ? 'danger' : initial === 'warn' ? 'warn' : 'all');
  // reviews waiting for this account's signature (the positions it holds: จัดการผู้ใช้)
  const reviews = useSyncedStore(window.CalReviews);
  const toSign = window.calReviewsToSign ? window.calReviewsToSign(reviews, window.__SIGN_ROLES || []) : [];

  const groups = useMemo(() => {
    const overdue = [], soon = [], nodata = [], pmOverdue = [], pmSoon = [];
    const today = window.TODAY_ISO;
    const exempt = (v) => { const s = String(v == null ? '' : v).trim(); return !s || s === '-' || /n\/?a/i.test(s) || /ไม่ต้อง/.test(s); };
    instruments.forEach(i => {
      if (window.isDecommissioned && window.isDecommissioned(i)) return;   // retired: no calibration / PM falls due
      const s = statusOf(i);
      // statusOf carries `kind` ('cal' / 'pm' / 'na') — route into the right bucket
      if (s.kind === 'cal') {
        if (s.key === 'danger') overdue.push({ i, s });
        else if (s.key === 'warn') soon.push({ i, s });
        else if (s.key === 'none') nodata.push({ i, s });
      } else if (s.kind === 'pm') {
        if (s.key === 'danger') pmOverdue.push({ i, s });
        else if (s.key === 'warn') pmSoon.push({ i, s });
      }
      // Instruments that need BOTH cal AND PM: statusOf returns the cal-side
      // status (cal takes priority for the main badge). Surface PM alerts
      // separately here so a late PM still shows up while cal is still valid.
      if (!(window.isCalExempt && window.isCalExempt(i)) && !exempt(i.pmPerYear) && i.pmNext) {
        const dd = Math.round((new Date(i.pmNext + 'T00:00:00') - new Date(today + 'T00:00:00')) / 86400000);
        if (dd < 0)         pmOverdue.push({ i, s: { days: dd, label: 'PM เกินกำหนด', key: 'danger', kind: 'pm' } });
        else if (dd <= NEAR_DAYS) pmSoon.push({ i, s: { days: dd, label: 'ใกล้ครบ PM', key: 'warn', kind: 'pm' } });
      }
    });
    overdue.sort((a, b) => a.s.days - b.s.days);
    soon.sort((a, b) => a.s.days - b.s.days);
    pmOverdue.sort((a, b) => a.s.days - b.s.days);
    pmSoon.sort((a, b) => a.s.days - b.s.days);
    return { overdue, soon, nodata, pmOverdue, pmSoon };
  }, [instruments]);

  const AlertRow = ({ x, tone }) => {
    const { i, s } = x;
    const col = tone === 'danger' ? 'var(--danger)' : tone === 'warn' ? 'var(--warn)' : 'var(--none)';
    const soft = tone === 'danger' ? 'var(--danger-soft)' : tone === 'warn' ? 'var(--warn-soft)' : 'var(--none-soft)';
    return (
      // mouse can click anywhere on the row; keyboard / screen readers use the "จัดการ" button
      // inside it (a row-as-button would nest that button inside another)
      <div onClick={() => go('detail', { code: i.code })} className="alert-row"
        style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 20px', borderBottom: '1px solid var(--line-soft)', cursor: 'pointer' }}>
        {/* countdown chip */}
        <div style={{ width: 66, flex: 'none', textAlign: 'center', background: soft, borderRadius: 12, padding: '9px 4px' }}>
          <div className="figure" style={{ fontSize: 24, lineHeight: 1, color: statusInk(col) }}>{s.days != null ? Math.abs(s.days) : '—'}</div>
          <div style={{ fontSize: 'var(--fs-xs)', color: 'var(--ink-3)', marginTop: 2 }}>{s.days == null ? 'ไม่มีนัด' : s.days < 0 ? 'เกิน (วัน)' : 'อีก (วัน)'}</div>
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
            <span className="code" style={{ fontWeight: 600, fontSize: 13 }}>{i.code}</span>
            <DeptBadge dept={i.dept} />
          </div>
          <div style={{ fontWeight: 600, fontSize: 14.5, marginTop: 3, textWrap: 'pretty' }}>{i.type}</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 1 }}>
            {i.brand}{i.model && i.model !== '-' ? ` · ${i.model}` : ''} {i.exp ? `· ครบกำหนด ${fmtDateFull(i.exp)}` : '· ยังไม่มีข้อมูลสอบเทียบ'}
          </div>
        </div>
        <Pill status={s} />
        <button className="btn btn-sm" aria-label={'จัดการ ' + i.code} onClick={(e) => { e.stopPropagation(); go('detail', { code: i.code }); }}>จัดการ <I.chevR size={14} /></button>
      </div>
    );
  };

  const Section = ({ title, sub, tone, items, icon }) => {
    if (!items.length) return null;
    const Ico = icon;
    const col = tone === 'danger' ? 'var(--danger)' : tone === 'warn' ? 'var(--warn)' : 'var(--ink-3)';
    return (
      <div className="card enter" style={{ overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px 20px', borderBottom: '1px solid var(--line)' }}>
          <span style={{ width: 36, height: 36, borderRadius: 10, background: tone === 'danger' ? 'var(--danger-soft)' : tone === 'warn' ? 'var(--warn-soft)' : 'var(--none-soft)', color: statusInk(col), display: 'grid', placeItems: 'center' }}><Ico size={19} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 15.5 }}>{title}</div>
            <div className="page-sub">{sub}</div>
          </div>
          <span className="figure" style={{ fontSize: 24, color: statusInk(col) }}>{items.length}</span>
        </div>
        <div>{items.map(x => <AlertRow key={x.i.code} x={x} tone={tone} />)}</div>
      </div>
    );
  };

  const show = (k) => seg === 'all' || seg === k;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {toSign.length > 0 && (
        <div className="card card-pad">
          <div style={{ fontWeight: 600, fontSize: 15 }}>รอคุณลงนาม {toSign.length} ใบ</div>
          <div style={{ display: 'flex', flexDirection: 'column', marginTop: 8 }}>
            {toSign.map(({ rev, role }) => (
              <button key={rev.id} className="menu-item" style={{ width: '100%' }} onClick={() => go('detail', { code: rev.code })}>
                <I.shield size={16} /> <span className="code">{rev.code}</span> {rev.instType || ''} · {role.verb} · สอบเทียบ {fmtDateFull(rev.calDate)}
              </button>
            ))}
          </div>
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div className="seg">
          <button className={seg === 'all' ? 'on' : ''} onClick={() => setSeg('all')}>ทั้งหมด</button>
          <button className={seg === 'danger' ? 'on' : ''} onClick={() => setSeg('danger')}>เกินกำหนด ({groups.overdue.length})</button>
          <button className={seg === 'warn' ? 'on' : ''} onClick={() => setSeg('warn')}>ใกล้ครบ ({groups.soon.length})</button>
          <button className={seg === 'none' ? 'on' : ''} onClick={() => setSeg('none')}>ไม่มีข้อมูล ({groups.nodata.length})</button>
        </div>
        <div style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--ink-3)' }}>เกณฑ์เตือนล่วงหน้า {NEAR_DAYS} วัน · อ้างอิง {fmtDateFull(TODAY_ISO)}</div>
      </div>

      {groups.overdue.length === 0 && groups.soon.length === 0 && groups.nodata.length === 0 && groups.pmOverdue.length === 0 && groups.pmSoon.length === 0 && (
        <div className="card"><EmptyState icon={I.check} title="ไม่มีการแจ้งเตือน" sub="เครื่องมือทุกเครื่องอยู่ในเกณฑ์ปกติ" /></div>
      )}

      {show('danger') && <Section title="เกินกำหนดสอบเทียบ" sub="ต้องดำเนินการโดยด่วน — ห้ามใช้งานจนกว่าจะสอบเทียบใหม่" tone="danger" items={groups.overdue} icon={I.warning} />}
      {show('danger') && <Section title="เกินกำหนด PM" sub="ครบรอบบำรุงรักษาแล้ว — ติดต่อ Vendor เข้าทำ PM" tone="danger" items={groups.pmOverdue} icon={I.refresh} />}
      {show('warn') && <Section title="ใกล้ครบกำหนดสอบเทียบ" sub={`จะครบกำหนดภายใน ${NEAR_DAYS} วัน — ควรนัดหมายล่วงหน้า`} tone="warn" items={groups.soon} icon={I.clock} />}
      {show('warn') && <Section title="ใกล้ครบรอบ PM" sub={`ครบรอบ PM ภายใน ${NEAR_DAYS} วัน — ควรนัดหมาย Vendor`} tone="warn" items={groups.pmSoon} icon={I.refresh} />}
      {show('none') && <Section title="ยังไม่มีข้อมูลสอบเทียบ" sub="รอบันทึกวันสอบเทียบ/ครบกำหนด" tone="none" items={groups.nodata} icon={I.tag} />}
    </div>
  );
}
window.Alerts = Alerts;
