// Screen: Intake — incoming prescriptions + New Rx entry (eRx / fax / phone / manual)

// ---- Source documents (left pane of split entry forms) ----------------

function FaxDoc({ doc }) {
  return (
    <div className="paper">
      <div className="fax-head">{doc.faxHead}</div>
      <div className="clinic">{doc.clinic}</div>
      <div className="addr">{doc.addr}</div>
      <hr></hr>
      <div className="field"><span className="lab">Patient</span><span style={{ fontWeight: 600 }}>{doc.patient}</span></div>
      <div className="field"><span className="lab">DOB</span><span>{doc.dob}</span></div>
      <div className="field"><span className="lab">Date</span><span>{doc.date}</span></div>
      <hr></hr>
      <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
        <span className="rxsym">℞</span>
        <div className="hand">
          {doc.drug}<br></br>
          {doc.disp}<br></br>
          {doc.sig}
        </div>
      </div>
      <div className="signature">{doc.signature}</div>
      <div className="sigline">
        <span>Prescriber signature</span>
        <span>{doc.npi}</span>
      </div>
    </div>
  );
}

function CallRecord({ doc }) {
  return (
    <div className="callrec">
      <div className="kicker" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span>{doc.line}</span>
        <span style={{ color: 'var(--ink-3)' }}>{doc.time}</span>
      </div>
      <div className="cr-grid">
        <div className="cr-k">Inbound from</div><div className="cr-v">{doc.from}</div>
        <div className="cr-k">Caller</div><div className="cr-v">{doc.caller}</div>
        <div className="cr-k">Taken by</div><div className="cr-v">{doc.pharmacist}</div>
        <div className="cr-k">Order</div><div className="cr-v">{doc.order}</div>
      </div>
      <div className="cr-readback">{doc.readback}</div>
      <div className="cr-foot">{doc.foot}</div>
    </div>
  );
}

// ---- Config-driven entry form (eRx / fax split / verbal split) --------

