/* ============================================================
   templog.jsx — fridge/freezer/incubator temperature log
   (FM-CL-00-045). Pick a temperature-controlled instrument →
   monthly grid, out-of-range highlight, corrective actions,
   print with the shared FR/FM header. Months live in
   window.TempLogs (sync.js: localStorage + GAS 'TempLogs' tab).
   ============================================================ */
const FRZ_TARGETS = [-20, -30, -40, -80];
const TL_MONTHS = THMONTH;
const TL_DEFAULT_TIME = { am: '09:00', pm: '15:00' };  // auto-filled on first reading of a session
const TL_EDIT_DAYS = 7;   // how far back a general user corrects a reading (the server holds the same limit)
const tlDayStart = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
const tlCorrId = () => 'r' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
// compact recorder initials, e.g. "ทนพ. พีรภัทร ภักตะภา" → "พ.ภ."
function tlInitials(name) {
  const s = String(name || '').trim();
  if (!s) return '';
  const parts = s.split(/\s+/).filter(p => !/^(นาย|นาง|นางสาว|ทนพ\.?|ทนพญ\.?|ดร\.?|พญ\.?|นพ\.?|ภญ\.?|ภก\.?)$/.test(p));
  const use = (parts.length >= 2 ? parts.slice(-2) : parts).filter(Boolean);
  if (!use.length) return s.charAt(0) + '.';
  return use.map(p => p.charAt(0)).join('.') + '.';
}

function tempProfile(inst) {
  const s = `${inst.type || ''} ${inst.typeName || ''} ${inst.code || ''}`.toLowerCase();
  const abbr = (inst.code || '').split('-')[2] || '';
  const has = (...k) => k.some(x => s.includes(x));
  if (has('เกล็ดเลือด', 'platelet') || ['PLT', 'PAG'].includes(abbr))
    return { cat: 'plt', word: 'ตู้เก็บเกล็ดเลือด', chambers: [{ key: 't', name: 'อุณหภูมิ', min: 20, max: 24 }] };
  if (has('เพาะเชื้อ', 'incubat', 'co2', ' 37') || ['INC', 'CO2', 'INB'].includes(abbr))
    return { cat: 'inc', word: 'ตู้อบเพาะเชื้อ', chambers: [{ key: 't', name: 'อุณหภูมิ', min: 35, max: 39 }] };
  if (has('แช่แข็ง', 'freez', '-20', '-30', '-40', '-80') || ['FRZ', 'FZR', 'FZ'].includes(abbr))
    return { cat: 'frz', word: 'ตู้แช่แข็ง', freezer: true, target: -20, chambers: [{ key: 'f', name: 'ช่องแช่แข็ง', min: -25, max: -15 }] };
  if (has('ตู้เย็น', 'refriger', '2-8', '2–8', 'iqc') || ['REF', 'BBR', 'BBK', 'FRG'].includes(abbr))
    return { cat: 'ref', word: 'ตู้เย็น', chambers: [{ key: 'c', name: 'ช่องแช่เย็น', min: 2, max: 8 }] };
  if (has('อุณหภูมิ', 'temp') || abbr === 'TMR')
    return { cat: 'ref', word: 'ตู้ควบคุมอุณหภูมิ', chambers: [{ key: 'c', name: 'อุณหภูมิ', min: 2, max: 8 }] };
  return null;
}

/* temperature trend chart — used on-screen (themed) and inside the printed
   sheet (print=true → fixed light colours, since the form is always white) */
