/* ============================================================
   calendar.jsx — monthly calibration / PM schedule
   ============================================================ */
function CalendarView({ instruments, go }) {
  const [cursor, setCursor] = useState(new Date(TODAY.getFullYear(), TODAY.getMonth(), 1));
  const [mode, setMode] = useState('month'); // month | agenda

  // map exp date -> instruments
  const byDate = useMemo(() => {
    const map = {};
    instruments.forEach(i => { if (i.exp) { (map[i.exp] = map[i.exp] || []).push(i); } });
    return map;
  }, [instruments]);

  const year = cursor.getFullYear(), month = cursor.getMonth();
  const monthName = `${THMONTH[month]} ${year + 543}`;
  const first = new Date(year, month, 1);
  const startDow = first.getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const monthEvents = useMemo(() => {
    const list = [];
    Object.entries(byDate).forEach(([date, insts]) => {
      const dt = parseD(date);
      if (dt.getFullYear() === year && dt.getMonth() === month) list.push({ date, dt, insts });
    });
    return list.sort((a, b) => a.dt - b.dt);
  }, [byDate, year, month]);

  const monthCount = monthEvents.reduce((n, e) => n + e.insts.length, 0);
  const isToday = (d) => TODAY.getFullYear() === year && TODAY.getMonth() === month && TODAY.getDate() === d;
  const dateStr = (d) => `${year}-${String(month+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;

  const DOW = ['อา','จ','อ','พ','พฤ','ศ','ส'];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <button className="btn btn-icon" onClick={() => setCursor(new Date(year, month - 1, 1))}><I.chevR size={17} style={{ transform: 'rotate(180deg)' }} /></button>
          <div className="figure" style={{ fontSize: 22, minWidth: 168, textAlign: 'center', color: 'var(--ink)' }}>{monthName}</div>
          <button className="btn btn-icon" onClick={() => setCursor(new Date(year, month + 1, 1))}><I.chevR size={17} /></button>
        </div>
        <button className="btn btn-sm" onClick={() => setCursor(new Date(TODAY.getFullYear(), TODAY.getMonth(), 1))}>เดือนนี้</button>
        <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>ครบกำหนดในเดือนนี้ <b className="tnum" style={{ color: 'var(--ink)' }}>{monthCount}</b> เครื่อง</span>
        <div style={{ marginLeft: 'auto' }} className="seg">
          <button className={mode === 'month' ? 'on' : ''} onClick={() => setMode('month')}>ปฏิทิน</button>
          <button className={mode === 'agenda' ? 'on' : ''} onClick={() => setMode('agenda')}>กำหนดการ</button>
        </div>
      </div>

      {mode === 'month' ? (
        <div className="card enter" style={{ overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', borderBottom: '1px solid var(--line)' }}>
            {DOW.map((d, i) => <div key={d} style={{ padding: '10px 12px', fontSize: 11.5, fontWeight: 600, color: i === 0 || i === 6 ? 'var(--ink-3)' : 'var(--ink-2)', textAlign: 'left', letterSpacing: '.03em' }}>{d}</div>)}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' }}>
            {cells.map((d, idx) => {
              const ds = d ? dateStr(d) : null;
              const evs = d && byDate[ds] ? byDate[ds] : [];
              const worst = evs.reduce((acc, i) => { const k = statusOf(i).key; return STATUS_ORDER[k] < STATUS_ORDER[acc] ? k : acc; }, 'ok');
              return (
                <div key={idx} style={{
                  minHeight: 104, padding: 7, borderRight: (idx % 7 !== 6) ? '1px solid var(--line-soft)' : 'none',
                  borderBottom: idx < cells.length - 7 ? '1px solid var(--line-soft)' : 'none',
                  background: d ? (isToday(d) ? 'var(--accent-softer)' : 'transparent') : 'var(--bg-sunk)',
                }}>
                  {d && (
                    <>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span className="tnum" style={{ fontSize: 12.5, fontWeight: isToday(d) ? 700 : 500, color: isToday(d) ? 'var(--accent-strong)' : 'var(--ink-2)', display: 'inline-grid', placeItems: 'center', width: 22, height: 22, borderRadius: 99, background: isToday(d) ? 'var(--accent)' : 'transparent', ...(isToday(d) ? { color: '#fff' } : {}) }}>{d}</span>
                        {evs.length > 0 && <span className="tnum" style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-3)' }}>{evs.length}</span>}
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 3, marginTop: 5 }}>
                        {evs.slice(0, 3).map(i => {
                          const k = statusOf(i).key;
                          const col = k === 'danger' ? 'var(--danger)' : k === 'warn' ? 'var(--warn)' : 'var(--ok)';
                          return (
                            <button key={i.code} onClick={() => go('detail', { code: i.code })} title={`${i.code} · ${i.type}`} style={{
                              display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'inherit', textAlign: 'left', cursor: 'pointer',
                              border: 'none', borderRadius: 6, padding: '2px 5px', background: 'var(--surface-2)', color: 'var(--ink-2)', fontSize: 10.5, width: '100%', overflow: 'hidden',
                            }}>
                              <span style={{ width: 6, height: 6, borderRadius: 2, background: col, flex: 'none' }} />
                              <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} className="code">{i.code.replace('LAB-', '')}</span>
                            </button>
                          );
                        })}
                        {evs.length > 3 && <span style={{ fontSize: 10, color: 'var(--ink-3)', paddingLeft: 5 }}>+{evs.length - 3} เพิ่มเติม</span>}
                      </div>
                    </>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      ) : (
        <div className="card enter">
          {monthEvents.length === 0 ? <EmptyState icon={I.calendar} title="ไม่มีกำหนดการในเดือนนี้" /> :
            monthEvents.map((e, idx) => (
              <div key={e.date} style={{ display: 'grid', gridTemplateColumns: '70px 1fr', gap: 16, padding: '16px 22px', borderBottom: idx < monthEvents.length - 1 ? '1px solid var(--line-soft)' : 'none' }}>
                <div style={{ textAlign: 'center' }}>
                  <div className="figure" style={{ fontSize: 26, color: 'var(--ink)' }}>{e.dt.getDate()}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{DOW[e.dt.getDay()]}.</div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {e.insts.map(i => {
                    const s = statusOf(i);
                    return (
                      <div key={i.code} onClick={() => go('detail', { code: i.code })} style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', padding: '8px 12px', borderRadius: 10, background: 'var(--surface-2)' }}>
                        <DeptDot dept={i.dept} />
                        <div style={{ minWidth: 0, flex: 1 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{i.type}</div>
                          <span className="code" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{i.code}</span>
                        </div>
                        <Pill status={s} showDays />
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
        </div>
      )}

      <div style={{ display: 'flex', gap: 18, fontSize: 12, color: 'var(--ink-3)', flexWrap: 'wrap' }}>
        {[['ปกติ', 'var(--ok)'], ['ใกล้ครบกำหนด', 'var(--warn)'], ['เกินกำหนด', 'var(--danger)']].map(([l, c]) =>
          <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: c }} />{l}</span>)}
      </div>
    </div>
  );
}
window.CalendarView = CalendarView;
