// Screen: Fill Queue — board + rejections workbench + refills due
function FillQueue({ scope, tab, setTab, nav, cards, setCards }) {
  const { useState } = React;
  const [openRx, setOpenRx] = useState(null);
  const [wcQuery, setWcQuery] = useState('');
  const [reworked, setReworked] = useState({});
  const [toast, showToast] = useToast();

  const visible = cards.filter(r => scope === 'all' || r.store.toLowerCase() === scope);
  const open = cards.find(c => c.rx === openRx);

  const verify = (rxId) => {
    setCards(cs => cs.map(c => c.rx === rxId ? { ...c, stage: 3, wait: 1, timeline: [...c.timeline.slice(0, -1), ['7:58a', 'Verified by C. Schaffner, PharmD'], ['—', 'In filling']] } : c));
    setOpenRx(null);
    showToast('Rx ' + rxId + ' verified — sent to Filling.');
  };

  // Will-call matches (Ready column only)
  const q = wcQuery.trim().toLowerCase();
  const wcHits = q.length > 1 ? visible.filter(c => c.stage === 4 && c.patient.toLowerCase().includes(q)) : [];
  const wcBins = [...new Set(wcHits.map(h => h.bin))].join(', ');
  const wcDue = wcHits.reduce((a, h) => a + (h.copayDue || 0), 0);

  const flagBadge = (flag) => {
    if (flag === 'compound') return <span className="badge comp">Lab</span>;
    if (flag === 'cii') return <span className="badge bad">C-II</span>;
    if (flag === 'neg-margin') return <span className="badge warn">Margin</span>;
    if (flag === 'dur') return <span className="badge warn">Interaction</span>;
    return null;
  };

  const openRejections = REJECTIONS.filter(r => !reworked[r.id]).length;

  return (
    <div className="content" data-screen-label="Fill Queue">

      {/* Tabs + will-call search */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div className="qtabs">
          <button className={tab === 'queue' ? 'on' : ''} onClick={() => setTab('queue')}>Queue</button>
          <button className={tab === 'rejections' ? 'on' : ''} onClick={() => setTab('rejections')}>
            Rejections<span className="cnt">{openRejections}</span>
          </button>
          <button className={tab === 'refills' ? 'on' : ''} onClick={() => setTab('refills')}>
            Refills due<span className="cnt">{REFILLS_DUE.length}</span>
          </button>
        </div>
        {tab === 'queue' ? (
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10 }}>
            {wcHits.length > 0 ? (
              <span className="wc-chip">
                {wcHits.length} item{wcHits.length > 1 ? 's' : ''} · Bin {wcBins} · Copay due ${wcDue.toFixed(2)}
              </span>
            ) : null}
            <div className="inv-search" style={{ flex: '0 0 250px' }}>
              <span style={{ color: 'var(--ink-3)' }}>⌕</span>
              <input placeholder="Will-call: patient name…" value={wcQuery} onChange={e => setWcQuery(e.target.value)}></input>
            </div>
          </div>
        ) : null}
      </div>

      {/* ---- Queue board ---- */}
      {tab === 'queue' ? (
        <div className="queue-board">
          {QUEUE_STAGES.map((stage, si) => {
            const colCards = visible.filter(r => r.stage === si);
            return (
              <div key={stage}>
                <div className="queue-col-head">
                  <span className="n">{'0' + (si + 1)}</span>
                  <h4>{stage}</h4>
                  <span className="n" style={{ marginLeft: 'auto' }}>{colCards.length}</span>
                </div>
                <div className="queue-col">
                  {colCards.map(r => (
                    <div key={r.rx}
                      className={'card rx-card' + (openRx === r.rx ? ' sel' : '') + (wcHits.some(h => h.rx === r.rx) ? ' hit' : '')}
                      onClick={() => setOpenRx(r.rx)}>
                      <div style={{ display: 'flex', alignItems: 'baseline' }}>
                        <span className="rxno">{r.rx}</span>
                        <span className={'wait' + (r.wait >= 15 ? ' slow' : '')}>
                          {r.stage === 4 ? (r.bin || 'ready') : r.wait + ' min'}
                        </span>
                      </div>
                      <div className="drug">{r.drug}</div>
                      <div className="pt">{r.patient} · {r.payer}</div>
                      <div className="foot">
                        <span className="storetag">{r.store}</span>
                        {flagBadge(r.flag)}
                      </div>
                    </div>
                  ))}
                  {colCards.length === 0 ? (
                    <div style={{
                      border: '1px dashed var(--line)', borderRadius: 9, padding: '18px 0',
                      textAlign: 'center', color: 'var(--ink-3)', fontSize: 12,
                    }}>Clear</div>
                  ) : null}
                </div>
              </div>
            );
          })}
        </div>
      ) : null}

      {/* ---- Rejections workbench ---- */}
      {tab === 'rejections' ? (
        <div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', marginBottom: 10 }}>
            12 claims rejected this week · {openRejections} unresolved below · 4 are Premera prior-auth holds on compounds.
          </div>
          <div className="card" style={{ overflow: 'hidden' }}>
            <table className="data">
              <thead>
                <tr><th>Patient</th><th>Claim</th><th>Payer</th><th>Reject code</th><th>Suggested fix</th><th className="num">Value</th><th></th></tr>
              </thead>
              <tbody>
                {REJECTIONS.map(r => (
                  <tr key={r.id} className={reworked[r.id] ? 'dimrow' : ''}>
                    <td>
                      <button className="pt-link" style={{ fontSize: 13 }} onClick={() => nav.goPatient(routePatient(r.patient))}>{r.patient}</button>
                    </td>
                    <td style={{ fontWeight: 600 }}>{r.drug}</td>
                    <td>{r.payer}</td>
                    <td><span className="code-chip">{r.code} · {r.meaning}</span></td>
                    <td style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{r.fix}</td>
                    <td className="num mono">{r.value}</td>
                    <td className="num">
                      {reworked[r.id]
                        ? <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Reworked</span>
                        : <button className="btn-sm" onClick={() => { setReworked(s => ({ ...s, [r.id]: true })); showToast('Returned to Data Entry.'); }}>Rework</button>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}

      {/* ---- Refills due ---- */}
      {tab === 'refills' ? (
        <div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', marginBottom: 10 }}>
            10 refills due in the next window · 2 awaiting prescriber renewal.
          </div>
          <div className="card" style={{ overflow: 'hidden' }}>
            <table className="data">
              <thead>
                <tr><th>Patient</th><th>Medication</th><th>Last filled</th><th>Due</th><th>Auto-refill</th><th>Status</th><th></th></tr>
              </thead>
              <tbody>
                {REFILLS_DUE.map((r, i) => (
                  <tr key={i}>
                    <td>
                      <button className="pt-link" style={{ fontSize: 13 }} onClick={() => nav.goPatient(routePatient(r.patient))}>{r.patient}</button>
                    </td>
                    <td style={{ fontWeight: 600 }}>{r.drug}</td>
                    <td className="mono">{r.last}</td>
                    <td className="mono" style={r.due === 'Today' ? { color: 'var(--bad)', fontWeight: 700 } : null}>{r.due}</td>
                    <td>{r.auto ? <span className="badge ok">Auto</span> : <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>—</span>}</td>
                    <td style={{ fontSize: 12.5 }}>
                      {r.status === 'renewal'
                        ? <span className="badge warn">Renewal request sent to prescriber</span>
                        : <span style={{ color: 'var(--ink-2)' }}>Due</span>}
                    </td>
                    <td className="num">
                      {r.status !== 'renewal'
                        ? <button className="btn-sm" onClick={() => showToast(r.drug + ' queued for ' + r.patient + '.')}>Queue fill</button>
                        : null}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}

      {/* Drawer / Verification station */}
      {open && open.stage === 2 ? (
        <VerificationStation rx={open} onVerify={verify} onClose={() => setOpenRx(null)} showToast={showToast}></VerificationStation>
      ) : null}
      {open && open.stage !== 2 ? (
        <RxDrawer rx={open} onClose={() => setOpenRx(null)} nav={nav} showToast={showToast}></RxDrawer>
      ) : null}

      <Toast msg={toast}></Toast>
    </div>
  );
}

Object.assign(window, { FillQueue });
