/* ============================================================
   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');

  const groups = useMemo(() => {
    const overdue = [], soon = [], nodata = [];
    instruments.forEach(i => {
      const s = statusOf(i);
      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 });
    });
    overdue.sort((a, b) => a.s.days - b.s.days);
    soon.sort((a, b) => a.s.days - b.s.days);
    return { overdue, soon, nodata };
  }, [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 (
      <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: col }}>{s.days != null ? Math.abs(s.days) : '—'}</div>
          <div style={{ fontSize: 9.5, 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" 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: 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: 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 }}>
      <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.toISOString().slice(0,10))}</div>
      </div>

      {groups.overdue.length === 0 && groups.soon.length === 0 && groups.nodata.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('warn') && <Section title="ใกล้ครบกำหนด" sub={`จะครบกำหนดภายใน ${NEAR_DAYS} วัน — ควรนัดหมายล่วงหน้า`} tone="warn" items={groups.soon} icon={I.clock} />}
      {show('none') && <Section title="ยังไม่มีข้อมูลสอบเทียบ" sub="รอบันทึกวันสอบเทียบ/ครบกำหนด" tone="none" items={groups.nodata} icon={I.tag} />}
    </div>
  );
}
window.Alerts = Alerts;