function EntryForm({ config, onClose, onSent, nav, showToast }) {
  const { useState } = React;
  const [phase, setPhase] = useState('form'); // form | processing | paid
  const [payer, setPayer] = useState(config.billing.default);

  const submit = () => {
    if (phase !== 'form') return;
    setPhase('processing');
    window.setTimeout(() => setPhase('paid'), 1000);
  };

  const p = config.paid;
  const money = (n) => '$' + n.toFixed(2);

  const formBody = (
    <React.Fragment>
      {/* Patient match / transcription */}
      <div className="entry-sec">
        <div className="match">
          <span className="check">✓ {config.match.profile ? 'Matched existing patient' : 'Patient on file'}</span>
          <span style={{ fontWeight: 700 }}>{config.match.name}</span>
          <span style={{ color: 'var(--ink-2)' }}>{config.match.meta}</span>
          {config.match.profile ? (
            <React.Fragment>
              <button className="pt-link" style={{ fontSize: 13 }} onClick={() => nav.goPatient(config.match.profile)}>View profile →</button>
              <button className="quiet-link" style={{ marginLeft: 'auto' }}
                onClick={() => showToast('Demo supports the matched patient.')}>Not her? Search patients</button>
            </React.Fragment>
          ) : null}
        </div>
        {config.transcript ? <div className="xnote" style={{ marginTop: 10 }}>{config.transcript}</div> : null}
      </div>

      {/* Prescriber + drug + sig */}
      <div className="entry-sec">
        <div className="field-row">
          <span className="flab">Prescriber</span>
          <div>
            <span style={{ fontWeight: 600 }}>{config.prescriber.name}</span>
            <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}> · {config.prescriber.clinic}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)', marginLeft: 8 }}>{config.prescriber.npi}</span>
          </div>
        </div>
        <div className="field-row">
          <span className="flab">Drug</span>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <div className="inp" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ color: 'var(--ink-3)' }}>⌕</span>
              <span style={{ fontWeight: 600 }}>{config.drug.name}</span>
              <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{config.drug.mfr}</span>
            </div>
          </div>
        </div>
        <div className="field-row">
          <span className="flab">Sig</span>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <span className="sigcode">{config.sig.code}</span>
            <span style={{ color: 'var(--ink-3)' }}>→</span>
            <span className="sig-line" style={{ fontSize: 15 }}>“{config.sig.text}”</span>
          </div>
        </div>
        <div className="field-row">
          <span className="flab">Dispense</span>
          <div style={{ display: 'flex', gap: 10 }}>
            <input className="inp" style={{ width: 90 }} defaultValue={config.dispense.qty} aria-label="Quantity"></input>
            <input className="inp" style={{ width: 110 }} defaultValue={config.dispense.days} aria-label="Days supply"></input>
            <input className="inp" style={{ width: 100 }} defaultValue={config.dispense.refills} aria-label="Refills"></input>
          </div>
        </div>
      </div>

      {/* Insurance */}
      <div className="entry-sec">
        <div className="field-row">
          <span className="flab">Billing</span>
          <div className="ins-radio">
            <button className={'ins-card' + (payer === config.billing.planId ? ' on' : '')} onClick={() => setPayer(config.billing.planId)}>
              <div className="plan">{payer === config.billing.planId ? '● ' : '○ '}{config.billing.planName}</div>
              <div className="det">{config.billing.planDet}</div>
            </button>
            <button className={'ins-card' + (payer === 'cash' ? ' on' : '')} onClick={() => setPayer('cash')}>
              <div className="plan">{payer === 'cash' ? '● ' : '○ '}Cash</div>
              <div className="det">{config.billing.cash}</div>
            </button>
          </div>
        </div>
        <div className="field-row">
          <span className="flab">Clinical</span>
          <span className="clin-strip">{config.clinical}</span>
        </div>
      </div>

      {/* Submit / result */}
      <div className="entry-sec" style={{ borderBottom: 'none' }}>
        {phase === 'paid' ? (
          <div className="paid-panel">
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span className="chip-status paid">PAID</span>
              <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>{p.payerLabel} · response in 0.8 s</span>
            </div>
            <div className="rows">
              <div><div className="v">{money(p.copay)}</div><div className="k">Copay</div></div>
              <div><div className="v">{money(p.plan)}</div><div className="k">Plan paid</div></div>
              <div><div className="v">{money(p.total)}</div><div className="k">Total</div></div>
              <div><div className="v">{money(p.acq)}</div><div className="k">Acquisition</div></div>
              <div><div className="v" style={{ color: 'var(--moss)' }}>{money(p.gp)}</div><div className="k">Gross profit · {p.margin}</div></div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 14 }}>
              <button className="btn-primary" style={{ flex: '0 0 auto', padding: '11px 26px' }} onClick={onSent}>
                Send to Fill Queue
              </button>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 14 }}>
            {phase === 'processing' ? (
              <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>{p.processing}</span>
            ) : null}
            <button className="btn-primary" style={{ flex: '0 0 auto', padding: '11px 26px', opacity: phase === 'processing' ? 0.6 : 1 }}
              onClick={submit} disabled={phase === 'processing'}>
              {phase === 'processing' ? 'Submitting…' : 'Submit Claim'}
            </button>
          </div>
        )}
      </div>
    </React.Fragment>
  );

  return (
    <div>
      <div className="scrim" onClick={phase === 'processing' ? undefined : onClose}></div>
      <div className="station" style={{ width: config.split ? 'min(1180px, 96vw)' : 'min(880px, 94vw)' }}>
        <div className="station-head">
          <span className="kicker">{config.kicker}</span>
          <span className={'badge ' + (config.badge.indexOf('Compound') === 0 ? 'comp' : 'neutral')}>{config.badge}</span>
          <button className="xclose" onClick={onClose}>✕</button>
        </div>
        {config.split ? (
          <div className="station-body">
            <div className="station-left">
              {config.split === 'fax' ? <FaxDoc doc={config.doc}></FaxDoc> : <CallRecord doc={config.doc}></CallRecord>}
            </div>
            <div style={{ overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>{formBody}</div>
          </div>
        ) : (
          <div style={{ overflowY: 'auto' }}>{formBody}</div>
        )}
      </div>
    </div>
  );
}

// ---- Phone IVR refill review (compact modal) --------------------------

function PhoneModal({ data, onClose, onQueue, nav }) {
  return (
    <div>
      <div className="scrim" onClick={onClose}></div>
      <div className="station" style={{ width: 'min(560px, 94vw)' }}>
        <div className="station-head">
          <span className="kicker">Refill request · Phone IVR</span>
          <span className="badge neutral">Refill · no new Rx</span>
          <button className="xclose" onClick={onClose}>✕</button>
        </div>
        <div style={{ overflowY: 'auto' }}>
          <div className="entry-sec">
            <div className="h" style={{ marginBottom: 6 }}>Call record</div>
            <div className="tl">
              {data.timeline.map((t, i) => (
                <div className="t-row" key={i}><span className="t-time">{t[0]}</span><span>{t[1]}</span></div>
              ))}
            </div>
          </div>
          <div className="entry-sec">
            <div className="match">
              <span className="check">✓ Matched patient</span>
              <span style={{ fontWeight: 700 }}>{data.patient}</span>
              <button className="pt-link" style={{ fontSize: 13, marginLeft: 'auto' }} onClick={() => nav.goPatient(data.profile)}>View profile →</button>
            </div>
            <div className="kv" style={{ marginTop: 12 }}>
              {data.facts.map((f, i) => (
                <div key={i}><div className="k">{f[0]}</div><div className="v" style={{ fontSize: 14 }}>{f[1]}</div></div>
              ))}
            </div>
            <div style={{ marginTop: 12 }}><span className="chip-status paid">Eligible today</span></div>
          </div>
          <div className="entry-sec" style={{ borderBottom: 'none', display: 'flex', justifyContent: 'flex-end' }}>
            <button className="btn-primary" style={{ flex: '0 0 auto', padding: '11px 26px' }} onClick={onQueue}>Queue refill</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Intake screen ----------------------------------------------------

function Intake({ nav, entered, setEntered }) {
  const { useState } = React;
  const [openId, setOpenId] = useState(null);
  const [phoneOpen, setPhoneOpen] = useState(false);
  const [manualOpen, setManualOpen] = useState(false);
  const [toast, showToast] = useToast();
  const rows = INTAKE_ITEMS.filter(i => !entered[i.id]);

  const handleRow = (item) => {
    if (item.id === 'in5') return setPhoneOpen(true);
    if (ENTRY_CONFIGS[item.id]) return setOpenId(item.id);
    showToast('Demo supports the highlighted prescriptions.');
  };

  const onSent = () => {
    const cfg = ENTRY_CONFIGS[openId];
    nav.addRx(cfg.record);
    setEntered(e => ({ ...e, [openId]: true }));
    setOpenId(null);
    showToast(cfg.toast);
  };

  const onQueueRefill = () => {
    nav.addRx(PHONE_REFILL.record);
    setEntered(e => ({ ...e, in5: true }));
    setPhoneOpen(false);
    showToast(PHONE_REFILL.toast);
  };

  const onManualSent = (record, msg) => {
    nav.addRx(record);
    setManualOpen(false);
    showToast(msg);
  };

  return (
    <div className="content" data-screen-label="Intake">
      <div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <SectionHead title={'Incoming · ' + rows.length + ' awaiting entry'} action="Fill queue →" onAction={() => nav.go('queue')}></SectionHead>
          </div>
          <button className="btn-primary" style={{ flex: '0 0 auto', padding: '9px 18px' }} onClick={() => setManualOpen(true)}>+ New Rx</button>
        </div>
        <div className="card" style={{ marginTop: 10, overflow: 'hidden' }}>
          {rows.map(item => (
            <div key={item.id} className={'intake-row' + (item.hero ? ' hero' : '')}>
              <div className="intake-kind">
                {item.kind}
                <span style={{ display: 'block', marginTop: 2 }}>{item.time}</span>
              </div>
              {item.fax ? (
                <div className="fax-thumb"><i></i><i></i><i></i><i></i><i></i></div>
              ) : null}
              <div className="intake-main">
                <div className="drug">{item.drug}</div>
                <div className="who">{item.patient} · {item.prescriber}</div>
              </div>
              <span className="storetag">{item.store}</span>
              <button className={item.hero ? 'btn-sm dark' : 'btn-sm'} onClick={() => handleRow(item)}>
                {item.id === 'in5' ? 'Review' : 'Enter Rx'}
              </button>
            </div>
          ))}
          {rows.length === 0 ? (
            <div style={{ padding: 28, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>
              Intake clear — nothing waiting.
            </div>
          ) : null}
        </div>
      </div>

      <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>
        eRx, fax, and refill calls flow in on their own — patient matched, prescriber verified, sig codes expanded. Entry is review, not retyping. Use <b>+ New Rx</b> for a verbal order phoned straight to the pharmacist.
      </div>

      {openId ? (
        <EntryForm config={ENTRY_CONFIGS[openId]} onClose={() => setOpenId(null)} onSent={onSent} nav={nav} showToast={showToast}></EntryForm>
      ) : null}
      {phoneOpen ? (
        <PhoneModal data={PHONE_REFILL} onClose={() => setPhoneOpen(false)} onQueue={onQueueRefill} nav={nav}></PhoneModal>
      ) : null}
      {manualOpen ? (
        <ManualEntryForm onClose={() => setManualOpen(false)} onSent={onManualSent} nav={nav} showToast={showToast}></ManualEntryForm>
      ) : null}
      <Toast msg={toast}></Toast>
    </div>
  );
}

Object.assign(window, { Intake, EntryForm, FaxDoc, CallRecord, PhoneModal });
