/* ============================================================
   UNSTOPPABLES — ID document capture + PII reveal reason gate
   Exports: IdDocumentCard, CaptureModal, RevealReasonModal
   ============================================================ */

// ---------- striped placeholder for an existing (imported) ID doc ----------
function IdPlaceholderSvg() {
  return (
    <svg viewBox="0 0 120 76" width="100%" height="100%" style={{ display: 'block' }} aria-hidden="true">
      <defs>
        <pattern id="id-stripes" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <rect width="8" height="8" fill="oklch(0.75 0.03 270)" />
          <rect width="4" height="8" fill="oklch(0.68 0.04 270)" />
        </pattern>
      </defs>
      <rect width="120" height="76" rx="6" fill="url(#id-stripes)" />
      <rect x="10" y="12" width="32" height="38" rx="4" fill="oklch(0.85 0.02 270)" />
      <rect x="50" y="16" width="58" height="7" rx="3.5" fill="oklch(0.85 0.02 270)" />
      <rect x="50" y="29" width="44" height="7" rx="3.5" fill="oklch(0.85 0.02 270)" />
      <rect x="50" y="42" width="52" height="7" rx="3.5" fill="oklch(0.85 0.02 270)" />
      <text x="60" y="68" textAnchor="middle" fontFamily="monospace" fontSize="8" fill="oklch(0.45 0.03 270)">gov-id scan</text>
    </svg>
  );
}

// ---------- camera / upload capture modal ----------
function CaptureModal({ onCapture, onClose, push }) {
  const videoRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const fileRef = React.useRef(null);
  const [camState, setCamState] = React.useState('idle'); // idle | live | denied

  const startCamera = () => {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { setCamState('denied'); return; }
    navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
      .then(stream => {
        streamRef.current = stream;
        setCamState('live');
        requestAnimationFrame(() => {
          if (videoRef.current) { videoRef.current.srcObject = stream; videoRef.current.play(); }
        });
      })
      .catch(() => setCamState('denied'));
  };
  const stopCamera = () => {
    if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; }
  };
  React.useEffect(() => stopCamera, []);

  const snap = () => {
    const v = videoRef.current;
    if (!v || !v.videoWidth) return;
    const c = document.createElement('canvas');
    c.width = v.videoWidth; c.height = v.videoHeight;
    c.getContext('2d').drawImage(v, 0, 0);
    stopCamera();
    onCapture(c.toDataURL('image/jpeg', 0.85));
  };
  const onFile = e => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => onCapture(r.result);
    r.readAsDataURL(f);
  };

  return ReactDOM.createPortal(
    <div style={{ position: 'fixed', inset: 0, zIndex: 360, display: 'grid', placeItems: 'center', padding: 20 }}>
      <div onClick={() => { stopCamera(); onClose(); }} style={{ position: 'absolute', inset: 0, background: 'oklch(0.1 0.02 305 / 0.5)', backdropFilter: 'blur(3px)' }}></div>
      <div className="glass-strong" style={{ position: 'relative', width: 'min(460px, 100%)', borderRadius: 'var(--radius-xl)', padding: 26, boxShadow: 'var(--shadow-pop)', animation: 'trellis-pop .35s var(--ease-spring)', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ fontSize: 17, fontWeight: 700 }}>Capture ID document</h3>
          <button onClick={() => { stopCamera(); onClose(); }} style={{ padding: 8, borderRadius: 10, background: 'var(--hover)' }}><Icon name="x" size={15} /></button>
        </div>

        {camState === 'live' ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <video ref={videoRef} playsInline muted style={{ width: '100%', borderRadius: 16, background: 'black', aspectRatio: '4 / 3', objectFit: 'cover' }}></video>
            <button onClick={snap} style={{ padding: '14px 20px', borderRadius: 14, fontSize: 14.5, fontWeight: 700, fontFamily: 'var(--font-display)', background: 'var(--accent)', color: 'var(--accent-ink)' }}>
              Snap photo
            </button>
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <button onClick={startCamera} style={{
              padding: '22px 12px', borderRadius: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9,
              background: 'var(--hover)', border: '1.5px dashed var(--hairline-strong)', fontSize: 13.5, fontWeight: 700
            }}>
              <Icon name="eye" size={22} node={false} style={{ color: 'var(--accent)' }} />
              Use camera
              <span className="t-faint" style={{ fontSize: 11, fontWeight: 600 }}>phone · tablet · PC webcam</span>
            </button>
            <button onClick={() => fileRef.current && fileRef.current.click()} style={{
              padding: '22px 12px', borderRadius: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9,
              background: 'var(--hover)', border: '1.5px dashed var(--hairline-strong)', fontSize: 13.5, fontWeight: 700
            }}>
              <Icon name="import" size={22} node={false} style={{ color: 'var(--blue)' }} />
              Upload photo
              <span className="t-faint" style={{ fontSize: 11, fontWeight: 600 }}>or take one via picker</span>
            </button>
          </div>
        )}
        {camState === 'denied' && (
          <div style={{ padding: '10px 14px', borderRadius: 12, background: 'var(--gold-soft)', fontSize: 12.5, lineHeight: 1.5 }}>
            Camera unavailable or permission denied — use <strong>Upload photo</strong> instead; on phones the picker opens the camera directly.
          </div>
        )}
        <input ref={fileRef} type="file" accept="image/*" capture="environment" onChange={onFile} style={{ display: 'none' }} />
        <div className="t-faint" style={{ fontSize: 11.5, display: 'flex', gap: 7, alignItems: 'flex-start', lineHeight: 1.5 }}>
          <Icon name="shield" size={13} node={false} style={{ flexShrink: 0, marginTop: 1 }} />
          Stored encrypted in Cloud Storage (Canada), masked by default. Never kept on this device.
        </div>
      </div>
    </div>,
    document.body
  );
}

