/* ============================================================
   detail.jsx — rich instrument card: identity, status, calibration
   certificate, PM, documents, code decode, history, scan preview.
   ============================================================ */
function InfoRow({ label, children, mono }) {
  return (
    <div className="info-row" style={{ display: 'grid', gridTemplateColumns: '128px 1fr', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--line-soft)' }}>
      <div style={{ fontSize: 12.5, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</div>
      <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--ink)', fontFamily: mono ? 'var(--mono)' : 'inherit', minWidth: 0, overflowWrap: 'anywhere', wordBreak: 'break-word' }}>{children}</div>
    </div>
  );
}
function SectionCard({ icon, title, sub, right, children }) {
  const Ico = icon;
  return (
    <div className="card card-pad">
      <div className="sec-head" style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 16 }}>
        {Ico && <span style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--accent-softer)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center', flex: 'none' }}><Ico size={17} /></span>}
        <div style={{ flex: 1, minWidth: 0 }}>
          <h2 className="sec-title" style={{ fontWeight: 600, fontSize: 15 }}>{title}</h2>
          {sub && <div className="page-sub">{sub}</div>}
        </div>
        {right && <div className="sec-head-right">{right}</div>}
      </div>
      {children}
    </div>
  );
}
function OpBadge({ op }) {
  const map = { up: ['var(--ok)', 'var(--ok-soft)'], repair: ['var(--warn)', 'var(--warn-soft)'], down: ['var(--danger)', 'var(--danger-soft)'], unknown: ['var(--none)', 'var(--none-soft)'] };
  const [c, soft] = map[op.key] || map.unknown;
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, padding: '3px 10px', borderRadius: 99, background: soft, color: statusInk(c) }}><span style={{ width: 7, height: 7, borderRadius: 99, background: c }} />{op.label}</span>;
}
function DocRow({ icon, name, meta, onOpen }) {
  const Ico = icon;
  return (
    <button onClick={onOpen} className="doc-row" style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 10, padding: '11px 13px', cursor: 'pointer', fontFamily: 'inherit', transition: 'border-color .14s, background .14s' }}>
      <span style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--surface)', display: 'grid', placeItems: 'center', color: 'var(--accent)', flex: 'none' }}><Ico size={17} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{meta}</div>
      </div>
      <I.download size={16} style={{ color: 'var(--ink-3)', flex: 'none' }} />
    </button>
  );
}

function ScanPreview({ inst, meta, s, onClose }) {
  const m = DEPT_META[inst.dept] || {};
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div style={{ position: 'fixed', inset: 0, display: 'grid', placeItems: 'center', zIndex: 60, pointerEvents: 'none' }}>
        <div className="enter" style={{ pointerEvents: 'auto', width: 320, background: '#0f0d0b', borderRadius: 38, padding: 11, boxShadow: 'var(--shadow-lg)' }}>
          <div style={{ background: 'var(--bg)', borderRadius: 28, overflow: 'hidden', height: 620, display: 'flex', flexDirection: 'column' }}>
            <div style={{ background: deptColor(inst.dept, 0.55, 0.12), color: '#fff', padding: '34px 20px 18px', position: 'relative' }}>
              <div style={{ position: 'absolute', top: 12, left: '50%', transform: 'translateX(-50%)', width: 90, height: 5, borderRadius: 99, background: '#ffffff55' }} />
              <div style={{ fontSize: 11, opacity: .9, fontWeight: 600, letterSpacing: '.05em' }}>สแกนสำเร็จ · บัตรเครื่องมือ</div>
              <div style={{ fontFamily: 'var(--mono)', fontWeight: 600, fontSize: 18, marginTop: 6 }}>{inst.code}</div>
              <div style={{ fontSize: 12.5, opacity: .95, marginTop: 2 }}>{inst.type}</div>
            </div>
            <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12, overflowY: 'auto', flex: 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><OpBadge op={meta.op} /><Pill status={s} showDays /></div>
              {[['แผนก', m.short || inst.dept], ['ที่ตั้ง', meta.location || '—'], ['ผู้รับผิดชอบ', meta.owner || '—'], ['ครบกำหนดสอบเทียบ', fmtDateFull(inst.exp)], ['PM ครั้งถัดไป', fmtDateFull(inst.pmNext)]].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: 12.5, paddingBottom: 8, borderBottom: '1px solid var(--line-soft)' }}>
                  <span style={{ color: 'var(--ink-3)' }}>{l}</span><span style={{ fontWeight: 600, textAlign: 'right' }}>{v}</span>
                </div>
              ))}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 2 }}>
                <button className="btn btn-sm" style={{ background: 'var(--danger-soft)', color: 'var(--danger-ink)', borderColor: 'transparent' }}><I.warning size={15} /> แจ้งซ่อม</button>
                <button className="btn btn-sm"><I.shield size={15} /> บันทึก PM</button>
                <button className="btn btn-sm" style={{ gridColumn: '1 / -1' }}><I.download size={15} /> ดูใบรับรองสอบเทียบ</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

