// alerts.jsx — interruptive alerts, hard stops, and cosign.
// The alert-fatigue point lands because of the RATIO: of the alerts that fire
// on a correct, clinically-indicated order, exactly one is worth reading. The
// other five demand the same number of clicks as the one that matters.
// Exports on window: AlertModal, HardStopModal, CosignModal, ALERTS

const ALERTS = {
  bpa: {
    id: 'bpa',
    severity: 'high',
    relevant: true,
    kind: 'Best Practice Advisory',
    title: 'ACE inhibitor ordered in acute kidney injury',
    body: 'This patient has an active problem of Acute Kidney Injury (N17.9). ACE inhibitors may reduce glomerular filtration pressure and worsen renal function. Serum creatinine is 2.1 mg/dL (baseline 1.4). Consider deferring until renal function has stabilised.',
    requiresReason: true,
    reasons: [
      'Benefit outweighs risk — clinical judgment',
      'Renal function improving; will monitor',
      'Patient tolerated previously',
      'Alert not applicable to this patient',
      'Will obtain nephrology input',
    ],
    accept: 'Acknowledge & Continue',
  },
  duplicate: {
    id: 'duplicate',
    severity: 'medium',
    relevant: false,
    kind: 'Duplicate Therapy Warning',
    title: 'Possible therapeutic duplication — antihypertensive',
    body: 'Patient has active orders for metoprolol succinate 50 mg PO daily and amlodipine 5 mg PO daily. The new order (lisinopril 10 mg PO daily) belongs to the same therapeutic category: ANTIHYPERTENSIVE AGENTS.',
    options: ['Keep both orders', 'Discontinue existing', 'Cancel new order'],
    accept: 'Continue',
  },
  allergy: {
    id: 'allergy',
    severity: 'low',
    relevant: false,
    kind: 'Allergy Interaction Check',
    title: 'Cross-sensitivity screen — Sulfamethoxazole-Trimethoprim',
    body: 'Patient has a recorded allergy to Sulfamethoxazole-Trimethoprim (rash, urticaria). The ordered agent has been screened for cross-sensitivity. No established cross-reactivity was identified. This alert is informational.',
    options: ['Not applicable', 'Reviewed with patient'],
    accept: 'Continue',
  },
  renal: {
    id: 'renal',
    severity: 'medium',
    relevant: true,
    kind: 'Renal Dosing Advisory',
    title: 'Dose adjustment recommended — CrCl 29 mL/min',
    body: 'Estimated creatinine clearance is 29 mL/min. Institutional protocol recommends vancomycin 1,000 mg IV q24h with trough monitoring before the 4th dose. Current order: 1,250 mg IV q24h.',
    options: ['Accept recommended dose', 'Keep ordered dose', 'Consult pharmacy'],
    accept: 'Continue',
  },
  formulary: {
    id: 'formulary',
    severity: 'low',
    relevant: false,
    kind: 'Formulary Notice',
    title: 'Preferred product substitution available',
    body: 'The selected product is formulary-preferred at this facility. No substitution is required. This notice is displayed for documentation purposes and does not require action beyond acknowledgement.',
    options: ['Acknowledged'],
    accept: 'Continue',
  },
  interaction: {
    id: 'interaction',
    severity: 'low',
    relevant: false,
    kind: 'Drug–Drug Interaction',
    title: 'Minor interaction — heparin / ACE inhibitor',
    body: 'Concurrent use may increase risk of hyperkalaemia. Severity: MINOR. Documentation: FAIR. Monitor serum potassium. No dose adjustment is generally required.',
    options: ['Will monitor', 'Not applicable'],
    accept: 'Continue',
  },
};

const SEV = {
  high:   { bar:'#DC2626', bg:'#FFF5F5', chip:'#FECACA', chipText:'#DC2626', label:'HIGH' },
  medium: { bar:'#D97706', bg:'#FEF9C3', chip:'#FEF3C7', chipText:'#92400E', label:'MEDIUM' },
  low:    { bar:'#6B7280', bg:'#F9FAFB', chip:'#F3F4F6', chipText:'#4B5563', label:'LOW' },
};