// ---------- client signature capture: consent confirmation → white pad ----------
function SignatureModal({ onDone, onClose }) {
  const [step, setStep] = React.useState(0);           // 0 = consent confirm, 1 = pad
  const canvasRef = React.useRef(null);
  const drawing = React.useRef(false);
  const [hasInk, setHasInk] = React.useState(false);

  const initCanvas = React.useCallback(node => {
    canvasRef.current = node;
    if (!node) return;
    const dpr = window.devicePixelRatio || 1;
    const w = node.clientWidth, h = node.clientHeight;
    node.width = w * dpr; node.height = h * dpr;
    const ctx = node.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, w, h);
    ctx.strokeStyle = '#1c1530'; ctx.lineWidth = 2.2; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  }, []);

  const pos = e => {
    const r = canvasRef.current.getBoundingClientRect();
    return [e.clientX - r.left, e.clientY - r.top];
  };
  const down = e => {
    e.preventDefault();
    canvasRef.current.setPointerCapture(e.pointerId);
    drawing.current = true;
    const ctx = canvasRef.current.getContext('2d');
    const [x, y] = pos(e);
    ctx.beginPath(); ctx.moveTo(x, y);
  };
  const move = e => {
    if (!drawing.current) return;
    const ctx = canvasRef.current.getContext('2d');
    const [x, y] = pos(e);
    ctx.lineTo(x, y); ctx.stroke();
    if (!hasInk) setHasInk(true);
  };
  const up = () => { drawing.current = false; };
  const clear = () => {
    const node = canvasRef.current;
    const ctx = node.getContext('2d');
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, node.clientWidth, node.clientHeight);
    setHasInk(false);
  };
  const done = () => { if (hasInk) onDone(canvasRef.current.toDataURL('image/png')); };

  const btn = (primary, disabled) => ({
    padding: '12px 22px', borderRadius: 13, fontSize: 14, fontWeight: 700, fontFamily: 'var(--font-display)',
    background: disabled ? 'var(--hover)' : primary ? 'var(--accent)' : 'var(--hover)',
    color: disabled ? 'var(--ink-faint)' : primary ? 'var(--accent-ink)' : 'var(--ink-soft)',
    border: primary ? 'none' : '1px solid var(--hairline)', minHeight: 46,
    cursor: disabled ? 'not-allowed' : 'pointer'
  });

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 500, display: 'grid', placeItems: 'center', padding: 20 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'oklch(0.1 0.02 305 / 0.6)', backdropFilter: 'blur(4px)' }}></div>
      <div className="glass-strong" style={{ position: 'relative', width: 'min(620px, 100%)', borderRadius: 'var(--radius-xl)', padding: 'clamp(22px, 4vw, 32px)', boxShadow: 'var(--shadow-pop)', animation: 'trellis-pop .3s var(--ease-spring)' }}>
        {step === 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div style={{ width: 56, height: 56, borderRadius: 16, display: 'grid', placeItems: 'center', background: 'var(--gold-soft)', color: 'var(--gold-deep)' }}>
              <Icon name="shield" size={26} node={false} />
            </div>
            <h2 style={{ fontSize: 19, fontWeight: 700, lineHeight: 1.35 }}>
              Do you confirm that an EHCW staff member has explained the Consent Form and Liability Waiver to you?
            </h2>
            <p className="t-soft" style={{ fontSize: 13.5, lineHeight: 1.6, margin: 0 }}>
              By signing on the next screen you acknowledge the consent and waiver as explained to you.
              Your signature is stored securely with your record.
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button onClick={onClose} style={btn(false, false)}>Cancel</button>
              <button onClick={() => setStep(1)} style={btn(true, false)}>I confirm</button>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h2 style={{ fontSize: 18, fontWeight: 700 }}>Client signature</h2>
            <p className="t-faint" style={{ fontSize: 12.5, margin: 0 }}>Please sign inside the white box.</p>
            <canvas ref={initCanvas}
              onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerLeave={up}
              style={{ width: '100%', height: 220, borderRadius: 14, background: '#ffffff',
                       border: '1.5px solid var(--hairline-strong)', touchAction: 'none', cursor: 'crosshair', display: 'block' }} />
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button onClick={onClose} style={btn(false, false)}>Cancel</button>
              <button onClick={clear} style={btn(false, false)}>Clear</button>
              <button onClick={done} disabled={!hasInk} style={btn(true, !hasInk)}>Done</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ---------- vault document lightbox (front/back popout, audit-logged) ----------
function DocLightbox({ client, field, label, onClose }) {
  const atts = (client._rec && client._rec[field]) || [];
  const [imgs, setImgs] = React.useState({}); // attId -> objectURL | 'error'
  React.useEffect(() => {
    let dead = false; const urls = [];
    atts.forEach(a => {
      window.EHCW_DB.loadDocImage(client._docId, field, a.id)
        .then(u => { urls.push(u); if (!dead) setImgs(m => ({ ...m, [a.id]: u })); })
        .catch(() => { if (!dead) setImgs(m => ({ ...m, [a.id]: 'error' })); });
    });
    return () => { dead = true; urls.forEach(u => URL.revokeObjectURL(u)); };
  }, []);
  const side = i => atts.length === 2 ? (i === 0 ? ' · front' : ' · back') : '';
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 400, display: 'grid', placeItems: 'center', padding: 20 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'oklch(0.1 0.02 305 / 0.62)', backdropFilter: 'blur(4px)' }}></div>
      <div className="glass-strong" style={{ position: 'relative', width: 'min(680px, 100%)', maxHeight: '88vh', overflowY: 'auto', borderRadius: 'var(--radius-xl)', padding: 'clamp(20px, 3vw, 30px)', boxShadow: 'var(--shadow-pop)', animation: 'trellis-pop .3s var(--ease-spring)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <h2 style={{ fontSize: 18, fontWeight: 700 }}>{label} — {client.id}</h2>
          <button onClick={onClose} style={{ padding: 8, borderRadius: 10, background: 'var(--hover)' }}><Icon name="x" size={15} /></button>
        </div>
        <p className="t-faint" style={{ fontSize: 12, margin: '0 0 14px' }}>
          Loaded live from the secure vault (Montréal) — this view is recorded in the audit trail.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {atts.map((a, i) => (
            <div key={a.id}>
              <div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 7, color: 'var(--ink-soft)' }}>Image {i + 1}{side(i)}</div>
              <div style={{ borderRadius: 14, overflow: 'hidden', border: '1px solid var(--hairline-strong)', background: 'var(--hover)', minHeight: 120, display: 'grid', placeItems: 'center' }}>
                {imgs[a.id] === 'error'
                  ? <span className="t-faint" style={{ fontSize: 13, padding: 24 }}>Could not load this image from the vault.</span>
                  : imgs[a.id]
                  ? <img src={imgs[a.id]} alt={`${label} image ${i + 1}`} style={{ width: '100%', display: 'block' }} />
                  : <span style={{ width: 22, height: 22, border: '3px solid var(--accent)', borderTopColor: 'transparent', borderRadius: 99, animation: 'spin 0.7s linear infinite', margin: 24 }}></span>}
              </div>
            </div>
          ))}
          {atts.length === 0 && <span className="t-faint" style={{ fontSize: 13 }}>No images on file.</span>}
        </div>
      </div>
    </div>
  );
}