/* instrument photo banner — real per-device photo, else a type image,
   else an icon placeholder. Independent of the QR code below it. */
function InstrumentPhoto({ inst }) {
  // try the per-device photo first; if it fails to load, fall back to the
  // type image; if that fails too, show the placeholder.
  const custom = inst.photo && String(inst.photo).trim() ? normalizeImageUrl(String(inst.photo).trim()) : null;
  const repo = (inst.code && window.PHOTO_MANIFEST && window.PHOTO_MANIFEST[inst.code]) ? ('photos/' + window.PHOTO_MANIFEST[inst.code]) : null;
  const typeImg = instrumentTypeImg(inst);
  const chain = [custom, repo, typeImg].filter(Boolean);
  const [idx, setIdx] = useState(0);
  useEffect(() => { setIdx(0); }, [inst.code, inst.photo]);
  const src = chain[idx];
  if (!src) {
    return (
      <div style={{ height: 150, display: 'grid', placeItems: 'center', background: 'var(--surface-2)', borderBottom: '1px solid var(--line)' }}>
        <div style={{ textAlign: 'center', color: 'var(--ink-4)' }}>
          <I.beaker size={36} />
          <div style={{ fontSize: 11.5, marginTop: 6 }}>ยังไม่มีรูปภาพ</div>
        </div>
      </div>
    );
  }
  return (
    <div style={{ height: 190, background: '#fff', borderBottom: '1px solid var(--line)', padding: 8 }}>
      <img key={src} src={src} alt={inst.type || inst.code} onError={() => setIdx(i => i + 1)}
        style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
    </div>
  );
}

