// Rx Detail Drawer + Verification Station
const STATUS_TONE = { Paid: 'paid', Cash: 'cash', Pending: 'pending', Rejected: 'rejected' };

function AdjPanel({ rx }) {
  const a = rx.adj;
  const gp = a.copay + a.reimb - a.acq;
  const revenue = a.copay + a.reimb;
  const marginPct = revenue > 0 ? (gp / revenue) * 100 : 0;
  return (
    <div className="adj">
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 8 }}>
        <span style={{ fontSize: 14, fontWeight: 700, color: '#f3f1e7' }}>{rx.payer === 'Cash' ? 'Cash / HSA' : rx.payer}</span>
        <span className={'chip-status ' + (STATUS_TONE[a.status] || 'pending')} style={{ marginLeft: 'auto' }}>{a.status}</span>
      </div>
      <div className="row"><span>Patient copay</span><span className="mono">${a.copay.toFixed(2)}</span></div>
      <div className="row"><span>Payer reimbursement</span><span className="mono">${a.reimb.toFixed(2)}</span></div>
      <div className="row"><span>Acquisition cost</span><span className="mono">−${a.acq.toFixed(2)}</span></div>
      <div className={'gp' + (gp < 0 ? ' neg' : '')}>
        <span className="big-num">{gp < 0 ? '−' : ''}${Math.abs(gp).toFixed(2)}</span>
        <span style={{ fontSize: 12, color: '#aab3a2' }}>
          gross profit on this fill · <b style={{ color: gp < 0 ? '#e08770' : '#9fc4ad' }}>{marginPct.toFixed(1)}%</b> margin
          {a.status === 'Pending' ? ' (estimated)' : ''}
        </span>
      </div>
    </div>
  );
}

function ClinicalBlock({ rx, showToast }) {
  const { useState } = React;
  const [acked, setAcked] = useState(false);
  if (rx.interaction && !acked) {
    return (
      <div className="dur">
        <b>⚠ {rx.interaction}</b>
        <div className="acts">
          <button className="btn-sm dark" onClick={() => { setAcked(true); showToast('Interaction acknowledged — noted on Rx record.'); }}>Acknowledge</button>
          <button className="btn-sm" onClick={() => showToast('Flagged for pharmacist review — moved to exceptions.')}>Flag</button>
        </div>
      </div>
    );
  }
  return <div className="ok-line">✓ No interactions found · Allergies checked{rx.interaction ? ' · interaction acknowledged' : ''}</div>;
}

function RxDrawer({ rx, onClose, nav, showToast }) {
  return (
    <div>
      <div className="scrim" onClick={onClose}></div>
      <aside className="drawer">
        <div className="drawer-head">
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <span className="kicker">Rx {rx.rx}</span>
            <span className="storetag">{rx.store}</span>
            {rx.flag === 'compound' ? <span className="badge comp">Lab</span> : null}
            {rx.flag === 'cii' ? <span className="badge bad">C-II</span> : null}
            <button className="xclose" onClick={onClose}>✕</button>
          </div>
          <h3 style={{ marginTop: 6 }}>{rx.drug}</h3>
          <div style={{ display: 'flex', gap: 10, alignItems: 'baseline', marginTop: 6 }}>
            <button className="pt-link" onClick={() => nav.goPatient(routePatient(rx.patient))}>{rx.patient} →</button>
            <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>DOB {rx.dob}</span>
          </div>
        </div>

        <div className="drawer-sec">
          <div className="kv">
            <div><div className="k">Quantity</div><div className="v">{rx.qty}</div></div>
            <div><div className="k">Days supply</div><div className="v">{rx.ds}</div></div>
            <div><div className="k">Refills left</div><div className="v">{rx.refills}</div></div>
            <div><div className="k">Origin</div><div className="v" style={{ fontWeight: 500, fontSize: 12 }}>{rx.origin}</div></div>
          </div>
          <div style={{ marginTop: 12 }}>
            <div className="h" style={{ marginBottom: 4 }}>Directions</div>
            <div className="sig-line">“{rx.sig}”</div>
          </div>
          <div style={{ marginTop: 12, fontSize: 12.5, color: 'var(--ink-2)' }}>
            {rx.prescriber} · {rx.clinic}
          </div>
        </div>

        <div className="drawer-sec">
          <div className="h">Clinical review</div>
          <ClinicalBlock rx={rx} showToast={showToast}></ClinicalBlock>
        </div>

        <div className="drawer-sec">
          <div className="h">Adjudication</div>
          <AdjPanel rx={rx}></AdjPanel>
        </div>

        <div className="drawer-sec" style={{ borderBottom: 'none' }}>
          <div className="h">Activity</div>
          <div className="tl">
            {rx.timeline.map((t, i) => (
              <div className="t-row" key={i}>
                <span className="t-time">{t[0]}</span>
                <span>{t[1]}</span>
              </div>
            ))}
            {rx.note ? (
              <div className="t-row">
                <span className="t-time">note</span>
                <span style={{ color: 'var(--ink-2)', fontStyle: 'italic' }}>{rx.note}</span>
              </div>
            ) : null}
          </div>
        </div>
      </aside>
    </div>
  );
}