// ---------- ID document card inside the client drawer ----------
function IdDocumentCard({ client, role, revealed, push, requestAdmin }) {
  // Truth source: the migrated attachments on the client's own record.
  // Demo records (no _docId) keep the deterministic prototype behaviour.
  const atts = (client._rec && client._rec.docIdVerification) || [];
  const isLive = !!client._docId;
  const n = parseInt((client.id || 'EH-1').replace(/\D/g, ''), 10) || 1;
  const importedDoc = isLive ? atts.length > 0 : n % 4 !== 0;
  const [captured, setCaptured] = React.useState(null); // dataURL, session-only
  const [capturing, setCapturing] = React.useState(false);
  const [viewing, setViewing] = React.useState(false);  // vault lightbox
  const [thumb, setThumb] = React.useState(null);        // real scan for the card
  const hasDoc = importedDoc || !!captured;
  const canSee = revealed && role === 'admin';

  // Revealed + live record → the thumbnail is the real scan, not a drawing
  React.useEffect(() => {
    let dead = false;
    if (canSee && isLive && atts.length > 0 && !thumb && window.EHCW_DB?.loadDocImage) {
      window.EHCW_DB.loadDocImage(client._docId, 'docIdVerification', atts[0].id)
        .then(u => { if (!dead) setThumb(u); else URL.revokeObjectURL(u); })
        .catch(() => {});
    }
    return () => { dead = true; if (thumb) URL.revokeObjectURL(thumb); };
  }, [canSee, isLive]);
  const openViewer = () => {
    if (!isLive || atts.length === 0) return;
    if (!canSee) { push('Reveal PII first — document views are audit-logged'); return; }
    setViewing(true);
  };

  return (
    <div className="glass" style={{ borderRadius: 16, padding: '16px', margin: '0 0 20px', display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
      {/* thumbnail */}
      <div onClick={openViewer} title={isLive && atts.length ? 'Click to view' : undefined}
        style={{ width: 120, height: 76, borderRadius: 10, overflow: 'hidden', position: 'relative', flexShrink: 0, border: '1px solid var(--hairline-strong)', background: 'var(--hover)', cursor: isLive && atts.length ? 'pointer' : 'default' }}>
        {hasDoc ? (
          <React.Fragment>
            <div style={{ position: 'absolute', inset: 0, filter: canSee ? 'none' : 'blur(9px) saturate(0.7)', transition: 'filter .4s ease' }}>
              {thumb
                ? <img src={thumb} alt="ID document" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                : captured
                ? <img src={captured} alt="ID document" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                : <IdPlaceholderSvg />}
            </div>
            {!canSee && (
              <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', color: 'oklch(0.99 0 0 / 0.9)', background: 'oklch(0.2 0.03 305 / 0.25)' }}>
                <Icon name="lock" size={18} stroke={2.2} node={false} />
              </div>
            )}
          </React.Fragment>
        ) : (
          <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', border: '1.5px dashed var(--hairline-strong)', borderRadius: 10, color: 'var(--ink-faint)' }}>
            <Icon name="clients" size={20} node={false} />
          </div>
        )}
      </div>

      {/* status + actions */}
      <div style={{ flex: 1, minWidth: 180, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 13.5, fontWeight: 700 }}>ID document</span>
          {hasDoc
            ? <Badge tone="leaf"><Icon name="check" size={11} node={false} /> {isLive && atts.length ? `${atts.length} image${atts.length === 1 ? '' : 's'} on file` : 'On file'}{canSee ? ' · click to view' : ' · masked'}</Badge>
            : <Badge tone="gold">Not on file</Badge>}
        </div>
        <span className="t-faint" style={{ fontSize: 12, lineHeight: 1.5 }}>
          {hasDoc
            ? (canSee ? 'Unmasked for this session — view is audit-logged.' : 'Image exists in the vault. Only an Admin reveal shows the document itself.')
            : 'Capture the client\u2019s ID with your camera, or upload a photo.'}
        </span>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button onClick={() => setCapturing(true)} style={{
            padding: '8px 14px', borderRadius: 11, fontSize: 12.5, fontWeight: 700,
            background: hasDoc ? 'var(--hover)' : 'var(--accent)',
            color: hasDoc ? 'var(--ink-soft)' : 'var(--accent-ink)',
            border: hasDoc ? '1px solid var(--hairline-strong)' : 'none',
            display: 'inline-flex', alignItems: 'center', gap: 6
          }}><Icon name="eye" size={13} node={false} /> {hasDoc ? 'Retake / replace' : 'Capture ID'}</button>
          {hasDoc && !canSee && role !== 'admin' && (
            <button onClick={() => requestAdmin && requestAdmin()} className="t-faint" style={{ fontSize: 12, fontWeight: 700, padding: '8px 6px' }}>
              Admin can reveal →
            </button>
          )}
        </div>
      </div>

      {capturing && (
        <CaptureModal
          onClose={() => setCapturing(false)}
          push={push}
          onCapture={img => {
            setCaptured(img); setCapturing(false);
            push('ID stored — encrypted in Canada, masked by default ✓');
          }} />
      )}
      {viewing && (
        <DocLightbox client={client} field="docIdVerification" label="ID document" onClose={() => setViewing(false)} />
      )}
    </div>
  );
}

// ---------- reveal-reason gate ----------
const REVEAL_REASONS = [
  'OW / ODSP application',
  'Legal or court filing',
  'Housing application',
  'Funder audit',
  'Record correction',
  'Emergency / safety check'
];

function RevealReasonModal({ client, onConfirm, onClose }) {
  const [reason, setReason] = React.useState(null);
  const [comment, setComment] = React.useState('');

  return ReactDOM.createPortal(
    <div style={{ position: 'fixed', inset: 0, zIndex: 360, display: 'grid', placeItems: 'center', padding: 20 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'oklch(0.1 0.02 305 / 0.5)', backdropFilter: 'blur(3px)' }}></div>
      <div className="glass-strong" style={{ position: 'relative', width: 'min(480px, 100%)', borderRadius: 'var(--radius-xl)', padding: 28, boxShadow: 'var(--shadow-pop)', animation: 'trellis-pop .35s var(--ease-spring)', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
          <div>
            <h3 style={{ fontSize: 17, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="eye" size={17} node={false} style={{ color: 'var(--coral)' }} /> Why are you revealing PII?
            </h3>
            <p className="t-soft" style={{ fontSize: 12.5, margin: '6px 0 0', lineHeight: 1.55 }}>
              Record <span className="mono">{client.id}</span> · your reason is written to the audit trail with your name and timestamp.
            </p>
          </div>
          <button onClick={onClose} style={{ padding: 8, borderRadius: 10, background: 'var(--hover)' }}><Icon name="x" size={15} /></button>
        </div>

        {/* reason tabs */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {REVEAL_REASONS.map(r => {
            const on = reason === r;
            return (
              <button key={r} onClick={() => setReason(r)} style={{
                padding: '10px 16px', borderRadius: 99, fontSize: 13, fontWeight: 700, minHeight: 42,
                background: on ? 'var(--accent)' : 'var(--hover)',
                color: on ? 'var(--accent-ink)' : 'var(--ink-soft)',
                border: '1px solid ' + (on ? 'transparent' : 'var(--hairline)'),
                transition: 'all .15s', display: 'inline-flex', alignItems: 'center', gap: 6
              }}>{on && <Icon name="check" size={13} stroke={2.6} node={false} />}{r}</button>
            );
          })}
        </div>

        <div>
          <label style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.04em', color: 'var(--ink-soft)', display: 'block', marginBottom: 7 }}>
            Additional comment <span className="t-faint" style={{ fontWeight: 500 }}>(optional)</span>
          </label>
          <textarea value={comment} onChange={e => setComment(e.target.value)} rows="2" placeholder="e.g. preparing June OW renewal package…"
            style={{
              width: '100%', padding: '12px 14px', borderRadius: 13, border: '1px solid var(--hairline-strong)',
              background: 'var(--glass-input)', fontSize: 13.5, outline: 'none', resize: 'vertical',
              fontFamily: 'var(--font-body)', boxSizing: 'border-box'
            }}></textarea>
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={onClose} style={{ flex: 1, padding: '13px 16px', borderRadius: 14, fontSize: 13.5, fontWeight: 700, background: 'var(--hover)', border: '1px solid var(--hairline)' }}>Cancel</button>
          <button disabled={!reason} onClick={() => reason && onConfirm(reason, comment)} style={{
            flex: 1.5, padding: '13px 16px', borderRadius: 14, fontSize: 13.5, fontWeight: 700,
            fontFamily: 'var(--font-display)',
            background: reason ? 'var(--coral)' : 'var(--hover)',
            color: reason ? 'white' : 'var(--ink-faint)',
            cursor: reason ? 'pointer' : 'not-allowed', transition: 'all .2s'
          }}>{reason ? 'Reveal & log to audit' : 'Select a reason first'}</button>
        </div>
      </div>
    </div>,
    document.body
  );
}

Object.assign(window, { IdDocumentCard, CaptureModal, RevealReasonModal, DocLightbox, SignatureModal });