function Detail({ instruments, code, go, onEdit, admin, onDelete, readOnly, otherDept, noNav, onUpdateInstrument, currentUser }) {
  const inst = useMemo(() => instruments.find(i => i.code === code), [instruments, code]);
  const [scan, setScan] = useState(false);
  const [labelOpen, setLabelOpen] = useState(false);
  const [pmOpen, setPmOpen] = useState(false);
  const [pmHistOpen, setPmHistOpen] = useState(false);
  const [calHistOpen, setCalHistOpen] = useState(false);
  // subscribe to PMLogs so the history-count chip on the PM card updates live
  const [, bumpPm] = useState(0);
  useEffect(() => window.PMLogs && window.PMLogs.subscribe(() => bumpPm(x => x + 1)), []);
  useEffect(() => window.CalJobs && window.CalJobs.subscribe(() => bumpPm(x => x + 1)), []);
  // latest acceptance reason recorded when this instrument was returned from calibration
  const calReason = (() => {
    if (!window.CalJobs || !inst) return '';
    const js = window.CalJobs.forCode(inst.code).filter(j => j.status === 'returned' && j.note);
    js.sort((a, b) => String(b.returnedDate || '').localeCompare(String(a.returnedDate || '')));
    return js.length ? js[0].note : '';
  })();
  const calHistCount = (window.CalJobs && inst) ? window.CalJobs.forCode(inst.code).filter(j => j.status === 'returned').length : 0;
  // computed before the early return so hook order stays stable (Rules of Hooks);
  // meta/s are derived locally so the memo doesn't depend on later consts
  const history = useMemo(() => {
    if (!inst) return [];
    const meta = instrumentMeta(inst);
    const s = statusOf(inst);
    const ev = [];
    if (inst.cal) {
      ev.push({ d: inst.cal, kind: 'cal', title: 'สอบเทียบ (Calibration)', note: [inst.provider, inst.calResult].filter(Boolean).join(' · ') || 'บันทึกการสอบเทียบ' });
      const cal = parseD(inst.cal), exp = parseD(inst.exp);
      if (cal && exp) {
        const span = Math.round((exp - cal) / 86400000);
        const prev = new Date(cal.getTime() - span * 86400000);
        const pd = prev.getFullYear() + '-' + String(prev.getMonth() + 1).padStart(2, '0') + '-' + String(prev.getDate()).padStart(2, '0');
        ev.unshift({ d: pd, kind: 'cal', title: 'สอบเทียบรอบก่อนหน้า', note: 'ผ่านเกณฑ์' });
      }
    }
    if (meta.pmLast) ev.push({ d: meta.pmLast, kind: 'pm', title: 'บำรุงรักษาเชิงป้องกัน (PM)', note: 'ตรวจสภาพ/ทำความสะอาดตามรอบ' });
    if (meta.intake) ev.push({ d: meta.intake, kind: 'in', title: 'รับเข้าใช้งาน', note: 'ลงทะเบียนเข้าระบบ' });
    if (inst.exp) ev.push({ d: inst.exp, kind: 'due', title: 'ครบกำหนดสอบเทียบครั้งถัดไป', note: s.key === 'danger' ? 'เลยกำหนดแล้ว — ต้องดำเนินการ' : 'นัดหมายล่วงหน้า', future: true });
    if (meta.pmNext) ev.push({ d: meta.pmNext, kind: 'pmdue', title: 'กำหนด PM ครั้งถัดไป', note: meta.pmCycle, future: true });
    return ev.sort((a, b) => (a.d < b.d ? 1 : -1));
  }, [inst]);
  // two-way decommission link (ISO 15189 §6.4 traceability). replacedBy is stored
  // ONLY on the retired instrument's own row — the "replaces" direction is derived
  // by scanning `instruments` for whoever points back at this code, never stored
  // as a second field (two fields would drift out of sync on a one-sided edit).
  // In the guest QR-card view `instruments` holds just this one row, so the reverse
  // lookup naturally comes back empty instead of erroring — that's expected there.
  const replacedByInst = useMemo(() => {
    if (!inst) return null;
    const meta = instrumentMeta(inst);
    if (!meta.replacedBy) return null;
    return (instruments || []).find(i => i.code === meta.replacedBy) || null;
  }, [inst, instruments]);
  const replacesInst = useMemo(() => {
    if (!inst) return null;
    return (instruments || []).find(i => i.replacedBy === inst.code) || null;
  }, [inst, instruments]);
  if (!inst) return <EmptyState icon={I.search} title="ไม่พบเครื่องมือนี้" sub={code} />;
  const s = statusOf(inst);
  const m = DEPT_META[inst.dept] || {};
  const meta = instrumentMeta(inst);
  const parts = inst.code.split('-');
  const typeInfo = (window.LAB_DATA.types || []).find(t => t.abbr === parts[2]);

  return (
    <div className="enter" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {scan && <ScanPreview inst={inst} meta={meta} s={s} onClose={() => setScan(false)} />}
      {labelOpen && <LabelModal items={[inst]} onClose={() => setLabelOpen(false)} />}
      {pmOpen && window.PMLogModal && (
        <PMLogModal inst={inst} currentUser={currentUser} admin={admin} onClose={() => setPmOpen(false)}
          onSaved={(i, r) => { onUpdateInstrument(i.code, { pmLast: r.doneDate, pmNext: r.nextDate, provider: r.vendor || i.provider }); setPmOpen(false); }} />
      )}
      {pmHistOpen && window.PMHistoryModal && (
        <PMHistoryModal inst={inst} onClose={() => setPmHistOpen(false)} />
      )}
      {calHistOpen && window.CalHistoryModal && (
        <CalHistoryModal inst={inst} onClose={() => setCalHistOpen(false)} />
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        {!noNav && <button className="btn btn-ghost btn-sm" onClick={() => go('inventory')}><I.arrowL size={16} /> กลับไปทะเบียนเครื่องมือ</button>}
        {/* actions stay a right-aligned group — on a phone they wrap under the back link together */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', justifyContent: 'flex-end', marginLeft: 'auto' }}>
          <button className="btn btn-sm" onClick={() => setScan(true)}><I.qr size={16} /> มุมมองสแกน QR</button>
          {!readOnly && admin && <button className="btn btn-sm" style={{ color: 'var(--danger-ink)', borderColor: 'var(--danger)' }} onClick={() => onDelete && onDelete(inst.code)}><I.trash size={16} /> ลบ</button>}
          {!readOnly && admin && <button className="btn btn-primary btn-sm" onClick={() => onEdit(inst.code)}><I.edit size={16} /> แก้ไข</button>}
        </div>
      </div>
      {otherDept && (
        <div className="rp-hint" style={{ marginTop: 12 }}>
          <I.eye size={15} />
          <span>เครื่องของแผนกอื่น: ดูข้อมูลทั่วไปและคู่มือได้ แต่ไม่แสดงบันทึกของแผนกนั้น และบันทึกเพิ่มไม่ได้</span>
        </div>
      )}

      <div className="detail-grid" style={{ display: 'grid', gridTemplateColumns: '340px 1fr', gap: 22, alignItems: 'start' }}>
        {/* ID card */}
        <div className="card" style={{ overflow: 'hidden', position: 'sticky', top: 88 }}>
          <div style={{ background: deptColor(inst.dept, 0.55, 0.12), padding: '18px 20px', color: '#fff' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11.5, opacity: .92, fontWeight: 600, letterSpacing: '.05em' }}>
              <span>บัตรประจำเครื่องมือ</span><span>{m.abbr}</span>
            </div>
            <div style={{ fontFamily: 'var(--mono)', fontWeight: 600, fontSize: 21, marginTop: 8 }}>{inst.code}</div>
            <div style={{ fontSize: 13, opacity: .95, marginTop: 2 }}>{m.short || inst.dept}</div>
          </div>
          <InstrumentPhoto inst={inst} />
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
            <button onClick={() => setScan(true)} title="ดูมุมมองสแกน" style={{ padding: 10, background: '#fff', borderRadius: 12, boxShadow: 'var(--shadow-sm)', border: 'none', cursor: 'pointer' }}><QRMatrix text={instrumentURL(inst.code)} size={148} /></button>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>สแกนเพื่อเปิดบัตรบนมือถือ</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 10, justifyContent: 'center' }}>
                <span className="kbd-code">{inst.code}</span><CopyBtn text={inst.code} />
              </div>
            </div>
            <div style={{ width: '100%', display: 'flex', gap: 8 }}>
              {!readOnly && <button className="btn btn-sm" style={{ flex: 1 }} onClick={() => setLabelOpen(true)}><I.qr size={15} /> พิมพ์ป้าย</button>}
              {!readOnly && admin && <button className="btn btn-sm" style={{ flex: 1 }} onClick={() => onEdit(inst.code)}><I.edit size={15} /> แก้ไข</button>}
            </div>
            <div style={{ width: '100%', borderTop: '1px solid var(--line-soft)', paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 9 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, fontSize: 12.5 }}><span style={{ color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>สถานะใช้งาน</span><OpBadge op={meta.op} /></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, fontSize: 12.5 }}><span style={{ color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>สอบเทียบ</span><Pill status={s} showDays /></div>
            </div>
          </div>
        </div>

        {/* details */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div className="card card-pad">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14 }}>
              <div>
                <h2 style={{ margin: 0, fontSize: 23, fontWeight: 600, letterSpacing: '-.02em', textWrap: 'pretty' }}>{inst.type}</h2>
                <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 4 }}>{inst.brand}{inst.model && inst.model !== '-' ? ` · รุ่น ${inst.model}` : ''}</div>
              </div>
              <Pill status={s} showDays />
            </div>
            {(() => {
              // Show the big due-date banner ONLY when action is needed
              // (warn = ใกล้ครบ, danger = เกินกำหนด). When status is normal,
              // the Pill at the top-right already carries the same info —
              // keeping the page clean for the vast majority of healthy
              // instruments. Pick the cycle wording from statusOf.kind.
              if (s.key !== 'warn' && s.key !== 'danger') return null;
              const trackPm = s.kind === 'pm';
              const anchor = trackPm ? inst.pmNext : inst.exp;
              if (!anchor || s.days == null) return null;
              const noun = trackPm ? 'PM' : 'สอบเทียบ';
              return (
              <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 16, background: s.key === 'warn' ? 'var(--warn-soft)' : 'var(--danger-soft)', borderRadius: 12, padding: '14px 18px' }}>
                <I.clock size={22} style={{ color: s.key === 'warn' ? 'var(--warn-ink)' : 'var(--danger-ink)' }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{s.days < 0 ? `เลยกำหนด${noun}มาแล้ว ${Math.abs(s.days)} วัน` : `เหลือเวลาอีก ${s.days} วัน ก่อนครบกำหนด${noun === 'PM' ? ' PM' : ''}`}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 1 }}>{trackPm ? `กำหนด PM ครั้งถัดไป` : `กำหนดสอบเทียบครั้งถัดไป`} {fmtDateFull(anchor)}</div>
                </div>
              </div>
              );
            })()}
            <div className="info-grid" style={{ marginTop: 6, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 28px' }}>
              <InfoRow label="ชนิดเครื่องมือ">{inst.type}</InfoRow>
              <InfoRow label="แผนก"><DeptBadge dept={inst.dept} /></InfoRow>
              <InfoRow label="ยี่ห้อ">{inst.brand || '—'}</InfoRow>
              <InfoRow label="รุ่น / Model" mono>{inst.model && inst.model !== '-' ? inst.model : '—'}</InfoRow>
              <InfoRow label="Serial No." mono>{inst.serial && inst.serial !== '-' ? inst.serial : '—'}</InfoRow>
              <InfoRow label="รหัสครุภัณฑ์" mono>{inst.asset && inst.asset !== '-' ? inst.asset : '—'}</InfoRow>
              <InfoRow label="ที่ตั้ง">{meta.location}</InfoRow>
              <InfoRow label="ผู้รับผิดชอบ">{meta.owner || <span className="muted">—</span>}</InfoRow>
              <InfoRow label="วันรับเข้าใช้งาน">{fmtDateFull(meta.intake)}</InfoRow>
              <InfoRow label="หมายเหตุ">{inst.note && inst.note !== '-' ? inst.note : <span className="muted">—</span>}</InfoRow>
            </div>
          </div>

          {/* calibration + PM side by side — only show cards that actually apply to this instrument.
             A value of '-' / 'N/A' / blank in calPerYear or pmPerYear means "this instrument
             does not require that service" → hide the corresponding card so the page only
             shows what's really maintained (ISO-honest). */}
          {(() => {
            const notReq = (v) => { const s = String(v == null ? '' : v).trim(); return !s || s === '-' || /n\/?a/i.test(s) || /ไม่ต้อง/.test(s); };
            const showCal = !notReq(inst.calPerYear);
            const showPm = !notReq(inst.pmPerYear);
            if (!showCal && !showPm) return null;
            const gridCols = (showCal && showPm) ? '1fr 1fr' : '1fr';
            return (
              <div style={{ display: 'grid', gridTemplateColumns: gridCols, gap: 20 }} className="cal-pm-grid">
                {showCal && (
                  <SectionCard icon={I.shield} title="การสอบเทียบ" sub="Calibration record"
                    right={calHistCount > 0 ? <button className="btn btn-sm" onClick={() => setCalHistOpen(true)} title="ดูประวัติการสอบเทียบทั้งหมด"><I.history size={14} /> ประวัติ ({calHistCount})</button> : null}>
                    <InfoRow label="สอบเทียบล่าสุด">{fmtDateFull(inst.cal)}</InfoRow>
                    <InfoRow label="ครบกำหนดถัดไป">{fmtDateFull(inst.exp)}</InfoRow>
                    <InfoRow label="ความถี่สอบเทียบ">{(window.calFreqOf && window.calFreqOf(inst)) || <span className="muted">—</span>}</InfoRow>
                    <InfoRow label="หน่วยงาน">{inst.provider || <span className="muted">—</span>}</InfoRow>
                    <InfoRow label="เลขใบรับรอง" mono>{inst.certNo || <span className="muted">—</span>}</InfoRow>
                    <InfoRow label="ผลการสอบเทียบ">{inst.calResult ? <span style={{ color: `var(--${window.calResultTone(inst.calResult)}-ink)`, fontWeight: 600 }}>{inst.calResult}</span> : <span className="muted">รอบันทึก</span>}</InfoRow>
                  </SectionCard>
                )}
                {showPm && (() => {
                  const histCount = window.PMLogs ? window.PMLogs.forCode(inst.code).length : 0;
                  return (
                  <SectionCard icon={I.refresh} title="บำรุงรักษา (PM)" sub="Preventive maintenance"
                    right={
                      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
                        {histCount > 0 && <button className="btn btn-sm" onClick={() => setPmHistOpen(true)} title="ดูประวัติการทำ PM ทั้งหมด"><I.history size={14} /> ประวัติ ({histCount})</button>}
                        {!readOnly && onUpdateInstrument && <button className="btn btn-sm btn-primary" onClick={() => setPmOpen(true)}><I.refresh size={14} /> บันทึก PM</button>}
                      </div>
                    }>
                    <InfoRow label="รอบการ PM">{inst.pmPerYear && Number(inst.pmPerYear) > 0 ? `ทุก ${Math.round(12 / Number(inst.pmPerYear))} เดือน` : <span className="muted">—</span>}</InfoRow>
                    <InfoRow label="PM ล่าสุด">{inst.pmLast ? fmtDateFull(inst.pmLast) : <span className="muted">—</span>}</InfoRow>
                    <InfoRow label="PM ครั้งถัดไป">{inst.pmNext ? fmtDateFull(inst.pmNext) : <span className="muted">—</span>}</InfoRow>
                    <InfoRow label="ผู้ให้บริการ">{inst.provider || <span className="muted">—</span>}</InfoRow>
                  </SectionCard>
                  );
                })()}
              </div>
            );
          })()}

          {/* real calibration criteria & result (from the master calibration plan).
             Honors calPerYear: an instrument that doesn't require calibration
             (calPerYear='-' / 'N/A' / blank) hides this card even if stale
             cal/exp/calResult values are still sitting in the sheet. */}
          {(() => { const v = String(inst.calPerYear == null ? '' : inst.calPerYear).trim(); return !(!v || v === '-' || /n\/?a/i.test(v) || /ไม่ต้อง/.test(v)); })() &&
          (inst.calPoint || inst.mpe || inst.useRange || inst.calResult) && (
            <SectionCard icon={I.shield} title="เกณฑ์ & ผลการสอบเทียบ" sub="ตามแผนสอบเทียบจริง (Calibration plan)"
              right={inst.calResult ? <span className={`pill ${window.calResultTone(inst.calResult)}`}><span className="dot"></span>{inst.calResult}</span> : null}>
              <div className="info-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 28px' }}>
                <InfoRow label="จุดสอบเทียบ">{inst.calPoint || <span className="muted">—</span>}</InfoRow>
                <InfoRow label="พิสัยการใช้งาน">{inst.useRange || <span className="muted">—</span>}</InfoRow>
                <InfoRow label="เกณฑ์ยอมรับ (MPE)" mono>{inst.mpe || <span className="muted">—</span>}</InfoRow>
                <InfoRow label="ผลการสอบเทียบ">{inst.calResult ? <span style={{ color: `var(--${window.calResultTone(inst.calResult)}-ink)`, fontWeight: 600 }}>{inst.calResult}</span> : <span className="muted">—</span>}</InfoRow>
              </div>
              {calReason && (
                <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line-soft)' }}>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 600, marginBottom: 3 }}>เหตุผล / เกณฑ์การยอมรับ</div>
                  <div style={{ fontSize: 13, color: 'var(--ink)', lineHeight: 1.5 }}>{calReason}</div>
                </div>
              )}
            </SectionCard>
          )}

          {/* calibration result review & fitness-for-use (ISO 15189 §6.4/6.5) —
             only for instruments that actually require calibration */}
          {!(window.isCalExempt && window.isCalExempt(inst)) && window.CalReviewSection && (
            <CalReviewSection inst={inst} admin={admin} readOnly={readOnly} currentUser={currentUser} />
          )}

          {/* ISO 15189 registry / lifecycle */}
          <SectionCard icon={I.building} title="ข้อมูลทะเบียน (ISO 15189)" sub="Asset registry & lifecycle">
            <div className="info-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 28px' }}>
              <InfoRow label="สถานะทะเบียน">
                {meta.lifecycle === 'decommissioned'
                  ? <span style={{ color: 'var(--danger-ink)', fontWeight: 600 }}>ปลดระวาง (Decommissioned)</span>
                  : <span style={{ color: 'var(--ok-ink)', fontWeight: 600 }}>ใช้งาน (In service)</span>}
              </InfoRow>
              {meta.lifecycle === 'decommissioned' && (
                <InfoRow label="เหตุผลปลดระวาง">{meta.decommissionReason || <span className="muted">—</span>}</InfoRow>
              )}
              {meta.lifecycle === 'decommissioned' && meta.replacedBy && (
                <InfoRow label="ถูกทดแทนด้วย">
                  {replacedByInst
                    ? <button onClick={() => go('detail', { code: replacedByInst.code })} className="code" style={{ background: 'none', border: 'none', padding: 0, fontSize: 'inherit', cursor: 'pointer', color: 'var(--accent-strong)', fontWeight: 600, textDecoration: 'underline' }}>{replacedByInst.code}{replacedByInst.type ? ' — ' + replacedByInst.type : ''}</button>
                    : <span className="code">{meta.replacedBy}</span>}
                </InfoRow>
              )}
              {replacesInst && (
                <InfoRow label="ทดแทนเครื่อง">
                  <button onClick={() => go('detail', { code: replacesInst.code })} className="code" style={{ background: 'none', border: 'none', padding: 0, fontSize: 'inherit', cursor: 'pointer', color: 'var(--accent-strong)', fontWeight: 600, textDecoration: 'underline' }}>{replacesInst.code}{replacesInst.type ? ' — ' + replacesInst.type : ''}</button>
                  {replacesInst.decommissionDate && <span style={{ color: 'var(--ink-3)' }}> (ปลดระวาง {fmtDateFull(replacesInst.decommissionDate)})</span>}
                </InfoRow>
              )}
              <InfoRow label="สภาพเมื่อรับเข้า">{meta.condition || <span className="muted">—</span>}</InfoRow>
              <InfoRow label="วันเริ่มใช้งาน">{fmtDateFull(meta.commissionDate)}</InfoRow>
              <InfoRow label="ผลตรวจรับเข้า">{meta.acceptance ? <span style={{ color: 'var(--ok-ink)', fontWeight: 600 }}>{meta.acceptance}</span> : <span className="muted">—</span>}</InfoRow>
              <InfoRow label="ผู้แทนจำหน่าย">{meta.vendor || <span className="muted">—</span>}</InfoRow>
              <InfoRow label="ติดต่อผู้แทนฯ" mono>{meta.vendorContact || <span className="muted">—</span>}</InfoRow>
              <InfoRow label="Software / Firmware" mono>{meta.firmware || <span className="muted">—</span>}</InfoRow>
              <InfoRow label="สัญญาบำรุงรักษา">{meta.serviceContract || <span className="muted">—</span>}</InfoRow>
              <InfoRow label="วันหมดประกัน">{fmtDateFull(meta.warrantyEnd)}</InfoRow>
              <InfoRow label="คู่มือการใช้งาน">{meta.manualRef || <span className="muted">—</span>}</InfoRow>
            </div>
          </SectionCard>

          {/* reagent & QC lots */}
          <ReagentLotsCard code={inst.code} go={go} />

          {/* audit trail for this instrument */}
          <InstrumentAudit code={inst.code} />

          {/* documents — real attachments stored in Google Drive */}
          <InstrumentDocs code={inst.code} admin={admin} />

          {/* training / video links */}
          {(inst.videoLink || inst.retrainLink) && (
            <SectionCard icon={I.copy} title="ลิงก์ & วิดีโออบรม" sub="สื่อการสอนใช้เครื่อง · Retraining">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {inst.videoLink && (
                  <a href={inst.videoLink} target="_blank" rel="noopener noreferrer" className="btn" style={{ justifyContent: 'flex-start', textDecoration: 'none', gap: 10 }}>
                    <I.spark size={16} style={{ color: 'var(--accent)' }} /> วิดีโอสอนใช้เครื่องมือ <span style={{ marginLeft: 'auto', color: 'var(--ink-3)', fontSize: 12 }}>เปิดลิงก์ ↗</span>
                  </a>
                )}
                {inst.retrainLink && (
                  <a href={inst.retrainLink} target="_blank" rel="noopener noreferrer" className="btn" style={{ justifyContent: 'flex-start', textDecoration: 'none', gap: 10 }}>
                    <I.refresh size={16} style={{ color: 'var(--accent)' }} /> วิดีโอ Retraining <span style={{ marginLeft: 'auto', color: 'var(--ink-3)', fontSize: 12 }}>เปิดลิงก์ ↗</span>
                  </a>
                )}
              </div>
            </SectionCard>
          )}

          {/* code decode */}
          <SectionCard title="โครงสร้างรหัสเครื่องมือ" icon={I.tag}>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {[
                { p: 'LAB', t: 'Laboratory', d: 'คำนำหน้าคงที่' },
                { p: parts[1], t: m.short || inst.dept, d: 'แผนก' },
                { p: parts[2], t: typeInfo ? typeInfo.en : inst.typeName, d: 'ประเภทเครื่องมือ' },
                { p: parts[3], t: 'ลำดับที่ ' + parseInt(parts[3], 10), d: 'เลขลำดับในกลุ่ม' },
              ].map((x, idx) => (
                <div key={idx} style={{ flex: '1 1 120px', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 11, padding: '12px 14px' }}>
                  <div className="code" style={{ fontSize: 18, fontWeight: 600, color: idx === 1 ? deptColor(inst.dept, 0.55) : 'var(--ink)' }}>{x.p}</div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 6 }}>{x.t}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{x.d}</div>
                </div>
              ))}
            </div>
          </SectionCard>

          {/* timeline */}
          <SectionCard icon={I.clock} title="ประวัติสอบเทียบ & บำรุงรักษา" sub="บันทึกย้อนหลังและกำหนดการครั้งถัดไป">
            <div style={{ position: 'relative', paddingLeft: 26 }}>
              <div style={{ position: 'absolute', left: 7, top: 6, bottom: 6, width: 2, background: 'var(--line)' }} />
              {history.map((e, idx) => {
                const col = e.kind === 'due' ? (s.key === 'danger' ? 'var(--danger)' : 'var(--warn)') : e.kind === 'pmdue' ? 'var(--warn)' : (e.kind === 'pm' || e.kind === 'pmdue') ? 'var(--accent)' : e.kind === 'in' ? 'var(--ink-4)' : 'var(--ok)';
                return (
                  <div key={idx} style={{ position: 'relative', paddingBottom: idx < history.length - 1 ? 20 : 0 }}>
                    <div style={{ position: 'absolute', left: -26, top: 1, width: 16, height: 16, borderRadius: 99, background: e.future ? 'var(--surface)' : col, border: `2.5px solid ${col}`, boxShadow: '0 0 0 3px var(--surface)' }} />
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                      <span style={{ fontWeight: 600, fontSize: 13.5 }}>{e.title}</span>
                      <span className="tnum" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{fmtDateFull(e.d)}</span>
                      {e.future && <span className="pill warn" style={{ fontSize: 11 }}>กำหนดการ</span>}
                    </div>
                    <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 2 }}>{e.note}</div>
                  </div>
                );
              })}
            </div>
          </SectionCard>
        </div>
      </div>
    </div>
  );
}
window.Detail = Detail;
window.OpBadge = OpBadge;
window.SectionCard = SectionCard;
window.InfoRow = InfoRow;