function TempChart({ chambers, days, cell, sessions, cnt, monthLabel, rangeText, print }) {
  const C = print
    ? { am: '#d9730d', pm: '#2563eb', band: '#16a34a', bandOp: '0.12', grid: '#cccccc', gridText: '#666666', oor: '#dc2626', title: '#111111', sub: '#555555', ink: '#111111', ok: '#16a34a' }
    : { am: 'var(--accent)', pm: 'oklch(0.55 0.13 250)', band: 'var(--ok)', bandOp: '0.10', grid: 'var(--line)', gridText: 'var(--ink-4)', oor: 'var(--danger)', title: 'var(--ink)', sub: 'var(--ink-3)', ink: 'var(--ink)', ok: 'var(--ok)' };
  const SESS_COL = { am: C.am, pm: C.pm };
  const series = [];
  chambers.forEach((c, ci) => sessions.forEach(([sk]) => {
    const pts = [];
    days.forEach(d => { const raw = cell(d, sk, c.key); if (raw === '' || raw == null) return; const v = parseFloat(raw); if (isNaN(v)) return; pts.push({ t: d - 1, v, oor: v < c.min || v > c.max }); });
    if (pts.length) series.push({ c, sk, color: SESS_COL[sk] || C.am, dash: sk === 'pm', pts });
  }));
  const allPts = series.reduce((a, s) => a.concat(s.pts), []);
  if (!allPts.length) {
    if (print) return null;
    return <div className="card card-pad tl-noprint" style={{ marginBottom: 14, color: 'var(--ink-3)', textAlign: 'center', fontSize: 13 }}><I.pie size={15} style={{ verticalAlign: '-2px', marginRight: 6 }} />กราฟเทรนด์อุณหภูมิจะแสดงเมื่อกรอกค่าในตารางด้านล่าง</div>;
  }
  const vals = allPts.map(p => p.v);
  let lo = Math.min.apply(null, vals.concat(chambers.map(c => c.min)));
  let hi = Math.max.apply(null, vals.concat(chambers.map(c => c.max)));
  const pad = Math.max(1, (hi - lo) * 0.12); lo -= pad; hi += pad;
  const W = 900, H = 240, padL = 42, padR = 14, padT = 14, padB = 26;
  const plotW = W - padL - padR, plotH = H - padT - padB;
  const xspan = Math.max(1, cnt - 1);
  const xOf = (t) => padL + (t / xspan) * plotW;
  const yOf = (v) => padT + (1 - (v - lo) / (hi - lo)) * plotH;
  const oorCount = allPts.filter(p => p.oor).length;
  const range = hi - lo;
  // never more than 40 lines, whatever was typed into a cell
  const step = Math.max(range <= 8 ? 1 : range <= 16 ? 2 : range <= 40 ? 5 : 10, Math.ceil(range / 40));
  const ticks = [];
  for (let tv = Math.ceil(lo / step) * step; tv <= hi + 0.001; tv += step) ticks.push(Math.round(tv * 10) / 10);
  return (
    <div className={print ? 'tl-printgraph' : 'card card-pad tl-noprint'} style={print ? { marginTop: 6 } : { marginBottom: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 8 }}>
        <span style={{ fontWeight: 600, fontSize: 15, color: C.title }}>กราฟเทรนด์อุณหภูมิ</span>
        <span style={{ fontSize: 12.5, color: C.sub }}>{monthLabel} · {rangeText}</span>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 14, fontSize: 12.5 }}>
          <span style={{ color: C.sub }}>ต่ำสุด <b style={{ color: C.ink }}>{Math.min.apply(null, vals)}</b>°C</span>
          <span style={{ color: C.sub }}>สูงสุด <b style={{ color: C.ink }}>{Math.max.apply(null, vals)}</b>°C</span>
          <span style={{ color: statusInk(oorCount ? C.oor : C.ok), fontWeight: 600 }}>หลุดช่วง {oorCount} จุด</span>
        </span>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
        {chambers.map((c, ci) => <rect key={'b' + ci} x={padL} y={yOf(c.max)} width={plotW} height={Math.max(0, yOf(c.min) - yOf(c.max))} fill={C.band} opacity={C.bandOp} />)}
        {ticks.map((tv, ti) => (<g key={'g' + ti}><line x1={padL} x2={W - padR} y1={yOf(tv)} y2={yOf(tv)} stroke={C.grid} strokeWidth="0.6" opacity="0.5" /><text x={padL - 6} y={yOf(tv) + 3} textAnchor="end" fontSize="9.5" fill={C.gridText}>{tv}°</text></g>))}
        {chambers.slice(0, 1).map((c, ci) => (<g key={'e' + ci}><line x1={padL} x2={W - padR} y1={yOf(c.max)} y2={yOf(c.max)} stroke={C.band} strokeDasharray="4 4" opacity="0.6" /><line x1={padL} x2={W - padR} y1={yOf(c.min)} y2={yOf(c.min)} stroke={C.band} strokeDasharray="4 4" opacity="0.6" /></g>))}
        {days.filter(d => d === 1 || d % 5 === 0).map(d => <text key={'x' + d} x={xOf(d - 1)} y={H - 8} textAnchor="middle" fontSize="9.5" fill={C.gridText}>{d}</text>)}
        {series.map((s, si) => (<g key={'s' + si}><polyline fill="none" stroke={s.color} strokeWidth="1.7" strokeDasharray={s.dash ? '5 3' : 'none'} points={s.pts.map(p => `${xOf(p.t)},${yOf(p.v)}`).join(' ')} />{s.pts.map((p, pi) => <circle key={pi} cx={xOf(p.t)} cy={yOf(p.v)} r={p.oor ? 3.4 : 2.2} fill={p.oor ? C.oor : s.color} />)}</g>))}
      </svg>
      <div style={{ display: 'flex', gap: 16, marginTop: 6, fontSize: 12, flexWrap: 'wrap' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: C.ink }}><span style={{ width: 18, borderTop: '2.5px solid ' + C.am }} />เช้า (เส้นทึบ)</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: C.ink }}><span style={{ width: 18, borderTop: '2.5px dashed ' + C.pm }} />บ่าย (เส้นประ)</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: C.ink }}><span style={{ width: 9, height: 9, borderRadius: '50%', background: C.oor }} />หลุดช่วง</span>
      </div>
    </div>
  );
}