// ---- Verification Station ----------------------------------------------

function ScannedRx({ rx }) {
  return (
    <div className="paper">
      <div className="clinic">{rx.clinic.split(',')[0]}</div>
      <div className="addr">{rx.clinic.split(',')[1] ? rx.clinic.split(',')[1].trim() + ', WA' : 'Skagit County, WA'} · (360) 555-0188 · Fax (360) 555-0189</div>
      <hr></hr>
      <div className="field"><span className="lab">Patient</span><span style={{ fontWeight: 600 }}>{rx.patient}</span></div>
      <div className="field"><span className="lab">DOB</span><span>{rx.dob}</span></div>
      <div className="field"><span className="lab">Date</span><span>06/11/2026</span></div>
      <hr></hr>
      <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
        <span className="rxsym">℞</span>
        <div className="hand">
          {rx.drug}<br></br>
          Disp: {rx.qty} · Refills: {rx.refills}<br></br>
          Sig: {rx.sig}
        </div>
      </div>
      <div className="signature">{rx.prescriber.replace('Dr. ', '').replace(', DVM', '')}</div>
      <div className="sigline">
        <span>Prescriber signature</span>
        <span>NPI 1396 558 214 · DEA BO5573821</span>
      </div>
    </div>
  );
}

function VerificationStation({ rx, onVerify, onClose, showToast }) {
  const rows = [
    ['Patient', rx.patient + ' · DOB ' + rx.dob],
    ['Drug', rx.drug],
    ['Quantity', rx.qty],
    ['Days supply', String(rx.ds)],
    ['Sig', rx.sig],
    ['Refills', String(rx.refills)],
    ['Prescriber', rx.prescriber],
    ['Payer', rx.payer],
  ];
  return (
    <div>
      <div className="scrim" onClick={onClose}></div>
      <div className="station">
        <div className="station-head">
          <span className="kicker">Verification · Rx {rx.rx}</span>
          {rx.flag === 'compound' ? <span className="badge comp">Lab</span> : null}
          {rx.flag === 'cii' ? <span className="badge bad">C-II</span> : null}
          <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>Source document vs. entered data</span>
          <button className="xclose" onClick={onClose}>✕</button>
        </div>
        <div className="station-body">
          <div className="station-left">
            <ScannedRx rx={rx}></ScannedRx>
          </div>
          <div className="station-right">
            <div className="h kicker" style={{ marginBottom: 6 }}>Entered data</div>
            {rows.map((r, i) => (
              <div className="vrow" key={i}>
                <span className="lab">{r[0]}</span>
                <span className="val">{r[1]}<span className="tick">✓</span></span>
              </div>
            ))}
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 10 }}>
              DUR clear · allergies checked · {rx.flag === 'compound' ? 'lot + BUD recorded' : 'NDC scan matched'}
            </div>
            <div className="station-actions">
              <button className="btn-primary" onClick={() => onVerify(rx.rx)}>Verify — send to Filling</button>
              <button className="btn-ghost" onClick={() => { showToast('Rx ' + rx.rx + ' flagged for review.'); onClose(); }}>Flag for review</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RxDrawer, VerificationStation, AdjPanel });
