// PublicScanScreen.jsx — Worker-facing catalog page after scanning the master QR.
// No login required. Reads account UUID from ?account= and renders either the
// PPE storeroom catalog or the equipment cage borrowing flow.

const PSS_DEPARTMENTS = ['Operations', 'Maintenance', 'Quality', 'HSE', 'Logistics', 'Production', 'Engineering', 'Warehouse'];
const PSS_DURATIONS   = ['4 hours', '1 day', '2 days', '3 days', '1 week', 'Custom'];

const pssStyles = {
  page: { minHeight: '100vh', background: '#F1F5F9', padding: '16px 14px 32px', fontFamily: "'DM Sans', sans-serif", color: '#0F172A' },
  card: { background: 'white', borderRadius: 14, padding: '18px 18px 22px', boxShadow: '0 2px 10px rgba(11,31,58,0.08)', marginBottom: 14 },
  header: { background: 'linear-gradient(135deg,#0B1F3A 0%,#0D9488 100%)', borderRadius: 14, padding: '18px 20px', color: 'white', marginBottom: 14 },
  headerKicker: { fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.8 },
  headerTitle: { fontSize: 19, fontWeight: 700, lineHeight: 1.3, marginTop: 4 },
  headerSub: { fontSize: 12, opacity: 0.85, marginTop: 6 },
  search: { width: '100%', height: 40, border: '1px solid #CBD5E1', borderRadius: 8, padding: '0 12px', fontSize: 14, background: '#F8FAFC', outline: 'none', boxSizing: 'border-box', marginBottom: 12 },
  catalogItem: { display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, padding: '12px 0', borderBottom: '1px solid #F1F5F9', alignItems: 'center' },
  itemName: { fontSize: 14, fontWeight: 600, color: '#0F172A' },
  itemMeta: { fontSize: 11, color: '#94A3B8', marginTop: 3 },
  qtyBox: { display: 'flex', alignItems: 'center', gap: 6 },
  qtyBtn: { width: 32, height: 32, border: '1px solid #CBD5E1', borderRadius: 6, background: 'white', fontSize: 18, cursor: 'pointer', color: '#0F172A', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', touchAction: 'manipulation' },
  qtyVal: { minWidth: 28, textAlign: 'center', fontSize: 15, fontWeight: 700, color: '#0F172A' },
  pickBtn: { height: 32, padding: '0 14px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 12, color: 'white', cursor: 'pointer', fontWeight: 700, touchAction: 'manipulation' },
  outChip: { fontSize: 10, color: '#DC2626', fontWeight: 700, padding: '4px 10px', background: '#FEE2E2', borderRadius: 6, textTransform: 'uppercase' },
  pill: { display: 'inline-block', padding: '2px 8px', borderRadius: 4, fontSize: 10, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase' },
  field: { marginBottom: 12 },
  label: { fontSize: 12, fontWeight: 700, color: '#334155', display: 'block', marginBottom: 6 },
  input: { width: '100%', height: 42, border: '1px solid #CBD5E1', borderRadius: 8, padding: '0 12px', fontSize: 14, color: '#0F172A', outline: 'none', background: '#F8FAFC', boxSizing: 'border-box' },
  primaryBtn: { width: '100%', height: 48, border: 'none', borderRadius: 10, background: '#0D9488', color: 'white', fontSize: 15, fontWeight: 700, cursor: 'pointer', touchAction: 'manipulation' },
  primaryDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },
  backBtn: { height: 36, padding: '0 14px', border: '1px solid #CBD5E1', borderRadius: 8, background: 'white', fontSize: 13, color: '#475569', cursor: 'pointer', marginBottom: 14, fontWeight: 600 },
  errorBox: { background: '#FEE2E2', border: '1px solid #FECACA', color: '#991B1B', borderRadius: 8, padding: '10px 14px', fontSize: 13, marginBottom: 12, lineHeight: 1.5 },
  serialOK:  { background: '#F0FDF4', border: '1px solid #BBF7D0', color: '#16A34A', borderRadius: 6, padding: '8px 12px', fontSize: 12, fontWeight: 600, marginTop: 8 },
  serialBad: { background: '#FEE2E2', border: '1px solid #FECACA', color: '#DC2626', borderRadius: 6, padding: '8px 12px', fontSize: 12, marginTop: 8 },
  cartSummary: { background: '#F0FDFA', border: '1px solid #99F6E4', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#0F766E', marginBottom: 12, fontWeight: 600 },
  successWrap: { textAlign: 'center', padding: '32px 12px' },
  successIcon: { width: 64, height: 64, borderRadius: '50%', background: '#F0FDF4', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 },
  successTitle: { fontSize: 20, fontWeight: 700, color: '#0F172A', marginBottom: 8 },
  successSub: { fontSize: 14, color: '#64748B', lineHeight: 1.6 },
  loading: { padding: 60, textAlign: 'center', color: '#64748B', fontSize: 14 },
  brandFooter: { textAlign: 'center', fontSize: 11, color: '#94A3B8', marginTop: 24 },
};

function stockColor(status) {
  if (status === 'critical') return { bg: '#FEE2E2', color: '#DC2626', label: 'CRITICAL' };
  if (status === 'low')      return { bg: '#FEF3C7', color: '#D97706', label: 'LOW' };
  return { bg: '#F0FDF4', color: '#16A34A', label: 'OK' };
}

// ── Public PPE Storeroom (multi-item cart) ──────────────────────────────────
function PublicPPEScan({ accountId, accountInfo }) {
  const [inventory, setInventory] = React.useState([]);
  const [loading, setLoading]     = React.useState(true);
  const [error, setError]         = React.useState('');
  const [step, setStep]           = React.useState('browse'); // browse | details | done
  const [cart, setCart]           = React.useState({});
  const [search, setSearch]       = React.useState('');
  const [form, setForm]           = React.useState({ empId: '', empName: '', dept: '', contact: '' });
  const [busy, setBusy]           = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  React.useEffect(() => {
    (async () => {
      try {
        const sb = window.supabaseClient;
        const { data, error: e } = await sb.from('ppe_inventory')
          .select('id, name, item_code, category, size, balance, status, unit, min_stock')
          .eq('user_id', accountId)
          .order('name');
        if (e) throw e;
        setInventory(data || []);
      } catch (err) {
        setError('Could not load catalog. ' + (err.message || ''));
      } finally { setLoading(false); }
    })();
  }, [accountId]);

  const filtered = inventory.filter(p => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (p.name || '').toLowerCase().includes(q)
        || (p.item_code || '').toLowerCase().includes(q)
        || (p.category || '').toLowerCase().includes(q);
  });

  const cartItems = Object.entries(cart)
    .map(([id, qty]) => ({ ppe: inventory.find(i => i.id === id), qty }))
    .filter(c => c.ppe && c.qty > 0);
  const totalQty = cartItems.reduce((s, c) => s + c.qty, 0);
  const detailsValid = form.empId && form.empName && form.dept && form.contact && cartItems.length > 0;

  const bump = (ppe, delta) => {
    setCart(c => {
      const cur = c[ppe.id] || 0;
      const next = Math.max(0, Math.min(ppe.balance ?? 0, cur + delta));
      const out = { ...c };
      if (next === 0) delete out[ppe.id]; else out[ppe.id] = next;
      return out;
    });
  };

  const handleSubmit = async () => {
    if (!detailsValid) return;
    setBusy(true); setError('');
    try {
      const sb = window.supabaseClient;
      const rows = cartItems.map(({ ppe, qty }) => ({
        account_id:    accountId,
        emp_id:        form.empId.trim(),
        emp_name:      form.empName.trim(),
        department:    form.dept,
        contact:       form.contact.trim(),
        ppe_item_name: ppe.name + (ppe.size ? ` [${ppe.size}]` : ''),
        ppe_item_id:   ppe.id,
        qty:           qty,
        status:        'pending',
      }));
      const { error: e } = await sb.from('ppe_requests').insert(rows);
      if (e) throw e;
      setStep('done');
    } catch (err) {
      setError('Submit failed: ' + (err.message || 'unknown error'));
    } finally { setBusy(false); }
  };

  if (loading) return <div style={pssStyles.loading}>Loading catalog…</div>;

  if (step === 'done') {
    return (
      <div style={pssStyles.card}>
        <div style={pssStyles.successWrap}>
          <div style={pssStyles.successIcon}>
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          </div>
          <div style={pssStyles.successTitle}>Request Submitted!</div>
          <div style={pssStyles.successSub}>
            {cartItems.length} item{cartItems.length === 1 ? '' : 's'} ({totalQty} total) sent for approval.<br/>
            You'll be notified when your supervisor approves it.
          </div>
          <button style={{ ...pssStyles.primaryBtn, marginTop: 24, maxWidth: 280 }} onClick={() => { setStep('browse'); setCart({}); setForm({ empId: '', empName: '', dept: '', contact: '' }); }}>
            Submit Another Request
          </button>
        </div>
      </div>
    );
  }

  if (step === 'details') {
    return (
      <div style={pssStyles.card}>
        <button style={pssStyles.backBtn} onClick={() => setStep('browse')}>← Back to catalog</button>
        <div style={{ fontSize: 17, fontWeight: 700, marginBottom: 4 }}>Your Details</div>
        <div style={{ fontSize: 13, color: '#64748B', marginBottom: 16 }}>Admin approval required before pickup.</div>
        {error && <div style={pssStyles.errorBox}>{error}</div>}
        <div style={pssStyles.field}><label style={pssStyles.label}>Employee ID *</label><input style={{ ...pssStyles.input, fontFamily: "'JetBrains Mono',monospace" }} placeholder="EMP-0000" value={form.empId} onChange={e => set('empId', e.target.value)} autoComplete="off"/></div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Full Name *</label><input style={pssStyles.input} placeholder="Your full name" value={form.empName} onChange={e => set('empName', e.target.value)} autoComplete="name"/></div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Department *</label>
          <select style={pssStyles.input} value={form.dept} onChange={e => set('dept', e.target.value)}>
            <option value="">Select</option>
            {PSS_DEPARTMENTS.map(d => <option key={d}>{d}</option>)}
          </select>
        </div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Contact Number *</label><input style={pssStyles.input} placeholder="+60 1x-xxx xxxx" value={form.contact} onChange={e => set('contact', e.target.value)} autoComplete="tel"/></div>
        <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8, padding: 12, marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#334155', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Your Cart ({cartItems.length})</div>
          {cartItems.map(({ ppe, qty }) => (
            <div key={ppe.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0', color: '#475569' }}>
              <span>{ppe.name}{ppe.size ? ` [${ppe.size}]` : ''}</span><span style={{ fontWeight: 700 }}>× {qty}</span>
            </div>
          ))}
        </div>
        <button style={{ ...pssStyles.primaryBtn, ...(!detailsValid || busy ? pssStyles.primaryDisabled : {}) }} onClick={handleSubmit} disabled={!detailsValid || busy}>
          {busy ? 'Submitting…' : `Submit Request (${totalQty} item${totalQty === 1 ? '' : 's'})`}
        </button>
      </div>
    );
  }

  return (
    <>
      <div style={pssStyles.card}>
        {error && <div style={pssStyles.errorBox}>{error}</div>}
        <input style={pssStyles.search} placeholder="Search by name, code, category…" value={search} onChange={e => setSearch(e.target.value)}/>
        {filtered.length === 0 ? (
          <div style={{ padding: 30, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>No PPE items found.</div>
        ) : filtered.map(ppe => {
          const balance = ppe.balance ?? 0;
          const inCart  = cart[ppe.id] || 0;
          const sc = stockColor(ppe.status);
          return (
            <div key={ppe.id} style={pssStyles.catalogItem}>
              <div>
                <div style={pssStyles.itemName}>{ppe.name}{ppe.size ? ` [${ppe.size}]` : ''}</div>
                <div style={pssStyles.itemMeta}>
                  <span style={{ ...pssStyles.pill, background: sc.bg, color: sc.color }}>{sc.label} · {balance} avail</span>
                  {ppe.item_code && <span style={{ marginLeft: 6 }}>{ppe.item_code}</span>}
                </div>
              </div>
              {balance <= 0 ? (
                <span style={pssStyles.outChip}>OUT</span>
              ) : (
                <div style={pssStyles.qtyBox}>
                  <button style={pssStyles.qtyBtn} onClick={() => bump(ppe, -1)} disabled={inCart === 0}>−</button>
                  <span style={pssStyles.qtyVal}>{inCart}</span>
                  <button style={pssStyles.qtyBtn} onClick={() => bump(ppe, +1)} disabled={inCart >= balance}>+</button>
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div style={{ position: 'sticky', bottom: 12, marginTop: 14 }}>
        {cartItems.length > 0 && <div style={pssStyles.cartSummary}>{cartItems.length} item{cartItems.length === 1 ? '' : 's'} · {totalQty} total in cart</div>}
        <button style={{ ...pssStyles.primaryBtn, ...(cartItems.length === 0 ? pssStyles.primaryDisabled : {}) }} onClick={() => setStep('details')} disabled={cartItems.length === 0}>
          Continue → ({cartItems.length})
        </button>
      </div>
    </>
  );
}

// ── Public Equipment Cage (pick one + serial confirm) ───────────────────────
function PublicEquipmentScan({ accountId, accountInfo }) {
  const [equipment, setEquipment] = React.useState([]);
  const [loading, setLoading]     = React.useState(true);
  const [error, setError]         = React.useState('');
  const [step, setStep]           = React.useState('browse'); // browse | form | done
  const [picked, setPicked]       = React.useState(null);
  const [search, setSearch]       = React.useState('');
  const [form, setForm]           = React.useState({ name: '', dept: '', contact: '', duration: '1 day', reason: '', serial: '' });
  const [busy, setBusy]           = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const isBorrowable = (eq) => eq.status !== 'pending_calibration' && eq.status !== 'expired';

  React.useEffect(() => {
    (async () => {
      try {
        const sb = window.supabaseClient;
        const { data, error: e } = await sb.from('equipment')
          .select('id, name, serial_number, department, status')
          .eq('user_id', accountId)
          .order('name');
        if (e) throw e;
        setEquipment(data || []);
      } catch (err) {
        setError('Could not load catalog. ' + (err.message || ''));
      } finally { setLoading(false); }
    })();
  }, [accountId]);

  const filtered = equipment.filter(eq => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (eq.name || '').toLowerCase().includes(q)
        || (eq.serial_number || '').toLowerCase().includes(q)
        || (eq.department || '').toLowerCase().includes(q);
  });

  const serialClean = (s) => (s || '').trim().toLowerCase();
  const serialMatches = picked && serialClean(form.serial) && serialClean(form.serial) === serialClean(picked.serial_number);
  const serialEntered = picked && form.serial.trim().length > 0;
  const detailsValid  = form.name && form.dept && form.contact && serialMatches;

  const handleSubmit = async () => {
    if (!detailsValid || !picked) return;
    setBusy(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { error: e } = await sb.from('borrow_requests').insert({
        account_id:     accountId,
        requester_name: form.name.trim(),
        department:     form.dept,
        contact:        form.contact.trim(),
        duration:       form.duration,
        reason:         form.reason || null,
        device_name:    picked.name,
        serial_number:  picked.serial_number,
        equipment_id:   picked.id,
        status:         'pending',
      });
      if (e) throw e;
      setStep('done');
    } catch (err) {
      setError('Submit failed: ' + (err.message || 'unknown error'));
    } finally { setBusy(false); }
  };

  if (loading) return <div style={pssStyles.loading}>Loading equipment cage…</div>;

  if (step === 'done') {
    return (
      <div style={pssStyles.card}>
        <div style={pssStyles.successWrap}>
          <div style={pssStyles.successIcon}>
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          </div>
          <div style={pssStyles.successTitle}>Borrow Request Submitted!</div>
          <div style={pssStyles.successSub}><strong>{picked.name}</strong><br/>Serial confirmed · awaiting admin approval.</div>
          <button style={{ ...pssStyles.primaryBtn, marginTop: 24, maxWidth: 280 }} onClick={() => { setStep('browse'); setPicked(null); setForm({ name: '', dept: '', contact: '', duration: '1 day', reason: '', serial: '' }); }}>
            Borrow Another Device
          </button>
        </div>
      </div>
    );
  }

  if (step === 'form') {
    return (
      <div style={pssStyles.card}>
        <button style={pssStyles.backBtn} onClick={() => setStep('browse')}>← Back to catalog</button>
        <div style={{ fontSize: 17, fontWeight: 700, marginBottom: 4 }}>Confirm & Borrow</div>
        <div style={{ fontSize: 13, color: '#64748B', marginBottom: 14 }}>Type the serial number from the device sticker to verify.</div>
        {error && <div style={pssStyles.errorBox}>{error}</div>}
        <div style={{ background: '#F0F7FC', border: '1px solid #B3D1E8', borderRadius: 8, padding: 12, marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#0F172A' }}>{picked.name}</div>
          <div style={{ fontSize: 12, color: '#475569', marginTop: 4 }}>Department: {picked.department || '—'}</div>
        </div>
        <div style={{ background: '#FFFBEB', border: '1px solid #FCD34D', borderRadius: 8, padding: 12, marginBottom: 14, fontSize: 12, color: '#92400E', lineHeight: 1.5 }}>
          <strong>🔒 Audit check:</strong> Type the serial number printed on the device sticker. This proves the correct unit was taken.
        </div>
        <div style={pssStyles.field}>
          <label style={pssStyles.label}>Serial Number on Device *</label>
          <input style={{ ...pssStyles.input, fontFamily: "'JetBrains Mono',monospace", letterSpacing: '0.05em' }} placeholder="Type serial from sticker" value={form.serial} onChange={e => set('serial', e.target.value)} autoCapitalize="characters" autoComplete="off"/>
          {serialEntered && !serialMatches && <div style={pssStyles.serialBad}>✗ Doesn't match. Check the sticker carefully.</div>}
          {serialMatches && <div style={pssStyles.serialOK}>✓ Serial confirmed</div>}
        </div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Your Full Name *</label><input style={pssStyles.input} placeholder="Full name" value={form.name} onChange={e => set('name', e.target.value)} autoComplete="name"/></div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Department *</label>
          <select style={pssStyles.input} value={form.dept} onChange={e => set('dept', e.target.value)}>
            <option value="">Select</option>
            {PSS_DEPARTMENTS.map(d => <option key={d}>{d}</option>)}
          </select>
        </div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Contact Number *</label><input style={pssStyles.input} placeholder="+60 1x-xxx xxxx" value={form.contact} onChange={e => set('contact', e.target.value)} autoComplete="tel"/></div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Duration</label>
          <select style={pssStyles.input} value={form.duration} onChange={e => set('duration', e.target.value)}>
            {PSS_DURATIONS.map(d => <option key={d}>{d}</option>)}
          </select>
        </div>
        <div style={pssStyles.field}><label style={pssStyles.label}>Reason (optional)</label><input style={pssStyles.input} placeholder="What you'll use it for" value={form.reason} onChange={e => set('reason', e.target.value)}/></div>
        <button style={{ ...pssStyles.primaryBtn, ...(!detailsValid || busy ? pssStyles.primaryDisabled : {}) }} onClick={handleSubmit} disabled={!detailsValid || busy}>
          {busy ? 'Submitting…' : 'Submit Borrow Request'}
        </button>
      </div>
    );
  }

  return (
    <div style={pssStyles.card}>
      {error && <div style={pssStyles.errorBox}>{error}</div>}
      <input style={pssStyles.search} placeholder="Search by name, serial, dept…" value={search} onChange={e => setSearch(e.target.value)}/>
      {filtered.length === 0 ? (
        <div style={{ padding: 30, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>No equipment found.</div>
      ) : filtered.map(eq => {
        const ok = isBorrowable(eq);
        const statusColor = eq.status === 'overdue' || eq.status === 'expired' ? '#DC2626' : eq.status === 'expiring' ? '#D97706' : '#16A34A';
        return (
          <div key={eq.id} style={pssStyles.catalogItem}>
            <div>
              <div style={pssStyles.itemName}>{eq.name}</div>
              <div style={pssStyles.itemMeta}>
                <span style={{ fontFamily: "'JetBrains Mono',monospace" }}>{eq.serial_number}</span>
                {eq.department && ` · ${eq.department}`}
                <span style={{ color: statusColor, marginLeft: 6, fontWeight: 700, textTransform: 'uppercase' }}>· {ok ? 'available' : 'unavailable'}</span>
              </div>
            </div>
            {ok
              ? <button style={pssStyles.pickBtn} onClick={() => { setPicked(eq); setForm(f => ({ ...f, serial: '' })); setStep('form'); }}>Pick →</button>
              : <span style={{ fontSize: 10, color: '#94A3B8', fontWeight: 700, padding: '4px 8px', background: '#F1F5F9', borderRadius: 4 }}>N/A</span>
            }
          </div>
        );
      })}
    </div>
  );
}

// ── Main public scan router ─────────────────────────────────────────────────
function PublicScanScreen({ path }) {
  const [accountInfo, setAccountInfo] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError]     = React.useState('');

  const params    = new URLSearchParams(window.location.search);
  const accountId = params.get('account');
  const isPPE     = path === '/ppe-storeroom';
  const isCage    = path === '/equipment-cage';

  React.useEffect(() => {
    if (!accountId) { setError('Missing account in URL. Please rescan the QR code.'); setLoading(false); return; }
    (async () => {
      try {
        const sb = window.supabaseClient;
        const { data, error: e } = await sb.rpc('get_public_account_info', { account_id: accountId });
        if (e) throw e;
        const info = Array.isArray(data) ? data[0] : data;
        if (!info) { setError('Invalid QR code — account not found. Please ask your supervisor for a new QR.'); }
        else if (!info.active) { setError('This account is currently inactive. Please contact your supervisor.'); }
        else { setAccountInfo(info); }
      } catch (err) {
        setError('Could not verify QR. ' + (err.message || ''));
      } finally { setLoading(false); }
    })();
  }, [accountId]);

  if (loading) {
    return <div style={pssStyles.page}><div style={pssStyles.loading}>Verifying QR code…</div></div>;
  }

  if (error) {
    return (
      <div style={pssStyles.page}>
        <div style={pssStyles.card}>
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#FEE2E2', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
              <svg width="28" height="28" 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 style={{ fontSize: 16, fontWeight: 700, color: '#0F172A', marginBottom: 6 }}>Cannot Open This QR</div>
            <div style={{ fontSize: 13, color: '#64748B', lineHeight: 1.6 }}>{error}</div>
          </div>
        </div>
      </div>
    );
  }

  const kicker = isPPE ? 'PPE Storeroom · Request Form' : 'Equipment Cage · Borrow Form';
  const title  = isPPE ? 'Pick the PPE you need' : 'Browse equipment to borrow';

  return (
    <div style={pssStyles.page}>
      <div style={pssStyles.header}>
        <div style={pssStyles.headerKicker}>{kicker}</div>
        <div style={pssStyles.headerTitle}>{title}</div>
        <div style={pssStyles.headerSub}>at <strong>{accountInfo.company}</strong></div>
      </div>
      {isPPE  && <PublicPPEScan accountId={accountId} accountInfo={accountInfo}/>}
      {isCage && <PublicEquipmentScan accountId={accountId} accountInfo={accountInfo}/>}
      <div style={pssStyles.brandFooter}>Powered by AegisComply · <a href="https://aegisfeld.com" style={{ color: '#0D9488' }}>aegisfeld.com</a></div>
    </div>
  );
}

Object.assign(window, { PublicScanScreen });