function AlertModal({ alert, onAccept, onCancel }) {
  const [reason, setReason] = React.useState('');
  const [reasonOpen, setReasonOpen] = React.useState(false);
  const [justification, setJustification] = React.useState('');
  const [choice, setChoice] = React.useState('');
  const s = SEV[alert.severity];

  const needsReason = alert.requiresReason;

  return (
    <div style={al.overlay}>
      <div style={{ ...al.modal, borderTop: `3px solid ${s.bar}` }}>
        <div style={{ ...al.head, background: s.bg }}>
          <span style={{ ...al.sevChip, background: s.chip, color: s.chipText }}>{s.label}</span>
          <span style={al.kind}>{alert.kind}</span>
          <span style={al.stamp}>Doe, John A · 4729-3841</span>
        </div>
        <div style={al.body}>
          <div style={al.title}>{alert.title}</div>
          <div style={al.text}>{alert.body}</div>

          {alert.options && (
            <div style={al.opts}>
              {alert.options.map((o, i) => (
                <label key={o} style={al.optRow} data-gc={`alert-opt-${i}`} onClick={() => setChoice(o)}>
                  <span style={{ ...al.radio, ...(choice === o ? al.radioOn : {}) }} />
                  <span style={al.optLabel}>{o}</span>
                </label>
              ))}
            </div>
          )}

          {needsReason && (
            <div style={al.reasonWrap}>
              <div style={al.fieldLabel}>Override reason <span style={al.req}>*</span></div>
              <div style={al.select} data-gc="alert-reason-trigger" onClick={() => setReasonOpen(o => !o)}>
                <span style={{ color: reason ? '#111827' : '#9CA3AF' }}>{reason || 'Select an override reason…'}</span>
                <span style={al.caret}>▾</span>
              </div>
              {reasonOpen && (
                <div style={al.dropdown}>
                  {alert.reasons.map((r, i) => (
                    <div key={r} style={al.dropItem} data-gc={`alert-reason-${i}`}
                      onClick={() => { setReason(r); setReasonOpen(false); }}>{r}</div>
                  ))}
                </div>
              )}
              <div style={{ ...al.fieldLabel, marginTop: 10 }}>Clinical justification <span style={al.req}>*</span></div>
              <textarea
                data-gc="alert-justification"
                style={al.textarea}
                value={justification}
                placeholder="Free-text justification is required and is retained in the permanent record."
                onChange={e => setJustification(e.target.value)}
                onClick={e => { if (!justification) setJustification('Renal function improving on diuresis; K+ normalised at 4.2. Restarting ACEi with close monitoring.'); }}
              />
            </div>
          )}
        </div>
        <div style={al.foot}>
          <span style={al.footNote}>This interaction is recorded and reportable.</span>
          <div style={{ flex: 1 }} />
          <button style={al.btnGhost} data-gc="alert-cancel" onClick={onCancel}>Cancel order</button>
          <button style={al.btnPrimary} data-gc="alert-accept" onClick={onAccept}>{alert.accept}</button>
        </div>
      </div>
    </div>
  );
}

function HardStopModal({ onReturn }) {
  return (
    <div style={al.overlay}>
      <div style={{ ...al.modal, width: 460, borderTop: '3px solid #DC2626' }}>
        <div style={{ ...al.head, background: '#FFF5F5' }}>
          <span style={{ ...al.sevChip, background: '#FECACA', color: '#DC2626' }}>HARD STOP</span>
          <span style={al.kind}>Required Documentation Missing</span>
        </div>
        <div style={al.body}>
          <div style={al.title}>Indication is required</div>
          <div style={al.text}>
            An indication must be recorded before this order can be signed. Regulatory
            documentation requirement — this field cannot be bypassed.
          </div>
          <div style={al.hardStopHint}>Field: <strong>Indication</strong> — Order Composer, below the visible area.</div>
        </div>
        <div style={al.foot}>
          <div style={{ flex: 1 }} />
          <button style={al.btnPrimary} data-gc="hardstop-return" onClick={onReturn}>Return to order</button>
        </div>
      </div>
    </div>
  );
}

function CosignModal({ onSign, onCancel }) {
  const [provider, setProvider] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const [attested, setAttested] = React.useState(false);
  const providers = [
    'Weaver, Margaret R, MD — Nephrology (Attending)',
    'Weaver, Margaret R, MD — Internal Medicine',
    'Weaver, M. R., MD [legacy directory entry]',
  ];
  return (
    <div style={al.overlay}>
      <div style={{ ...al.modal, width: 540, borderTop: '3px solid #0066CC' }}>
        <div style={{ ...al.head, background: '#EFF6FF' }}>
          <span style={{ ...al.sevChip, background: '#DBEAFE', color: '#1E40AF' }}>COSIGN</span>
          <span style={al.kind}>Supervising Provider Required</span>
        </div>
        <div style={al.body}>
          <div style={al.title}>Orders placed by a resident require attending cosignature</div>
          <div style={al.fieldLabel}>Supervising provider <span style={al.req}>*</span></div>
          <div style={al.select} data-gc="cosign-trigger" onClick={() => setOpen(o => !o)}>
            <span style={{ color: provider ? '#111827' : '#9CA3AF' }}>{provider || 'Search provider directory…'}</span>
            <span style={al.caret}>▾</span>
          </div>
          {open && (
            <div style={al.dropdown}>
              {providers.map((p, i) => (
                <div key={p} style={al.dropItem} data-gc={`cosign-provider-${i}`}
                  onClick={() => { setProvider(p); setOpen(false); }}>{p}</div>
              ))}
            </div>
          )}
          <label style={al.attestRow} data-gc="cosign-attest" onClick={() => setAttested(a => !a)}>
            <span style={{ ...al.checkbox, ...(attested ? al.checkboxOn : {}) }}>{attested ? '✓' : ''}</span>
            <span style={al.attestText}>
              I attest that I have personally reviewed the patient's record, that these orders
              reflect my clinical judgment, and that documentation supports the level of service billed.
            </span>
          </label>
        </div>
        <div style={al.foot}>
          <div style={{ flex: 1 }} />
          <button style={al.btnGhost} data-gc="cosign-cancel" onClick={onCancel}>Cancel</button>
          <button style={al.btnPrimary} data-gc="cosign-sign" onClick={onSign}>Sign Orders</button>
        </div>
      </div>
    </div>
  );
}

