// CalibrationScreen.jsx — AegisComply (Supabase-powered Records + History + Efficiency)

const CAL_PAGE_SIZE = 20;
const RESULT_OPTIONS = ['Pass', 'Fail', 'Pending'];

// ── Sortable column header helper ───────────────────────────────────────────
function SortHeaderCal({ label, field, sort, setSort, style }) {
  const active = sort.field === field;
  const dir = active ? sort.dir : null;
  const click = () => setSort({ field, dir: !active ? 'asc' : sort.dir === 'asc' ? 'desc' : 'asc' });
  return (
    <div onClick={click} style={{ ...style, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4, userSelect: 'none' }}>
      <span>{label}</span>
      <span style={{ fontSize: 9, color: active ? '#0D9488' : '#CBD5E1', lineHeight: 1 }}>
        {dir === 'asc' ? '▲' : dir === 'desc' ? '▼' : '↕'}
      </span>
    </div>
  );
}

const calStyles = {
  page: { padding: 24 },
  tabs: { display: 'flex', gap: 2, marginBottom: 20, background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: 4, width: 'fit-content', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' },
  tab: { padding: '7px 18px', borderRadius: 6, fontSize: 13, fontWeight: 500, cursor: 'pointer', border: 'none', background: 'transparent', color: '#64748B', fontFamily: "'DM Sans', sans-serif", transition: 'all 150ms' },
  tabActive: { background: '#0B1F3A', color: 'white', fontWeight: 600 },
  topCards: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 20 },
  miniCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '14px 16px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)', display: 'flex', alignItems: 'center', gap: 14 },
  miniIcon: { width: 40, height: 40, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
  miniVal: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 26, fontWeight: 700, lineHeight: 1 },
  miniLabel: { fontSize: 11, color: '#64748B', marginTop: 2 },
  tableCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' },
  tableHead: { display: 'grid', gridTemplateColumns: '2fr 1.1fr 1.1fr 1.2fr 1.2fr 1fr 110px', gap: 8, padding: '10px 16px', background: '#F8FAFC', borderBottom: '1px solid #E2E8F0' },
  thCell: { fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', textTransform: 'uppercase', color: '#94A3B8' },
  tableRow: { display: 'grid', gridTemplateColumns: '2fr 1.1fr 1.1fr 1.2fr 1.2fr 1fr 110px', gap: 8, padding: '11px 16px', borderBottom: '1px solid #F1F5F9', transition: 'background 150ms', alignItems: 'center' },
  tdName: { fontSize: 13, fontWeight: 500, color: '#0F172A' },
  tdMono: { fontSize: 11, fontFamily: "'JetBrains Mono', monospace", color: '#64748B' },
  tdCell: { fontSize: 13, color: '#475569', display: 'flex', alignItems: 'center' },
  badge: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 4, fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase' },
  certBtn: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 9px', borderRadius: 5, border: '1px solid #CBD5E1', background: 'white', fontSize: 11, color: '#0D9488', cursor: 'pointer', fontWeight: 600, fontFamily: "'DM Sans', sans-serif" },
  uploadBtn: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 9px', borderRadius: 5, border: '1px dashed #CBD5E1', background: '#F8FAFC', fontSize: 11, color: '#94A3B8', cursor: 'pointer', fontFamily: "'DM Sans', sans-serif" },
  addBtn: { height: 36, padding: '0 16px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 600, color: 'white', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: "'DM Sans', sans-serif" },
  addBtnDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },
  bookBtn: { height: 28, padding: '0 10px', borderRadius: 5, border: 'none', background: '#0B1F3A', fontSize: 11, fontWeight: 600, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", display: 'inline-flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' },
  renewBtn: { height: 28, padding: '0 10px', border: '1px solid #CBD5E1', borderRadius: 5, background: 'white', fontSize: 11, color: '#334155', cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", fontWeight: 500 },
  overlay: { position: 'fixed', inset: 0, background: 'rgba(11,31,58,0.45)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 },
  modal: { background: 'white', borderRadius: 12, width: '100%', maxWidth: 560, maxHeight: '90vh', display: 'flex', flexDirection: 'column', boxShadow: '0 16px 48px rgba(0,0,0,0.18)' },
  modalHeader: { padding: '18px 24px', borderBottom: '1px solid #E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  modalTitle: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 16, fontWeight: 700, color: '#0F172A' },
  modalSub: { fontSize: 12, color: '#64748B', marginTop: 3 },
  modalClose: { width: 30, height: 30, borderRadius: 6, border: 'none', background: '#F1F5F9', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#64748B' },
  modalBody: { padding: '20px 24px', overflowY: 'auto', flex: 1 },
  modalFooter: { padding: '14px 24px', borderTop: '1px solid #E2E8F0', display: 'flex', gap: 10, justifyContent: 'flex-end', background: '#F8FAFC' },
  fieldGroup: { marginBottom: 14 },
  fieldLabel: { fontSize: 12, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 5 },
  required: { color: '#DC2626', marginLeft: 2 },
  fieldInput: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 12px', fontFamily: "'DM Sans', sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', boxSizing: 'border-box' },
  fieldSelect: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 28px 0 10px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', appearance: 'none', backgroundImage: 'url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%2364748B\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3e%3cpolyline points=\'6 9 12 15 18 9\'%3e%3c/polyline%3e%3c/svg%3e")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 8px center', boxSizing: 'border-box' },
  fieldTextarea: { width: '100%', minHeight: 60, border: '1px solid #CBD5E1', borderRadius: 6, padding: '8px 10px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', resize: 'vertical', boxSizing: 'border-box' },
  fileWrap: { display: 'flex', alignItems: 'center', gap: 10 },
  fileBtn: { height: 36, padding: '0 14px', border: '1px dashed #CBD5E1', borderRadius: 6, background: 'white', fontSize: 13, fontWeight: 500, color: '#0D9488', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  fileName: { fontSize: 12, color: '#64748B' },
  btnPrimary: { height: 38, padding: '0 18px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  btnPrimaryDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },
  btnSecondary: { height: 38, padding: '0 18px', border: '1px solid #CBD5E1', borderRadius: 6, background: 'white', fontSize: 13, fontWeight: 600, color: '#64748B', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  errorBox: { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 },
  infoBox: { background: '#F0FDFA', border: '1px solid #99F6E4', borderRadius: 6, padding: '10px 12px', fontSize: 12, color: '#0F766E', marginBottom: 14, lineHeight: 1.6 },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
  deviceList: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.05)', maxHeight: 600, overflowY: 'auto' },
  deviceRow: { display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px', borderBottom: '1px solid #F1F5F9', cursor: 'pointer', transition: 'background 150ms' },
  deviceName: { fontSize: 13, fontWeight: 600, color: '#0F172A', flex: 1 },
  deviceSerial: { fontSize: 11, fontFamily: "'JetBrains Mono', monospace", color: '#94A3B8' },
  historyPanel: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' },
  histHead: { display: 'grid', gridTemplateColumns: '1fr 1fr 1.4fr 80px 100px 100px 90px', gap: 8, padding: '9px 16px', background: '#F8FAFC', borderBottom: '1px solid #E2E8F0' },
  histRow: { display: 'grid', gridTemplateColumns: '1fr 1fr 1.4fr 80px 100px 100px 90px', gap: 8, padding: '10px 16px', borderBottom: '1px solid #F1F5F9', alignItems: 'center', transition: 'background 150ms' },
  issueBadge: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 4, fontSize: 10, fontWeight: 700, background: '#FFF5F5', color: '#DC2626', letterSpacing: '0.05em', textTransform: 'uppercase' },
  onTimeBadge: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 4, fontSize: 10, fontWeight: 700 },
  effGrid: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 20 },
  effKpi: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '16px 20px', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' },
  effVal: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 32, fontWeight: 700, lineHeight: 1, marginBottom: 4 },
  effLabel: { fontSize: 11, color: '#64748B' },
  effSubLabel: { fontSize: 11, fontWeight: 600, marginTop: 4 },
  empty: { padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 13 },
};

const calStatusMap = {
  active:              { bg: '#F0FDF4', color: '#16A34A', dot: '#16A34A', label: 'Active' },
  valid:               { bg: '#F0FDF4', color: '#16A34A', dot: '#16A34A', label: 'Active' },
  expiring:            { bg: '#FFFBEB', color: '#D97706', dot: '#D97706', label: 'Expiring' },
  overdue:             { bg: '#FFF7ED', color: '#EA580C', dot: '#EA580C', label: 'Overdue' },
  expired:             { bg: '#FFF5F5', color: '#DC2626', dot: '#DC2626', label: 'Expired' },
  pending_calibration: { bg: '#F1F5F9', color: '#475569', dot: '#475569', label: 'At Lab' },
};

function CalBadge({ status }) {
  const s = calStatusMap[status] || calStatusMap.active;
  return <span style={{ ...calStyles.badge, background: s.bg, color: s.color }}>
    <span style={{ width: 6, height: 6, borderRadius: '50%', background: s.dot, display: 'inline-block' }}/>
    {s.label}
  </span>;
}

function calFmtDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); }
  catch { return d; }
}