// asks why before earlier days open up: the reason goes into the change history with every cell
function TempFixModal({ title, onClose, onStart }) {
  const [why, setWhy] = useState('');
  const ok = why.trim().length >= 3;
  const footer = (
    <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
      <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
      <button className="btn btn-primary" disabled={!ok} onClick={() => onStart(why.trim())}><I.edit size={15} /> เริ่มแก้ไข</button>
    </div>
  );
  return (
    <CJModal title={title || 'แก้ไขบันทึกย้อนหลัง'} sub="ค่าเดิม ค่าใหม่ ผู้แก้ และเหตุผลจะอยู่ในประวัติการแก้ไข" icon={I.edit} onClose={onClose} footer={footer}>
      <CJField label="เหตุผลที่ต้องแก้ไข"><input value={why} onChange={e => setWhy(e.target.value)} maxLength={300} placeholder="เช่น พิมพ์ค่าผิด / ลืมบันทึกในวันนั้น" style={cjInput} autoFocus /></CJField>
    </CJModal>
  );
}

function TempLog({ instruments, currentUser }) {
  const isAuditor = window.__CURRENT_ROLE === 'auditor';
  const isAdminRole = window.__CURRENT_ROLE === 'admin';
  const devices = useMemo(() => instruments.map(i => ({ i, p: tempProfile(i) })).filter(x => x.p), [instruments]);
  const [dept, setDept] = useState(devices[0] ? devices[0].i.dept : '');
  const [code, setCode] = useState(devices[0] ? devices[0].i.code : '');
  // only departments that own a temperature-controlled device, + that dept's devices
  const deptList = useMemo(() => Object.keys(DEPT_META).filter(d => devices.some(x => x.i.dept === d)), [devices]);
  const deptDevices = useMemo(() => devices.filter(x => x.i.dept === dept), [devices, dept]);
  const pickDept = (d) => { setDept(d); const first = devices.find(x => x.i.dept === d); if (first) setCode(first.i.code); };
  const pickCode = (c) => { setCode(c); const d = devices.find(x => x.i.code === c); if (d) setDept(d.i.dept); };
  const today = TODAY;
  const [month, setMonth] = useState(today.getMonth());
  const [year, setYear] = useState(today.getFullYear() + 543);
  // months live in window.TempLogs (shared by every device) — see useSyncedStore
  const store = useSyncedStore(window.TempLogs);

  const dev = devices.find(d => d.i.code === code);
  const inst = dev ? dev.i : null;
  const meta = inst ? window.instrumentMeta(inst) : {};
  const ym = `${code}|${year}-${month}`;
  // a page left open overnight moves on to the new day by itself
  const [dayNow, setDayNow] = useState(() => tlDayStart(new Date()));
  useEffect(() => {
    const t = setInterval(() => setDayNow(tlDayStart(new Date())), 60000);
    return () => clearInterval(t);
  }, []);
  const [fixReason, setFixReason] = useState('');   // set = earlier days are open; each change carries it
  const [fixOpen, setFixOpen] = useState(false);
  const [releaseOpen, setReleaseOpen] = useState(false);
  useEffect(() => { setFixReason(''); }, [ym]);
  const rec = store[ym] || { grid: {}, corr: [], ranges: null, target: null };
  // range and target are an admin's, set once: a month takes them from the latest earlier one
  // (a month already on the sheet keeps what it was recorded under)
  const inherited = window.TempLogs.onSheet(ym) ? { ranges: null, target: null } : window.TempLogs.inherited(code, year, month);
  const targetNow = rec.target ?? inherited.target ?? (dev ? dev.p.target : null);
  const rangesNow = rec.ranges || inherited.ranges;
  // cells on this device that aren't on the sheet and won't get there by themselves
  const stuck = window.TempLogs.stuck(ym);
  const stuckCount = window.TempLogs.stuckCount(ym);

  // effective chambers (apply freezer target / saved ranges)
  const chambers = useMemo(() => {
    if (!dev) return [];
    let ch = dev.p.chambers.map(c => ({ ...c }));
    if (dev.p.freezer) ch = [{ key: 'f', name: 'ช่องแช่แข็ง', min: targetNow - 5, max: targetNow + 5 }];
    if (rangesNow) ch = ch.map(c => ({ ...c, ...(rangesNow[c.key] || {}) }));
    return ch;
  }, [dev, targetNow, rangesNow]);

  const daysInMonth = new Date(year - 543, month + 1, 0).getDate();
  const backOf = (d) => Math.round((dayNow - new Date(year - 543, month, d).getTime()) / 86400000);
  const reach = (back) => !isAuditor && (back === 0 || (back > 0 && !!fixReason && (isAdminRole || back <= TL_EDIT_DAYS)));
  const canEnter = (d) => reach(backOf(d));
  // corrective actions belong to the month: dated by its last day
  const monthOpen = backOf(1) >= 0 && reach(Math.max(0, backOf(daysInMonth)));
  const limitsOpen = monthOpen && isAdminRole;
  const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);

  // every change goes through window.TempLogs: it saves locally at once and
  // sends to the sheet a moment after typing stops
  const update = (mut) => {
    if (window.__CURRENT_ROLE === 'auditor' || !dev) return;
    window.TempLogs.update(ym, mut, { grid: {}, corr: [], ranges: null, target: null }, fixReason);
  };
  const setCell = (day, sess, key, val) => update(r => { r.grid[`${day}.${sess}.${key}`] = val; });
  // entering a temperature auto-fills that session's time (09:00/15:00) if still
  // blank — fewer keystrokes per reading. The recorder is always the logged-in
  // user, here for the screen; the server sets the one that counts
  const enterReading = (day, sess, ckey, val) => update(r => {
    r.grid[`${day}.${sess}.${ckey}`] = val;
    if (val !== '' && val != null) {
      if (!r.grid[`${day}.${sess}.time`]) r.grid[`${day}.${sess}.time`] = TL_DEFAULT_TIME[sess] || '';
      if (currentUser) r.grid[`${day}.${sess}.by`] = tlInitials(currentUser);
    }
  });
  const cell = (day, sess, key) => (store[ym] && store[ym].grid[`${day}.${sess}.${key}`]) || '';
  // what is only on this device stays out of the chart and off the printed form
  const sheetCell = (day, sess, key) => (stuck[`g:${day}.${sess}.${key}`] ? '' : cell(day, sess, key));
  const setTarget = (t) => update(r => { r.target = t; });
  const setRange = (ck, field, val) => update(r => { r.ranges = { ...(r.ranges || rangesNow || {}) }; r.ranges[ck] = { ...(r.ranges[ck] || {}), [field]: val === '' ? undefined : +val }; });
  // a corrective row has its id from before its first letter: the same row on screen once typed
  // in, and its own row on the sheet if someone else adds one at the same moment
  const corrIds = useRef({}).current;
  const blankCorr = (i, corr) => {
    if (!corrIds[i] || corr.some(c => c && c.id === corrIds[i])) corrIds[i] = tlCorrId();
    return { id: corrIds[i], no: i + 1, date: '', problem: '', fix: '', by: '' };
  };
  const addCorr = () => update(r => { r.corr = [...r.corr, blankCorr(r.corr.length, r.corr)]; });
  const setCorr = (idx, field, val) => update(r => { const arr = [...r.corr]; while (arr.length <= idx) arr.push(blankCorr(arr.length, arr)); arr[idx] = { ...arr[idx], [field]: val, by: currentUser || arr[idx].by }; r.corr = arr; });
  // installation location follows the device's own department (no mismatch)
  const locValue = inst ? deptLoc(inst.dept) : '';

  const oor = (ck, raw) => {
    if (raw === '' || raw == null) return false;
    const n = parseFloat(raw); if (isNaN(n)) return false;
    const c = chambers.find(x => x.key === ck); if (!c) return false;
    return n < c.min || n > c.max;
  };

  const doPrint = () => {
    document.body.classList.add('printing-temp');
    const cleanup = () => { document.body.classList.remove('printing-temp'); window.removeEventListener('afterprint', cleanup); };
    window.addEventListener('afterprint', cleanup);
    setTimeout(() => window.print(), 60);
  };

  if (devices.length === 0) return <EmptyState icon={I.beaker} title="ไม่พบเครื่องควบคุมอุณหภูมิในทะเบียน" sub="เพิ่มตู้เย็น/ตู้แช่/ตู้อบเพาะเชื้อก่อน" />;

  const cnt = days.length;
  const sessions = [['am', 'เช้า'], ['pm', 'บ่าย']];
  const rangeText = chambers.map(c => `${c.name} ${c.min}°C ถึง ${c.max}°C`).join(' · ');

  return (
    <div className="enter">
      {window.__CURRENT_ROLE === 'auditor' && (
        <div className="rp-hint tl-noprint" style={{ background: 'var(--warn-soft)', borderColor: 'var(--warn)' }}>
          <I.eye size={15} />
          <span>โหมดอ่านอย่างเดียว — บัญชีผู้ตรวจประเมินดูข้อมูลได้เท่านั้น บันทึกค่าไม่ได้</span>
        </div>
      )}
      {/* controls (hidden in print) */}
      <div className="tl-bar tl-noprint">
        <div className="fld">
          <label>เลือกแผนก</label>
          <select className="select" aria-label="เลือกแผนก" style={{ minWidth: 230 }} value={dept} onChange={e => pickDept(e.target.value)}>
            {deptList.map(d => <option key={d} value={d}>{deptLoc(d)}</option>)}
          </select>
        </div>
        <div className="fld">
          <label>เลือกเครื่อง (ตู้ควบคุมอุณหภูมิ)</label>
          <select className="select" aria-label="เลือกเครื่อง (ตู้ควบคุมอุณหภูมิ)" style={{ minWidth: 300 }} value={code} onChange={e => setCode(e.target.value)}>
            {deptDevices.map(d => <option key={d.i.code} value={d.i.code}>{d.i.code} · {d.i.type}</option>)}
          </select>
        </div>
        <div className="fld">
          <label>เดือน</label>
          <select className="select" aria-label="เดือน" value={month} onChange={e => setMonth(+e.target.value)}>{TL_MONTHS.map((m, i) => <option key={i} value={i}>{m}</option>)}</select>
        </div>
        <div className="fld">
          <label>พ.ศ.</label>
          <input className="input" aria-label="พ.ศ." style={{ width: 90 }} type="number" value={year} onChange={e => setYear(+e.target.value)} />
        </div>
        {dev && dev.p.freezer && (
          <div className="fld">
            <label>อุณหภูมิเป้าหมาย</label>
            <select className="select" aria-label="อุณหภูมิเป้าหมาย" disabled={!limitsOpen} value={targetNow} onChange={e => setTarget(+e.target.value)}>
              {FRZ_TARGETS.map(t => <option key={t} value={t}>{t}°C (±5)</option>)}
            </select>
          </div>
        )}
        <div style={{ flex: 1 }} />
        <SyncPill sync={window.TempLogs.sync} />
        {!isAuditor && !fixReason && <button className="btn" onClick={() => setFixOpen(true)}><I.edit size={16} /> แก้ไขย้อนหลัง</button>}
        <button className="btn btn-primary" onClick={doPrint}><I.download size={16} /> พิมพ์ฟอร์ม</button>
      </div>

      {!isAuditor && (fixReason ? (
        <div className="rp-hint tl-noprint" style={{ background: 'var(--warn-soft)', borderColor: 'var(--warn)' }}>
          <I.edit size={15} />
          <span style={{ flex: 1, minWidth: 0 }}>กำลังแก้ไขย้อนหลัง{isAdminRole ? '' : ` (ไม่เกิน ${TL_EDIT_DAYS} วัน)`} · เหตุผล: {fixReason}</span>
          <button className="btn btn-sm" onClick={() => setFixReason('')}><I.check size={14} /> จบการแก้ไข</button>
        </div>
      ) : (
        <div className="rp-hint tl-noprint">
          <I.eye size={15} />
          <span>กรอกได้เฉพาะวันนี้ · ชื่อผู้บันทึกมาจากบัญชีที่เข้าสู่ระบบ · วันอื่นกด "แก้ไขย้อนหลัง" และระบุเหตุผล</span>
        </div>
      ))}
      {stuckCount > 0 && (
        <div className="rp-hint tl-noprint" style={{ background: 'var(--warn-soft)', borderColor: 'var(--warn)' }}>
          <I.bell size={15} />
          <span style={{ flex: 1, minWidth: 0 }}>มี {stuckCount} ค่าในเครื่องนี้ที่ยังไม่ขึ้นระบบ (ช่องที่มีกรอบเหลือง) เพราะเกินกำหนดย้อนหลัง หรือกรอกโดยบัญชีอื่น ค่าเหล่านี้ไม่พิมพ์ลงฟอร์ม</span>
          {isAdminRole && <button className="btn btn-sm" onClick={() => setReleaseOpen(true)}><I.check size={14} /> บันทึกในชื่อฉัน</button>}
          {window.TempLogs.canDiscard(ym) && <button className="btn btn-sm btn-ghost" onClick={() => { if (window.confirm('ทิ้งค่าที่ค้างในเครื่องนี้? ค่าบนระบบไม่เปลี่ยน')) window.TempLogs.discard(ym); }}>ทิ้งค่าที่ค้าง</button>}
        </div>
      )}
      {fixOpen && <TempFixModal onClose={() => setFixOpen(false)} onStart={(why) => { setFixReason(why); setFixOpen(false); }} />}
      {releaseOpen && <TempFixModal title="บันทึกค่าที่ค้างในเครื่องนี้" onClose={() => setReleaseOpen(false)} onStart={(why) => { window.TempLogs.release(ym, why); setReleaseOpen(false); }} />}

      {/* on-screen trend graph (themed, not part of the printed FM form) */}
      <TempChart chambers={chambers} days={days} cell={sheetCell} sessions={sessions} cnt={cnt} monthLabel={`${TL_MONTHS[month]} ${year}`} rangeText={rangeText} print={false} />

      {/* the sheet (editor doubles as printable form) */}
      <div className="tl-sheetwrap">
        <div className="temp-sheet">
          <LabDocHeader docNo="FR-MO-0007" line2="แก้ไขครั้งที่ 0 : 17 มิ.ย. 2569" />

          <div className="ts-meta">
            <div>
              <b style={{ fontSize: 16 }}>แบบบันทึกอุณหภูมิ{dev ? dev.p.word : ''}</b> &nbsp;
              ประจำเดือน <span className="uline">{TL_MONTHS[month]}</span> พ.ศ. <span className="uline">{year}</span> &nbsp;
              หมายเลขครุภัณฑ์ <span className="uline">{inst && inst.asset !== '-' ? inst.asset : '-'}</span> &nbsp;
              ยี่ห้อ <span className="uline">{inst ? inst.brand : '-'}</span> &nbsp;
              รุ่น <span className="uline">{inst && inst.model !== '-' ? inst.model : '-'}</span>
            </div>
            <div>
              รหัสเครื่อง <span className="uline">{inst ? inst.code : '-'}</span> &nbsp;
              สถานที่ตั้ง <span className="uline">{locValue || '-'}</span> &nbsp;
              ช่วงอุณหภูมิที่ยอมรับได้ :
              {chambers.map((c, i) => (
                <span key={c.key}> &nbsp;{c.name}
                  <input type="number" aria-label={`${c.name} ต่ำสุด (°C)`} value={c.min} disabled={!limitsOpen} onChange={e => setRange(c.key, 'min', e.target.value)} style={{ width: 50 }} />°C ถึง
                  <input type="number" aria-label={`${c.name} สูงสุด (°C)`} value={c.max} disabled={!limitsOpen} onChange={e => setRange(c.key, 'max', e.target.value)} style={{ width: 50 }} />°C
                </span>
              ))}
            </div>
          </div>

          {/* grid */}
          <table className="tl-grid">
            <thead>
              <tr>
                <th colSpan={2} className="tl-rowlab" style={{ width: 130 }}>วันที่</th>
                {days.map(d => <th key={d}>{d}</th>)}
              </tr>
            </thead>
            <tbody>
              {sessions.map(([sk, sname]) => {
                const rows = [...chambers.map(c => ({ type: 'chamber', c })), { type: 'time' }, { type: 'by' }];
                return rows.map((row, ri) => (
                  <tr key={sk + ri}>
                    {ri === 0 && <td className="tl-sesslab" rowSpan={rows.length}>{sname}</td>}
                    <td className="tl-rowlab">{row.type === 'chamber' ? row.c.name : row.type === 'time' ? 'เวลา' : 'ผู้บันทึก'}</td>
                    {days.map(d => {
                      const key = row.type === 'chamber' ? row.c.key : row.type;
                      const val = cell(d, sk, key);
                      const bad = row.type === 'chamber' && oor(row.c.key, val);
                      return (
                        <td key={d} className={`tl-cell${bad ? ' oor' : ''}${stuck[`g:${d}.${sk}.${key}`] ? ' held' : ''}`}>
                          <input aria-label={`${sname} ${row.type === 'chamber' ? row.c.name : row.type === 'time' ? 'เวลา' : 'ผู้บันทึก'} วันที่ ${d}`} value={val} disabled={row.type === 'by' || !canEnter(d)} onChange={e => (row.type === 'chamber' ? enterReading(d, sk, key, e.target.value) : setCell(d, sk, key, e.target.value))} />
                        </td>
                      );
                    })}
                  </tr>
                ));
              })}
            </tbody>
          </table>

          <div className="ts-notes">
            <b>หมายเหตุ :</b> 1. กรณีอุณหภูมิออกนอกช่วงค่าที่กำหนด ให้ติดตามต่อไปอีก 1 ชั่วโมง หากยังไม่ได้อีกให้ติดต่อช่างงานซ่อมบำรุง &nbsp; 2. กรณีไม่ได้ใช้งาน กรุณากาเครื่องหมาย (−) เมื่อได้ปฏิบัติในข้อนั้น ๆ
          </div>

          {/* corrective action */}
          <div className="ts-corr">
            <h4>การปฏิบัติแก้ไข (Corrective action)</h4>
            <table className="tl-corr">
              <thead><tr><th style={{ width: 50 }}>ครั้งที่</th><th style={{ width: 110 }}>วันที่</th><th>ปัญหา</th><th>การแก้ไข</th><th style={{ width: 130 }}>ผู้บันทึก</th></tr></thead>
              <tbody>
                {Array.from({ length: Math.max(2, rec.corr.length) }, (_, i) => rec.corr[i] || blankCorr(i, rec.corr)).map((c, i) => (
                  <tr key={c.id || i}>
                    <td style={{ textAlign: 'center' }}>{i + 1}</td>
                    <td className={stuck[`c:${c.id || i}.date`] ? 'held' : ''}><input aria-label={`ครั้งที่ ${i + 1} วันที่`} value={c.date} disabled={!monthOpen} onChange={e => setCorr(i, 'date', e.target.value)} /><div className="tl-corr-print">{stuck[`c:${c.id || i}.date`] ? '' : c.date}</div></td>
                    <td className={stuck[`c:${c.id || i}.problem`] ? 'held' : ''}><input aria-label={`ครั้งที่ ${i + 1} ปัญหา`} value={c.problem} disabled={!monthOpen} onChange={e => setCorr(i, 'problem', e.target.value)} /><div className="tl-corr-print">{stuck[`c:${c.id || i}.problem`] ? '' : c.problem}</div></td>
                    <td className={stuck[`c:${c.id || i}.fix`] ? 'held' : ''}><input aria-label={`ครั้งที่ ${i + 1} การแก้ไข`} value={c.fix} disabled={!monthOpen} onChange={e => setCorr(i, 'fix', e.target.value)} /><div className="tl-corr-print">{stuck[`c:${c.id || i}.fix`] ? '' : c.fix}</div></td>
                    <td className={stuck[`c:${c.id || i}.by`] ? 'held' : ''}><input aria-label={`ครั้งที่ ${i + 1} ผู้บันทึก`} value={c.by} disabled readOnly /><div className="tl-corr-print">{stuck[`c:${c.id || i}.by`] ? '' : c.by}</div></td>
                  </tr>
                ))}
              </tbody>
            </table>
            {monthOpen && <button className="btn btn-sm tl-noprint" style={{ marginTop: 8 }} onClick={addCorr}><I.plus size={14} /> เพิ่มแถว</button>}
          </div>

          {/* printed trend graph (hidden on screen — the themed one above is shown instead) */}
          <div className="tl-printonly">
            <TempChart chambers={chambers} days={days} cell={sheetCell} sessions={sessions} cnt={cnt} monthLabel={`${TL_MONTHS[month]} ${year}`} rangeText={rangeText} print={true} />
          </div>
          <div className="ts-review">ทบทวนโดย : ............................................. วันที่ ........./........./.........</div>
          <div className="lbl-foot">(เอกสารสำเนาอิเล็กทรอนิกส์ถูกควบคุมให้เป็นปัจจุบันเมื่ออยู่บนเว็บไซต์เท่านั้น)</div>
        </div>
      </div>
    </div>
  );
}
window.TempLog = TempLog;