const al = {
  overlay: { position:'absolute', inset:0, background:'rgba(17,24,39,0.42)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:800, fontFamily:'"Segoe UI", system-ui, sans-serif' },
  modal: { width:560, background:'#fff', borderRadius:5, boxShadow:'0 16px 48px rgba(0,0,0,0.28)', overflow:'visible', position:'relative' },
  head: { display:'flex', alignItems:'center', gap:8, padding:'8px 12px', borderBottom:'1px solid #E5E7EB' },
  sevChip: { fontSize:9.5, fontWeight:800, letterSpacing:0.6, padding:'2px 6px', borderRadius:2 },
  kind: { fontSize:11, fontWeight:700, color:'#374151' },
  stamp: { marginLeft:'auto', fontSize:10, color:'#9CA3AF' },
  body: { padding:'14px 16px 16px', position:'relative' },
  title: { fontSize:14, fontWeight:700, color:'#111827', marginBottom:7, lineHeight:1.3 },
  text: { fontSize:11.5, color:'#4B5563', lineHeight:1.6 },
  opts: { marginTop:12, display:'flex', flexDirection:'column', gap:5 },
  optRow: { display:'flex', alignItems:'flex-start', gap:7, cursor:'pointer', padding:'3px 4px', borderRadius:2 },
  radio: { width:11, height:11, borderRadius:'50%', border:'1.5px solid #9CA3AF', flexShrink:0, marginTop:1 },
  radioOn: { border:'3.5px solid #0066CC' },
  optLabel: { fontSize:11.5, color:'#111827' },
  reasonWrap: { marginTop:13, position:'relative' },
  fieldLabel: { fontSize:11, fontWeight:700, color:'#4B5563', marginBottom:4 },
  req: { color:'#DC2626' },
  select: { border:'1px solid #9CA3AF', borderRadius:2, padding:'5px 8px', fontSize:11.5, display:'flex', alignItems:'center', cursor:'pointer', background:'#fff' },
  caret: { marginLeft:'auto', fontSize:9.5, color:'#6B7280' },
  dropdown: { position:'absolute', left:0, right:0, background:'#fff', border:'1px solid #9CA3AF', borderTop:'none', maxHeight:150, overflowY:'auto', zIndex:40, boxShadow:'0 4px 12px rgba(0,0,0,0.12)' },
  dropItem: { fontSize:11.5, padding:'6px 8px', cursor:'pointer', borderBottom:'1px solid #F3F4F6', color:'#111827' },
  textarea: { width:'100%', minHeight:52, border:'1px solid #9CA3AF', borderRadius:2, padding:'6px 8px', fontSize:11.5, fontFamily:'inherit', resize:'none', color:'#111827' },
  hardStopHint: { marginTop:11, background:'#FFF5F5', border:'1px solid #FECACA', borderRadius:3, padding:'7px 9px', fontSize:11, color:'#DC2626' },
  attestRow: { display:'flex', alignItems:'flex-start', gap:8, marginTop:14, cursor:'pointer' },
  checkbox: { width:13, height:13, border:'1.5px solid #6B7280', borderRadius:2, flexShrink:0, fontSize:11, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', marginTop:1 },
  checkboxOn: { background:'#0066CC', borderColor:'#0066CC' },
  attestText: { fontSize:11, color:'#4B5563', lineHeight:1.55 },
  foot: { display:'flex', alignItems:'center', gap:8, padding:'9px 12px', borderTop:'1px solid #E5E7EB', background:'#F9FAFB' },
  footNote: { fontSize:10, color:'#9CA3AF' },
  btnGhost: { fontSize:11.5, padding:'6px 12px', background:'#fff', border:'1px solid #CBD5E1', borderRadius:2, cursor:'pointer', color:'#4B5563' },
  btnPrimary: { fontSize:11.5, fontWeight:600, padding:'6px 14px', background:'#0066CC', border:'1px solid #0066CC', borderRadius:2, cursor:'pointer', color:'#fff' },
  btnDisabled: { background:'#CBD5E1', borderColor:'#CBD5E1', cursor:'not-allowed' },
};

Object.assign(window, { AlertModal, HardStopModal, CosignModal, ALERTS });