function calStatusFromDue(dueDate) {
  if (!dueDate) return 'active';
  const due = new Date(dueDate);
  const now = new Date();
  const daysUntil = (due - now) / 86400000;
  if (daysUntil < 0)  return 'expired';
  if (daysUntil < 30) return 'expiring';
  return 'active';
}

// ── Add Calibration Record Modal ────────────────────────────────────────────
function AddCalibrationModal({ equipment, preSelectedEqId, onClose, onSaved, user }) {
  const [form, setForm] = React.useState({
    equipment_id: preSelectedEqId || '',
    cal_date:     new Date().toISOString().slice(0, 10),
    due_date:     '',
    lab_provider: '',
    result:       'Pass',
    cert_number:  '',
    issue_note:   '',
  });
  const [file, setFile]     = React.useState(null);
  const [error, setError]   = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const selectedEq = equipment.find(e => e.id === form.equipment_id);
  const valid = form.equipment_id && form.cal_date && form.due_date && form.lab_provider;

  // Auto-fill due_date when equipment changes (default: cal_date + 1 year)
  React.useEffect(() => {
    if (form.equipment_id && form.cal_date && !form.due_date) {
      const cal = new Date(form.cal_date);
      cal.setFullYear(cal.getFullYear() + 1);
      set('due_date', cal.toISOString().slice(0, 10));
    }
  }, [form.equipment_id]);

  const uploadCert = async (eqId) => {
    if (!file) return null;
    const sb = window.supabaseClient;
    const ext = file.name.split('.').pop() || 'pdf';
    const path = `${user.id}/${eqId}-${Date.now()}.${ext}`;
    const { error: upErr } = await sb.storage.from('certificates').upload(path, file, { upsert: false });
    if (upErr) throw new Error(`Cert upload failed: ${upErr.message}`);
    return path;
  };

  const handleSubmit = async () => {
    setError('');
    if (!valid) { setError('Equipment, dates, and lab provider are required.'); return; }
    setSaving(true);
    try {
      const sb = window.supabaseClient;

      // 1. Upload certificate if provided
      let certPath = null;
      if (file) certPath = await uploadCert(form.equipment_id);

      // 2. Compute on_time + days_diff vs the equipment's PREVIOUS due date
      const prevDue = selectedEq?.calibration_due ? new Date(selectedEq.calibration_due) : null;
      const calD    = new Date(form.cal_date);
      let daysDiff  = 0, onTime = true;
      if (prevDue) {
        daysDiff = Math.round((calD - prevDue) / 86400000);
        onTime   = daysDiff <= 7; // 7-day grace
      }

      const hasIssue = form.result === 'Fail' || !!form.issue_note.trim();

      // 3. Insert calibration_records row
      const { error: insErr } = await sb.from('calibration_records').insert({
        user_id:      user.id,
        equipment_id: form.equipment_id,
        cal_date:     form.cal_date,
        due_date:     form.due_date,
        lab_provider: form.lab_provider,
        result:       form.result,
        cert_url:     certPath,
        on_time:      onTime,
        days_diff:    daysDiff,
        has_issue:    hasIssue,
        issue_note:   form.issue_note || null,
      });
      if (insErr) throw insErr;

      // 4. Update equipment's last_cal_date, calibration_due, status, cert_url
      const newStatus = calStatusFromDue(form.due_date);
      const eqUpdate = {
        last_cal_date:   form.cal_date,
        calibration_due: form.due_date,
        status:          newStatus,
      };
      if (form.cert_number) eqUpdate.cert_number = form.cert_number;
      if (certPath)         eqUpdate.cert_url    = certPath;
      const { error: upErr } = await sb.from('equipment').update(eqUpdate).eq('id', form.equipment_id);
      if (upErr) console.warn('[Calibration] Equipment update failed:', upErr);

      setSaving(false);
      onSaved();
    } catch (err) {
      console.error('[Calibration] Add record error:', err);
      setError(err.message || 'Save failed.');
      setSaving(false);
    }
  };

  return (
    <div style={calStyles.overlay} onClick={!saving ? onClose : undefined}>
      <div style={calStyles.modal} onClick={e => e.stopPropagation()}>
        <div style={calStyles.modalHeader}>
          <div>
            <div style={calStyles.modalTitle}>Add Calibration Record</div>
            <div style={calStyles.modalSub}>Logs a calibration event and updates the equipment</div>
          </div>
          <button style={calStyles.modalClose} onClick={onClose} disabled={saving}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div style={calStyles.modalBody}>
          {error && <div style={calStyles.errorBox}>{error}</div>}

          <div style={calStyles.fieldGroup}>
            <label style={calStyles.fieldLabel}>Equipment<span style={calStyles.required}>*</span></label>
            <select style={calStyles.fieldSelect} value={form.equipment_id} onChange={e => set('equipment_id', e.target.value)} disabled={!!preSelectedEqId}>
              <option value="">— Select equipment —</option>
              {equipment.map(e => (
                <option key={e.id} value={e.id}>
                  {e.name} ({e.serial_number}){e.calibration_due ? ` — was due ${calFmtDate(e.calibration_due)}` : ''}
                </option>
              ))}
            </select>
          </div>

          <div style={calStyles.grid2}>
            <div style={calStyles.fieldGroup}>
              <label style={calStyles.fieldLabel}>Calibration Date<span style={calStyles.required}>*</span></label>
              <input type="date" style={calStyles.fieldInput} value={form.cal_date} onChange={e => set('cal_date', e.target.value)}/>
            </div>
            <div style={calStyles.fieldGroup}>
              <label style={calStyles.fieldLabel}>Next Due Date<span style={calStyles.required}>*</span></label>
              <input type="date" style={calStyles.fieldInput} value={form.due_date} onChange={e => set('due_date', e.target.value)}/>
            </div>
          </div>

          <div style={calStyles.grid2}>
            <div style={calStyles.fieldGroup}>
              <label style={calStyles.fieldLabel}>Lab / Provider<span style={calStyles.required}>*</span></label>
              <input style={calStyles.fieldInput} placeholder="e.g. SIRIM Bhd" value={form.lab_provider} onChange={e => set('lab_provider', e.target.value)}/>
            </div>
            <div style={calStyles.fieldGroup}>
              <label style={calStyles.fieldLabel}>Result</label>
              <select style={calStyles.fieldSelect} value={form.result} onChange={e => set('result', e.target.value)}>
                {RESULT_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
          </div>

          <div style={calStyles.fieldGroup}>
            <label style={calStyles.fieldLabel}>Certificate Number</label>
            <input style={calStyles.fieldInput} placeholder="e.g. CAL-2025-GD001" value={form.cert_number} onChange={e => set('cert_number', e.target.value)}/>
          </div>

          <div style={calStyles.fieldGroup}>
            <label style={calStyles.fieldLabel}>Certificate File (PDF)</label>
            <div style={calStyles.fileWrap}>
              <label style={calStyles.fileBtn}>
                {file ? 'Change file…' : 'Choose PDF…'}
                <input type="file" accept="application/pdf,.pdf" style={{ display: 'none' }} onChange={e => setFile(e.target.files?.[0] || null)}/>
              </label>
              <span style={calStyles.fileName}>{file ? file.name : 'No file selected'}</span>
            </div>
          </div>

          <div style={calStyles.fieldGroup}>
            <label style={calStyles.fieldLabel}>Issue Note (if any)</label>
            <textarea style={calStyles.fieldTextarea} placeholder="Sensor drift, deviation, re-test required, etc. Leave blank if no issues." value={form.issue_note} onChange={e => set('issue_note', e.target.value)}/>
          </div>

          {selectedEq && selectedEq.calibration_due && (
            <div style={calStyles.infoBox}>
              Previous due date: <strong>{calFmtDate(selectedEq.calibration_due)}</strong>
              <br/>This will update the equipment's <strong>last calibration date</strong> and <strong>next due date</strong>.
            </div>
          )}
        </div>
        <div style={calStyles.modalFooter}>
          <button style={calStyles.btnSecondary} onClick={onClose} disabled={saving}>Cancel</button>
          <button
            style={{ ...calStyles.btnPrimary, ...((!valid || saving) ? calStyles.btnPrimaryDisabled : {}) }}
            onClick={handleSubmit}
            disabled={!valid || saving}
          >
            {saving ? 'Saving…' : 'Save Calibration'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Booking modal — kept as mailto for now ──────────────────────────────────
function BookingModal({ item, devEmail, user, onClose }) {
  const [form, setForm]   = React.useState({ preferredDate: '', lab: '', urgency: item.status === 'expired' || item.status === 'overdue' ? 'Urgent' : 'Normal', remarks: '', recipient: devEmail || '' });
  const [sending, setSending] = React.useState(false);
  const [sent, setSent]   = React.useState(false);
  const [error, setError] = React.useState('');
  const [savedLabs, setSavedLabs] = React.useState([]);

  // Load saved calibration labs + pre-fill default
  React.useEffect(() => {
    (async () => {
      try {
        const sb = window.supabaseClient;
        const { data } = await sb.from('vendors').select('*').eq('type', 'cal_lab').order('is_default', { ascending: false });
        const labs = data || [];
        setSavedLabs(labs);
        const def = labs.find(l => l.is_default);
        if (def) setForm(f => ({ ...f, recipient: def.email, lab: def.name }));
      } catch {}
    })();
  }, []);

  const pickLab = (labId) => {
    if (!labId) return;
    const lab = savedLabs.find(l => l.id === labId);
    if (lab) setForm(f => ({ ...f, recipient: lab.email, lab: lab.name }));
  };

  const handleSend = async () => {
    if (!form.recipient) { setError('Recipient email is required.'); return; }
    setSending(true); setError('');
    try {
      const sb = window.supabaseClient;
      const subject = `[AegisComply] Calibration Booking — ${item.name} (${item.serial_number})`;
      const html = `
        <div style="font-family: 'DM Sans', Arial, sans-serif; max-width: 600px; color: #0F172A;">
          <h2 style="color: #0B1F3A; margin: 0 0 8px;">Calibration Booking Request</h2>
          <p style="color: #64748B; margin: 0 0 18px;">From <strong>${user?.company || 'AegisComply user'}</strong></p>

          <table cellpadding="6" cellspacing="0" style="border-collapse: collapse; width: 100%; background: #F8FAFC; border-radius: 6px;">
            <tr><td style="color: #94A3B8; font-size: 12px;">Equipment</td><td style="font-weight: 600;">${item.name}</td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Serial No.</td><td style="font-family: monospace;">${item.serial_number}</td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Brand / Model</td><td>${item.brand_model || '—'}</td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Due Date</td><td><strong style="color: ${item.status === 'expired' || item.status === 'overdue' ? '#DC2626' : '#0F172A'};">${calFmtDate(item.calibration_due)}</strong></td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Status</td><td>${item.status.toUpperCase()}</td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Location</td><td>${item.location || '—'}</td></tr>
          </table>

          <h3 style="color: #0B1F3A; margin: 18px 0 8px;">Booking Details</h3>
          <table cellpadding="6" cellspacing="0" style="border-collapse: collapse; width: 100%;">
            <tr><td style="color: #94A3B8; font-size: 12px; width: 140px;">Preferred Date</td><td>${form.preferredDate || 'To be confirmed'}</td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Lab / Provider</td><td>${form.lab || '—'}</td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Urgency</td><td><strong style="color: ${form.urgency === 'Emergency' ? '#DC2626' : form.urgency === 'Urgent' ? '#D97706' : '#16A34A'};">${form.urgency}</strong></td></tr>
            <tr><td style="color: #94A3B8; font-size: 12px;">Remarks</td><td>${form.remarks || '—'}</td></tr>
          </table>

          <p style="color: #94A3B8; font-size: 11px; margin-top: 24px; border-top: 1px solid #E2E8F0; padding-top: 12px;">
            Sent automatically from AegisComply by ${user?.name || 'admin'} · ${user?.email || ''}<br/>
            ${new Date().toLocaleString('en-MY')}
          </p>
        </div>
      `;

      const { error: fnErr } = await sb.functions.invoke('send-email', {
        body: {
          to:      form.recipient,
          subject,
          html,
          replyTo: user?.email,
        },
      });
      if (fnErr) throw fnErr;
      setSent(true);
    } catch (err) {
      console.error('[Calibration Booking] email error:', err);
      setError(err.message || 'Failed to send booking email.');
    } finally {
      setSending(false);
    }
  };
  return (
    <div style={calStyles.overlay} onClick={onClose}>
      <div style={{ ...calStyles.modal, maxWidth: 480 }} onClick={e => e.stopPropagation()}>
        <div style={calStyles.modalHeader}>
          <div>
            <div style={calStyles.modalTitle}>Book Calibration</div>
            <div style={calStyles.modalSub}>Sends email to your calibration lab contact</div>
          </div>
          <button style={calStyles.modalClose} onClick={onClose}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div style={calStyles.modalBody}>
          {sent ? (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div style={{ width: 48, height: 48, borderRadius: '50%', background: '#F0FDF4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A', marginBottom: 4 }}>Booking email sent ✓</div>
              <div style={{ fontSize: 12, color: '#64748B' }}>Sent to <strong>{form.recipient}</strong>. Replies will go to {user?.email || 'your email'}.</div>
            </div>
          ) : (
            <>
              {error && <div style={calStyles.errorBox}>{error}</div>}
              <div style={calStyles.infoBox}>
                <strong>{item.name}</strong> · {item.serial_number}<br/>
                Due: <strong>{calFmtDate(item.calibration_due)}</strong> · <CalBadge status={item.status}/>
              </div>
              {savedLabs.length > 0 && (
                <div style={calStyles.fieldGroup}>
                  <label style={calStyles.fieldLabel}>Saved Lab (optional)</label>
                  <select style={calStyles.fieldSelect} value={savedLabs.find(l => l.email === form.recipient)?.id || ''} onChange={e => pickLab(e.target.value)}>
                    <option value="">— Pick from saved labs —</option>
                    {savedLabs.map(l => (
                      <option key={l.id} value={l.id}>
                        {l.name}{l.is_default ? ' (default)' : ''}{l.specialty ? ` · ${l.specialty}` : ''}
                      </option>
                    ))}
                  </select>
                </div>
              )}
              <div style={calStyles.fieldGroup}>
                <label style={calStyles.fieldLabel}>Send to (lab email)<span style={calStyles.required}>*</span></label>
                <input style={calStyles.fieldInput} type="email" placeholder="lab@sirim.my" value={form.recipient} onChange={e => setForm({...form, recipient: e.target.value})}/>
                {savedLabs.length === 0 && (
                  <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 4 }}>💡 Save labs in Settings → Labs & Suppliers for quick reuse.</div>
                )}
              </div>
              <div style={calStyles.grid2}>
                <div style={calStyles.fieldGroup}><label style={calStyles.fieldLabel}>Preferred Date</label><input type="date" style={calStyles.fieldInput} value={form.preferredDate} onChange={e => setForm({...form, preferredDate: e.target.value})}/></div>
                <div style={calStyles.fieldGroup}><label style={calStyles.fieldLabel}>Urgency</label><select style={calStyles.fieldSelect} value={form.urgency} onChange={e => setForm({...form, urgency: e.target.value})}><option>Normal</option><option>Urgent</option><option>Emergency</option></select></div>
              </div>
              <div style={calStyles.fieldGroup}><label style={calStyles.fieldLabel}>Preferred Lab / Provider</label><input style={calStyles.fieldInput} placeholder="e.g. SIRIM Bhd" value={form.lab} onChange={e => setForm({...form, lab: e.target.value})}/></div>
              <div style={calStyles.fieldGroup}><label style={calStyles.fieldLabel}>Remarks</label><textarea style={calStyles.fieldTextarea} placeholder="Access requirements, special instructions..." value={form.remarks} onChange={e => setForm({...form, remarks: e.target.value})}/></div>
              <div style={{ fontSize: 11, color: '#94A3B8', lineHeight: 1.6 }}>
                💡 While in test mode, Resend only delivers to <strong>{user?.email || 'your verified email'}</strong>. After you verify a domain, it'll send to any address.
              </div>
            </>
          )}
        </div>
        <div style={calStyles.modalFooter}>
          <button onClick={onClose} style={calStyles.btnSecondary} disabled={sending}>{sent ? 'Close' : 'Cancel'}</button>
          {!sent && (
            <button
              onClick={handleSend}
              style={{ ...calStyles.btnPrimary, ...((sending || !form.recipient) ? calStyles.btnPrimaryDisabled : {}) }}
              disabled={sending || !form.recipient}
            >
              {sending ? 'Sending…' : 'Send Booking Email'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Records Tab — Equipment-centric calibration view ────────────────────────
function RecordsTab({ devEmail, user, isFrozen }) {
  const [equipment, setEquipment] = React.useState([]);
  const [loading, setLoading]     = React.useState(false);
  const [error, setError]         = React.useState('');
  const [hovered, setHovered]     = React.useState(null);
  const [booking, setBooking]     = React.useState(null);
  const [addingForEqId, setAddingForEqId] = React.useState(null); // null | '' (any) | eqId
  const [sort, setSort] = React.useState({ field: 'calibration_due', dir: 'asc' });

  const fetchEquipment = React.useCallback(async () => {
    setLoading(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { data, error: qErr } = await sb.from('equipment')
        .select('*')
        .order(sort.field, { ascending: sort.dir === 'asc', nullsFirst: false });
      if (qErr) throw qErr;
      setEquipment(data || []);
    } catch (err) {
      console.error('[Calibration Records] fetch error:', err);
      setError(err.message || 'Failed to load.');
    } finally {
      setLoading(false);
    }
  }, [sort]);

  React.useEffect(() => { fetchEquipment(); }, [fetchEquipment]);

  // Realtime
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`cal-records-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'equipment', filter: `user_id=eq.${user.id}` }, () => fetchEquipment())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchEquipment]);

  const downloadCert = async (path) => {
    try {
      const sb = window.supabaseClient;
      const { data, error: urlErr } = await sb.storage.from('certificates').createSignedUrl(path, 60);
      if (urlErr) throw urlErr;
      window.open(data.signedUrl, '_blank');
    } catch (err) {
      alert('Could not open certificate: ' + err.message);
    }
  };

  const stats = React.useMemo(() => {
    const total      = equipment.length;
    const expired    = equipment.filter(e => e.status === 'expired' || e.status === 'overdue').length;
    const expiring   = equipment.filter(e => e.status === 'expiring').length;
    const compliant  = equipment.filter(e => e.status === 'active' || e.status === 'pending_calibration').length;
    return { total, expired, expiring, compliant };
  }, [equipment]);

  return (
    <div>
      <div style={calStyles.topCards}>
        <div style={calStyles.miniCard}>
          <div style={{ ...calStyles.miniIcon, background: '#FFF5F5' }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#DC2626" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
          </div>
          <div><div style={{ ...calStyles.miniVal, color: '#DC2626' }}>{stats.expired}</div><div style={calStyles.miniLabel}>Expired / Overdue</div></div>
        </div>
        <div style={calStyles.miniCard}>
          <div style={{ ...calStyles.miniIcon, background: '#FFFBEB' }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#D97706" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          </div>
          <div><div style={{ ...calStyles.miniVal, color: '#D97706' }}>{stats.expiring}</div><div style={calStyles.miniLabel}>Expiring within 30 days</div></div>
        </div>
        <div style={calStyles.miniCard}>
          <div style={{ ...calStyles.miniIcon, background: '#F0FDF4' }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
          </div>
          <div><div style={{ ...calStyles.miniVal, color: '#16A34A' }}>{stats.compliant}</div><div style={calStyles.miniLabel}>Compliant calibrations</div></div>
        </div>
      </div>

      {error && <div style={calStyles.errorBox}>{error}</div>}

      <div style={calStyles.tableCard}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 15, fontWeight: 600, color: '#0F172A', flex: 1 }}>Calibration Records</span>
          <button
            style={{ ...calStyles.addBtn, background: 'white', color: '#475569', border: '1px solid #CBD5E1' }}
            onClick={async () => {
              try {
                const sb = window.supabaseClient;
                const { data: cal } = await sb.from('calibration_records').select('*');
                await window.AegisPDF.exportCalibrationAudit(user, equipment, cal || []);
              } catch (err) {
                alert('PDF export failed: ' + err.message);
              }
            }}
            title="Export audit-ready PDF"
          >
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
            Export PDF
          </button>
          <button
            style={{ ...calStyles.addBtn, ...(isFrozen ? calStyles.addBtnDisabled : {}) }}
            onClick={() => !isFrozen && setAddingForEqId('')}
            disabled={isFrozen}
          >
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            Add Record
          </button>
        </div>
        <div style={calStyles.tableHead}>
          <SortHeaderCal label="Equipment"    field="name"            sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Last Cal."    field="last_cal_date"   sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Next Due"     field="calibration_due" sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Lab Provider" field="verified_by"     sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <div style={calStyles.thCell}>Certificate</div>
          <SortHeaderCal label="Status"       field="status"          sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <div style={calStyles.thCell}>Actions</div>
        </div>
        {loading && equipment.length === 0 ? (
          <div style={calStyles.empty}>Loading…</div>
        ) : equipment.length === 0 ? (
          <div style={calStyles.empty}>No equipment yet. Add equipment on the Equipment page first.</div>
        ) : equipment.map((r, i) => (
          <div key={r.id} style={{ ...calStyles.tableRow, background: hovered === i ? '#F8FAFC' : 'white' }} onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
            <div>
              <div style={calStyles.tdName}>{r.name}</div>
              <div style={calStyles.tdMono}>{r.serial_number}</div>
            </div>
            <div style={{ ...calStyles.tdCell, fontSize: 12 }}>{calFmtDate(r.last_cal_date)}</div>
            <div style={{ ...calStyles.tdCell, fontSize: 12, fontWeight: (r.status === 'expired' || r.status === 'overdue' || r.status === 'expiring') ? 600 : 400, color: r.status === 'expired' || r.status === 'overdue' ? '#DC2626' : r.status === 'expiring' ? '#D97706' : '#475569' }}>{calFmtDate(r.calibration_due)}</div>
            <div style={{ ...calStyles.tdCell, fontSize: 12 }}>{r.verified_by || '—'}</div>
            <div style={calStyles.tdCell}>
              {r.cert_url
                ? <button style={calStyles.certBtn} onClick={() => downloadCert(r.cert_url)}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                    Download
                  </button>
                : <button style={calStyles.uploadBtn} onClick={() => !isFrozen && setAddingForEqId(r.id)} disabled={isFrozen}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                    Upload
                  </button>
              }
            </div>
            <div style={calStyles.tdCell}><CalBadge status={r.status}/></div>
            <div style={{ display: 'flex', gap: 5 }}>
              {(r.status === 'expiring' || r.status === 'expired' || r.status === 'overdue')
                ? <button style={calStyles.bookBtn} onClick={() => setBooking(r)} disabled={isFrozen}>
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                    Book
                  </button>
                : <button style={calStyles.renewBtn} onClick={() => !isFrozen && setAddingForEqId(r.id)} disabled={isFrozen}>Add Record</button>
              }
            </div>
          </div>
        ))}
      </div>

      {addingForEqId !== null && (
        <AddCalibrationModal
          equipment={equipment}
          preSelectedEqId={addingForEqId || null}
          user={user}
          onClose={() => setAddingForEqId(null)}
          onSaved={() => { setAddingForEqId(null); fetchEquipment(); }}
        />
      )}
      {booking && <BookingModal item={booking} devEmail={devEmail} user={user} onClose={() => setBooking(null)}/>}
    </div>
  );
}

// ── History Tab ─────────────────────────────────────────────────────────────
function OnTimeBadge({ onTime, daysDiff }) {
  if (daysDiff < 0) return <span style={{ ...calStyles.onTimeBadge, background: '#F0FDFA', color: '#0D9488' }}>{Math.abs(daysDiff)}d early</span>;
  if (daysDiff === 0) return <span style={{ ...calStyles.onTimeBadge, background: '#F0FDF4', color: '#16A34A' }}>On time</span>;
  if (daysDiff <= 7) return <span style={{ ...calStyles.onTimeBadge, background: '#FFFBEB', color: '#D97706' }}>+{daysDiff}d late</span>;
  return <span style={{ ...calStyles.onTimeBadge, background: '#FFF5F5', color: '#DC2626' }}>+{daysDiff}d late</span>;
}

function HistoryTab({ user }) {
  const [equipment, setEquipment] = React.useState([]);
  const [selected, setSelected]   = React.useState(null);
  const [history, setHistory]     = React.useState([]);
  const [search, setSearch]       = React.useState('');
  const [expandedRow, setExpandedRow] = React.useState(null);
  const [loading, setLoading]     = React.useState(false);

  const fetchEquipment = React.useCallback(async () => {
    const sb = window.supabaseClient;
    const { data } = await sb.from('equipment').select('*').order('name');
    setEquipment(data || []);
    if (!selected && data && data.length) setSelected(data[0].id);
  }, [selected]);

  const fetchHistory = React.useCallback(async () => {
    if (!selected) { setHistory([]); return; }
    setLoading(true);
    try {
      const sb = window.supabaseClient;
      const { data } = await sb.from('calibration_records').select('*').eq('equipment_id', selected).order('cal_date', { ascending: false });
      setHistory(data || []);
    } finally {
      setLoading(false);
    }
  }, [selected]);

  React.useEffect(() => { fetchEquipment(); }, [fetchEquipment]);
  React.useEffect(() => { fetchHistory(); }, [fetchHistory]);

  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`cal-history-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'calibration_records', filter: `user_id=eq.${user.id}` }, () => fetchHistory())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'equipment', filter: `user_id=eq.${user.id}` }, () => fetchEquipment())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchHistory, fetchEquipment]);

  const filtered = equipment.filter(d =>
    (d.name || '').toLowerCase().includes(search.toLowerCase()) ||
    (d.serial_number || '').toLowerCase().includes(search.toLowerCase())
  );
  const selectedEq = equipment.find(d => d.id === selected);

  const downloadCert = async (path) => {
    try {
      const sb = window.supabaseClient;
      const { data, error } = await sb.storage.from('certificates').createSignedUrl(path, 60);
      if (error) throw error;
      window.open(data.signedUrl, '_blank');
    } catch (err) {
      alert('Could not open: ' + err.message);
    }
  };

  const issueCount = history.filter(h => h.has_issue).length;
  const lateCount  = history.filter(h => (h.days_diff || 0) > 0).length;
  const onTimePct  = history.length > 0 ? Math.round(((history.length - lateCount) / history.length) * 100) : 0;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 16 }}>
      <div style={calStyles.deviceList}>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid #F1F5F9' }}>
          <input style={{ width: '100%', height: 32, border: '1px solid #E2E8F0', borderRadius: 6, padding: '0 10px', fontSize: 12, fontFamily: "'DM Sans', sans-serif", color: '#334155', outline: 'none', boxSizing: 'border-box' }} placeholder="Search device…" value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
        {filtered.length === 0 ? (
          <div style={calStyles.empty}>No equipment.</div>
        ) : filtered.map((d) => (
          <div key={d.id} style={{ ...calStyles.deviceRow, background: selected === d.id ? '#F0FDFA' : 'white', borderLeft: selected === d.id ? '3px solid #0D9488' : '3px solid transparent' }} onClick={() => setSelected(d.id)}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ ...calStyles.deviceName, fontSize: 12 }}>{d.name}</div>
              <div style={calStyles.deviceSerial}>{d.serial_number}</div>
            </div>
            <CalBadge status={d.status}/>
          </div>
        ))}
      </div>

      <div>
        {selectedEq && (
          <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '16px 20px', marginBottom: 14, boxShadow: '0 1px 3px rgba(0,0,0,0.05)', display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 2 }}>{selectedEq.name}</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#94A3B8' }}>{selectedEq.serial_number}</div>
            </div>
            {[
              { label: 'Total records', val: history.length, color: '#0B1F3A' },
              { label: 'On-time rate',  val: history.length ? `${onTimePct}%` : '—', color: onTimePct >= 80 ? '#16A34A' : '#D97706' },
              { label: 'Issues found',  val: issueCount, color: issueCount > 0 ? '#DC2626' : '#16A34A' },
              { label: 'Late count',    val: lateCount, color: lateCount > 0 ? '#D97706' : '#16A34A' },
            ].map((s, i) => (
              <div key={i} style={{ textAlign: 'center' }}>
                <div style={{ fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 22, fontWeight: 700, color: s.color, lineHeight: 1 }}>{s.val}</div>
                <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2 }}>{s.label}</div>
              </div>
            ))}
          </div>
        )}

        {loading ? (
          <div style={calStyles.empty}>Loading history…</div>
        ) : history.length === 0 ? (
          <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '40px 20px', textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>
            No calibration history for this device.<br/>
            <span style={{ fontSize: 12 }}>Add a calibration record from the Records tab to start tracking.</span>
          </div>
        ) : (
          <div style={calStyles.historyPanel}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid #F1F5F9' }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: '#0F172A', fontFamily: "'Helvetica', Arial, sans-serif" }}>Calibration History</span>
            </div>
            <div style={calStyles.histHead}>
              {['Cal. Date', 'Due Date', 'Lab / Provider', 'Result', 'Timing', 'Certificate', 'Issues'].map(h => <div key={h} style={calStyles.thCell}>{h}</div>)}
            </div>
            {history.map((h, i) => (
              <React.Fragment key={h.id}>
                <div
                  style={{ ...calStyles.histRow, background: h.has_issue ? '#FFFBF5' : expandedRow === i ? '#F8FAFC' : 'white', cursor: h.has_issue ? 'pointer' : 'default', borderLeft: h.has_issue ? '3px solid #DC2626' : '3px solid transparent' }}
                  onClick={() => h.has_issue && setExpandedRow(expandedRow === i ? null : i)}
                >
                  <div style={{ fontSize: 13, fontWeight: 500, color: '#0F172A' }}>{calFmtDate(h.cal_date)}</div>
                  <div style={{ fontSize: 13, color: '#475569' }}>{calFmtDate(h.due_date)}</div>
                  <div style={{ fontSize: 12, color: '#475569' }}>{h.lab_provider || '—'}</div>
                  <div>
                    <span style={{ ...calStyles.badge, background: h.result === 'Pass' ? '#F0FDF4' : h.result === 'Fail' ? '#FFF5F5' : '#F1F5F9', color: h.result === 'Pass' ? '#16A34A' : h.result === 'Fail' ? '#DC2626' : '#475569' }}>{h.result}</span>
                  </div>
                  <div><OnTimeBadge onTime={h.on_time} daysDiff={h.days_diff || 0}/></div>
                  <div>
                    {h.cert_url
                      ? <button style={calStyles.certBtn} onClick={e => { e.stopPropagation(); downloadCert(h.cert_url); }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                          PDF
                        </button>
                      : <span style={{ fontSize: 11, color: '#94A3B8' }}>—</span>
                    }
                  </div>
                  <div>
                    {h.has_issue
                      ? <span style={calStyles.issueBadge}>Issue ▾</span>
                      : <span style={{ fontSize: 11, color: '#94A3B8' }}>—</span>
                    }
                  </div>
                </div>
                {expandedRow === i && h.has_issue && (
                  <div style={{ padding: '10px 16px 14px 19px', background: '#FFF5F5', borderBottom: '1px solid #FECACA', borderLeft: '3px solid #DC2626' }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: '#991B1B', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Issue Details</div>
                    <div style={{ fontSize: 13, color: '#7F1D1D', lineHeight: 1.6 }}>{h.issue_note || '(no note)'}</div>
                  </div>
                )}
              </React.Fragment>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Efficiency Tab ──────────────────────────────────────────────────────────
function EfficiencyTab({ user }) {
  const [equipment, setEquipment] = React.useState([]);
  const [allRecords, setAllRecords] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [sort, setSort] = React.useState({ field: 'onTimePct', dir: 'asc' });

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const sb = window.supabaseClient;
      const [eq, recs] = await Promise.all([
        sb.from('equipment').select('*').order('name'),
        sb.from('calibration_records').select('*'),
      ]);
      setEquipment(eq.data || []);
      setAllRecords(recs.data || []);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`cal-eff-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'calibration_records', filter: `user_id=eq.${user.id}` }, () => load())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'equipment', filter: `user_id=eq.${user.id}` }, () => load())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, load]);

  const totalCals  = allRecords.length;
  const onTimeCals = allRecords.filter(r => (r.days_diff || 0) <= 7).length;
  const lateCals   = allRecords.filter(r => (r.days_diff || 0) > 7).length;
  const issuesCals = allRecords.filter(r => r.has_issue).length;
  const onTimePct  = totalCals > 0 ? Math.round((onTimeCals / totalCals) * 100) : 0;

  const deviceStats = React.useMemo(() => {
    const rows = equipment.map(d => {
      const recs = allRecords.filter(r => r.equipment_id === d.id);
      if (!recs.length) return { ...d, onTimePct: 0, issues: 0, total: 0 };
      const late = recs.filter(r => (r.days_diff || 0) > 0).length;
      return { ...d, onTimePct: Math.round(((recs.length - late) / recs.length) * 100), issues: recs.filter(r => r.has_issue).length, total: recs.length };
    });
    const sorted = [...rows].sort((a, b) => {
      const av = a[sort.field], bv = b[sort.field];
      if (av === bv) return 0;
      if (av === null || av === undefined) return 1;
      if (bv === null || bv === undefined) return -1;
      const cmp = typeof av === 'number' ? av - bv : String(av).localeCompare(String(bv));
      return sort.dir === 'asc' ? cmp : -cmp;
    });
    return sorted;
  }, [equipment, allRecords, sort]);

  return (
    <div>
      <div style={calStyles.effGrid}>
        <div style={calStyles.effKpi}>
          <div style={{ ...calStyles.effVal, color: onTimePct >= 80 ? '#16A34A' : '#D97706' }}>{totalCals > 0 ? `${onTimePct}%` : '—'}</div>
          <div style={calStyles.effLabel}>Overall on-time calibration rate</div>
          <div style={{ ...calStyles.effSubLabel, color: onTimePct >= 80 ? '#16A34A' : '#D97706' }}>
            {totalCals === 0 ? 'No records yet' : onTimePct >= 80 ? 'Compliant' : 'Needs improvement'}
          </div>
        </div>
        <div style={calStyles.effKpi}>
          <div style={{ ...calStyles.effVal, color: lateCals > 0 ? '#DC2626' : '#16A34A' }}>{lateCals}</div>
          <div style={calStyles.effLabel}>Calibrations late by &gt;7 days</div>
          <div style={{ ...calStyles.effSubLabel, color: '#64748B' }}>of {totalCals} total records</div>
        </div>
        <div style={calStyles.effKpi}>
          <div style={{ ...calStyles.effVal, color: issuesCals > 0 ? '#DC2626' : '#16A34A' }}>{issuesCals}</div>
          <div style={calStyles.effLabel}>Calibrations with reported issues</div>
          <div style={{ ...calStyles.effSubLabel, color: issuesCals > 0 ? '#DC2626' : '#16A34A' }}>{issuesCals > 0 ? 'Review required' : 'No issues found'}</div>
        </div>
      </div>

      <div style={calStyles.tableCard}>
        <div style={{ padding: '12px 16px', borderBottom: '1px solid #F1F5F9' }}>
          <span style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Helvetica', Arial, sans-serif", color: '#0F172A' }}>Per-Device Compliance</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 80px 80px 80px 130px', gap: 8, padding: '9px 16px', background: '#F8FAFC', borderBottom: '1px solid #E2E8F0' }}>
          <SortHeaderCal label="Equipment"  field="name"          sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Serial"     field="serial_number" sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Records"    field="total"         sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="On Time"    field="onTimePct"     sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Issues"     field="issues"        sort={sort} setSort={setSort} style={calStyles.thCell}/>
          <SortHeaderCal label="Compliance" field="onTimePct"     sort={sort} setSort={setSort} style={calStyles.thCell}/>
        </div>
        {loading ? (
          <div style={calStyles.empty}>Loading…</div>
        ) : deviceStats.length === 0 ? (
          <div style={calStyles.empty}>No equipment data.</div>
        ) : deviceStats.map((d, i) => {
          const compColor = d.total === 0 ? '#94A3B8' : d.onTimePct >= 80 ? '#16A34A' : d.onTimePct >= 60 ? '#D97706' : '#DC2626';
          const compBg    = d.total === 0 ? '#F8FAFC' : d.onTimePct >= 80 ? '#F0FDF4' : d.onTimePct >= 60 ? '#FFFBEB' : '#FFF5F5';
          return (
            <div key={d.id} style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 80px 80px 80px 130px', gap: 8, padding: '11px 16px', borderBottom: '1px solid #F1F5F9', alignItems: 'center' }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: '#0F172A' }}>{d.name}</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#94A3B8' }}>{d.serial_number}</div>
              <div style={{ fontSize: 13, color: '#475569' }}>{d.total || '—'}</div>
              <div style={{ fontSize: 13, color: d.total === 0 ? '#94A3B8' : d.onTimePct >= 80 ? '#16A34A' : '#D97706', fontWeight: 600 }}>{d.total ? `${d.onTimePct}%` : '—'}</div>
              <div style={{ fontSize: 13, fontWeight: d.issues > 0 ? 600 : 400, color: d.issues > 0 ? '#DC2626' : '#94A3B8' }}>{d.issues > 0 ? d.issues : '—'}</div>
              <div>
                {d.total > 0 ? (
                  <div>
                    <div style={{ height: 6, background: '#F1F5F9', borderRadius: 3, overflow: 'hidden', marginBottom: 3 }}>
                      <div style={{ height: '100%', borderRadius: 3, background: compColor, width: `${d.onTimePct}%` }}/>
                    </div>
                    <span style={{ ...calStyles.badge, background: compBg, color: compColor, fontSize: 10 }}>{d.onTimePct >= 80 ? 'Compliant' : d.onTimePct >= 60 ? 'Moderate' : 'Non-compliant'}</span>
                  </div>
                ) : <span style={{ fontSize: 11, color: '#94A3B8' }}>No data</span>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Main CalibrationScreen ──────────────────────────────────────────────────
function CalibrationScreen({ devEmail, user, isFrozen }) {
  const [tab, setTab] = React.useState('records');
  return (
    <div style={calStyles.page}>
      <div style={calStyles.tabs}>
        {[['records', 'Calibration Records'], ['history', 'Device History'], ['efficiency', 'Efficiency Report'], ['qr', 'QR Borrowing']].map(([id, label]) => (
          <button key={id} style={{ ...calStyles.tab, ...(tab === id ? calStyles.tabActive : {}) }} onClick={() => setTab(id)}>{label}</button>
        ))}
      </div>
      {tab === 'records'    && <RecordsTab    devEmail={devEmail} user={user} isFrozen={isFrozen}/>}
      {tab === 'history'    && <HistoryTab    user={user}/>}
      {tab === 'efficiency' && <EfficiencyTab user={user}/>}
      {tab === 'qr'         && <CalibrationQRTab user={user} isFrozen={isFrozen}/>}
    </div>
  );
}

Object.assign(window, { CalibrationScreen });
