/* global React, Icon, MOUNJARO, WEGOVY, PATIENTS_SEED, ORDERS_SEED, fmtMoney, initials, calcAge, productById, formatDate, StatusBadge */
const { useState: uS4, useRef: uR4, useEffect: uE4 } = React;

// ===== STEP A: BASKET (browse + add to basket, no patient yet) =====
function BasketScreen({ basket, setBasket, setRoute }) {
  const [productTab, setProductTab] = uS4("mounjaro");
  const products = productTab === "mounjaro" ? MOUNJARO : WEGOVY;

  const updateBasket = (pid, delta) => {
    setBasket(prev => {
      const found = prev.find(b => b.pid === pid);
      if (!found && delta > 0) return [...prev, { pid, qty: 1 }];
      if (!found) return prev;
      const newQty = found.qty + delta;
      if (newQty <= 0) return prev.filter(b => b.pid !== pid);
      return prev.map(b => b.pid === pid ? { ...b, qty: newQty } : b);
    });
  };

  const subtotal = basket.reduce((s, b) => s + (productById(b.pid)?.price || 0) * b.qty, 0);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Step 1 of 5 · Basket</div>
          <h1 className="page-title">Add treatments to your basket</h1>
          <p className="page-sub">Pick products and quantities first — you'll allocate them to one or more patients in the next step.</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost" onClick={() => setRoute("dashboard")}>Cancel</button>
        </div>
      </div>

      <div className="stepper">
        <div className="step active"><div className="step-num">1</div>Basket</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">2</div>Allocate</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">3</div>Declare</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">4</div>Pay</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">5</div>Sign</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 }}>
        <div className="card">
          <div className="product-tabs">
            <button className={"product-tab" + (productTab === "mounjaro" ? " active" : "")} onClick={() => setProductTab("mounjaro")}>Mounjaro · Tirzepatide</button>
            <button className={"product-tab" + (productTab === "wegovy" ? " active" : "")} onClick={() => setProductTab("wegovy")}>Wegovy · Semaglutide</button>
          </div>
          <div className="strength-grid">
            {products.map(p => {
              const inB = basket.find(b => b.pid === p.id);
              return (
                <div key={p.id} className={"strength-card" + (inB ? " selected" : "") + (p.stock === "out" ? " disabled" : "")} onClick={() => p.stock !== "out" && updateBasket(p.id, inB ? 0 : 1)}>
                  <div className={"strength-stock " + ("stock-" + p.stock)}>{p.stock === "in" ? "In stock" : p.stock === "low" ? "Low stock" : "Out of stock"}</div>
                  <div className="strength-img">
                    {p.img ? <img src={p.img} alt={p.strength} /> : <div className="placeholder" style={{ width: "100%", height: "100%" }}>{p.strength}</div>}
                  </div>
                  <div>
                    <div className="strength-name">{p.strength}</div>
                    <div className="strength-meta">{p.name} · 4 doses {p.line === "starter" ? "· starter" : ""}</div>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 4 }}>
                    <div className="strength-price tnum">{fmtMoney(p.price)}</div>
                    {inB ? (
                      <div className="qty" onClick={(e) => e.stopPropagation()}>
                        <button className="qty-btn" onClick={() => updateBasket(p.id, -1)}>−</button>
                        <div className="qty-val tnum">{inB.qty}</div>
                        <button className="qty-btn" onClick={() => updateBasket(p.id, 1)}>+</button>
                      </div>
                    ) : (
                      <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); if (p.stock !== "out") updateBasket(p.id, 1); }} disabled={p.stock === "out"}>Add</button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="card" style={{ position: "sticky", top: 88, alignSelf: "start" }}>
          <div className="section-h"><h2>Basket</h2><span className="badge badge-draft">{basket.reduce((s, b) => s + b.qty, 0)} items</span></div>
          {basket.length === 0 ? (
            <div style={{ textAlign: "center", padding: "30px 0", color: "var(--ink-4)", fontSize: 13 }}>
              Empty basket.<br /><span style={{ fontSize: 11 }}>Pick a product to begin.</span>
            </div>
          ) : (
            <>
              {basket.map(b => {
                const p = productById(b.pid);
                return (
                  <div key={b.pid} className="order-line">
                    <div className="order-line-img">{p.img ? <img src={p.img} alt={p.strength} /> : <div style={{ fontSize: 9 }}>{p.strength}</div>}</div>
                    <div className="order-line-body">
                      <div className="order-line-title">{p.name} {p.strength}</div>
                      <div className="order-line-sub">qty {b.qty} · {fmtMoney(p.price)} ea</div>
                    </div>
                    <div className="order-line-price tnum">{fmtMoney(p.price * b.qty)}</div>
                  </div>
                );
              })}
              <div className="divider" />
              <div className="summary-line total"><span>Subtotal</span><span className="v tnum">{fmtMoney(subtotal)}</span></div>
              <button className="btn btn-accent btn-lg" style={{ width: "100%", justifyContent: "center", marginTop: 14 }} onClick={() => setRoute("allocate")}>
                Continue · allocate to patients <Icon.ChevronR />
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ===== STEP B: ALLOCATE basket items to one or more patients =====
function AllocateScreen({ basket, setBasket, allocations, setAllocations, patients, setRoute, addPatient }) {
  // allocations: [{ patientId | newPatient, items: [{pid, qty}] }]
  const [showAddPatient, setShowAddPatient] = uS4(false);

  // Compute remaining unallocated for each item
  const totalAllocated = (pid) => allocations.reduce((s, a) => s + (a.items.find(i => i.pid === pid)?.qty || 0), 0);
  const unallocated = basket.map(b => ({ pid: b.pid, remaining: b.qty - totalAllocated(b.pid) }));
  const totalRemaining = unallocated.reduce((s, u) => s + u.remaining, 0);

  // Validate that every allocated patient has BMI ≥ 27
  const allocPatients = allocations.map(a => patients.find(p => p.id === a.patientId)).filter(Boolean);
  const bmiBlockers = allocPatients.filter(p => !p.bmi || p.bmi < 27);
  const allItemsAssigned = allocations.every(a => a.items.length > 0);

  const canProceed = totalRemaining === 0 && allocations.length > 0 && bmiBlockers.length === 0 && allItemsAssigned;

  const addAllocation = (patientId) => {
    if (allocations.find(a => a.patientId === patientId)) return;
    setAllocations([...allocations, { patientId, items: [] }]);
  };
  const removeAllocation = (idx) => {
    setAllocations(allocations.filter((_, i) => i !== idx));
  };
  const updateAllocItem = (idx, pid, delta) => {
    const max = unallocated.find(u => u.pid === pid).remaining + (allocations[idx].items.find(i => i.pid === pid)?.qty || 0);
    setAllocations(allocations.map((a, i) => {
      if (i !== idx) return a;
      const found = a.items.find(it => it.pid === pid);
      if (!found) {
        if (delta <= 0) return a;
        return { ...a, items: [...a.items, { pid, qty: 1 }] };
      }
      const newQty = Math.max(0, Math.min(max, found.qty + delta));
      const items = newQty === 0 ? a.items.filter(it => it.pid !== pid) : a.items.map(it => it.pid === pid ? { ...it, qty: newQty } : it);
      return { ...a, items };
    }));
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Step 2 of 5 · Allocate</div>
          <h1 className="page-title">Assign items to patients</h1>
          <p className="page-sub">Allocate every basket item to a patient. You can split items across multiple prescriptions.</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost" onClick={() => setRoute("basket")}>← Back to basket</button>
        </div>
      </div>

      <div className="stepper">
        <div className="step done"><div className="step-num"><Icon.Check /></div>Basket</div>
        <div className="step-divider" />
        <div className="step active"><div className="step-num">2</div>Allocate</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">3</div>Declare</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">4</div>Pay</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">5</div>Sign</div>
      </div>

      {/* Unallocated items strip */}
      <div className="card" style={{ padding: "16px 20px", marginBottom: 16, background: totalRemaining === 0 ? "var(--green-soft)" : "var(--gold-soft)", borderColor: totalRemaining === 0 ? "var(--green)" : "var(--gold)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ width: 32, height: 32, borderRadius: "50%", background: "var(--paper)", display: "grid", placeItems: "center", color: totalRemaining === 0 ? "var(--green)" : "var(--gold)" }}>
            {totalRemaining === 0 ? <Icon.Check /> : <span style={{ fontWeight: 700, fontSize: 14 }} className="tnum">{totalRemaining}</span>}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 14, color: totalRemaining === 0 ? "var(--green)" : "var(--gold)" }}>
              {totalRemaining === 0 ? "All items allocated" : `${totalRemaining} item${totalRemaining > 1 ? "s" : ""} unallocated`}
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>
              {unallocated.filter(u => u.remaining > 0).map(u => `${productById(u.pid).strength} × ${u.remaining}`).join(" · ") || "Ready to proceed to payment."}
            </div>
          </div>
        </div>
      </div>

      {/* Allocations */}
      {allocations.map((alloc, idx) => {
        const patient = alloc.patientId === "_new_" ? alloc.newPatient : patients.find(p => p.id === alloc.patientId);
        const allocTotal = alloc.items.reduce((s, it) => s + productById(it.pid).price * it.qty, 0);
        return (
          <div key={idx} className="card" style={{ marginBottom: 12, padding: 0 }}>
            <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
              <div className="patient-avatar" style={{ width: 38, height: 38 }}>{patient ? initials(patient.first || "?", patient.last || "?") : "?"}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>Prescription {idx + 1} · {patient ? `${patient.first} ${patient.last}` : "Unknown"}</div>
                <div style={{ fontSize: 11, color: "var(--ink-4)" }}>
                  {patient && patient.dob ? `DOB ${formatDate(patient.dob)} · ` : ""}
                  {patient && patient.bmi ? `BMI ${typeof patient.bmi === "number" ? patient.bmi.toFixed(1) : patient.bmi}` : ""}
                </div>
              </div>
              <div className="tnum" style={{ fontFamily: "'Newsreader', serif", fontSize: 22, letterSpacing: "-0.02em" }}>{fmtMoney(allocTotal)}</div>
              <button className="btn btn-ghost btn-sm" onClick={() => removeAllocation(idx)}>Remove</button>
            </div>
            <div style={{ padding: "12px 20px" }}>
              {basket.map(b => {
                const p = productById(b.pid);
                const inAlloc = alloc.items.find(it => it.pid === b.pid);
                const remaining = unallocated.find(u => u.pid === b.pid).remaining;
                const max = (inAlloc?.qty || 0) + remaining;
                return (
                  <div key={b.pid} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--line)" }}>
                    <div className="order-line-img" style={{ width: 44, height: 44 }}>
                      {p.img ? <img src={p.img} alt={p.strength} /> : <div style={{ fontSize: 9 }}>{p.strength}</div>}
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 500, fontSize: 13 }}>{p.name} {p.strength}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-4)" }}>{fmtMoney(p.price)} each · {b.qty} in basket · {remaining} unallocated</div>
                    </div>
                    <div className="qty">
                      <button className="qty-btn" onClick={() => updateAllocItem(idx, b.pid, -1)} disabled={!inAlloc}>−</button>
                      <div className="qty-val tnum">{inAlloc?.qty || 0}</div>
                      <button className="qty-btn" onClick={() => updateAllocItem(idx, b.pid, 1)} disabled={max === (inAlloc?.qty || 0)}>+</button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}

      {/* Add another prescription */}
      <PatientPicker
        patients={patients}
        excludeIds={allocations.filter(a => a.patientId !== "_new_").map(a => a.patientId)}
        onPick={(id) => addAllocation(id)}
        onAddNew={(np) => {
          const newP = addPatient(np);
          setAllocations([...allocations, { patientId: newP.id, items: [] }]);
        }}
      />

      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
        <button className="btn btn-ghost" onClick={() => setRoute("basket")}>← Back</button>
        <button className="btn btn-primary" disabled={!canProceed} onClick={() => setRoute("declare")}>
          Continue to declarations <Icon.ChevronR />
        </button>
      </div>

      {bmiBlockers.length > 0 && (
        <div style={{ marginTop: 16, padding: "12px 14px", borderRadius: 8, background: "#FBE9E2", border: "1px solid var(--rust)", color: "var(--rust)", fontSize: 12, lineHeight: 1.5 }}>
          <strong>Blocked:</strong> {bmiBlockers.map(p => `${p.first} ${p.last}`).join(", ")} {bmiBlockers.length === 1 ? "does" : "do"} not meet the BMI threshold (≥27 with comorbidity, or ≥30). Open the patient record to update or remove from this prescription.
        </div>
      )}
    </div>
  );
}

function PatientPicker({ patients, excludeIds, onPick, onAddNew }) {
  const [q, setQ] = uS4("");
  const [focused, setFocused] = uS4(false);
  const [showNew, setShowNew] = uS4(false);
  const [np, setNp] = uS4({ first: "", last: "", dob: "", phone: "", email: "", address: "", postcode: "", height: "", weight: "", gpName: "", gpSurgery: "", comorbidity: "" });
  const inputRef = uR4(null);

  if (showNew) {
    const h = parseFloat(np.height);
    const w = parseFloat(np.weight);
    const bmiNum = h > 0 && w > 0 ? w / Math.pow(h / 100, 2) : null;
    const bmi = bmiNum ? bmiNum.toFixed(1) : "—";

    let bmiBanner = null;
    if (bmiNum !== null) {
      if (bmiNum >= 30) {
        bmiBanner = { kind: "ok", text: `BMI ${bmi} · meets the ≥30 threshold for weight-loss treatment.` };
      } else if (bmiNum >= 27) {
        bmiBanner = { kind: "warn", text: `BMI ${bmi} · between 27–30. A weight-related comorbidity (e.g. T2DM, hypertension, OSA, dyslipidaemia) must be documented.` };
      } else {
        bmiBanner = { kind: "blocked", text: `BMI ${bmi} · below 27. This patient is outside the licensed indication for GLP-1 weight management. Cannot proceed.` };
      }
    }

    const canSave = np.first && np.last && np.dob && np.address && np.postcode && bmiNum !== null && bmiNum >= 27 && (bmiNum >= 30 || np.comorbidity);

    return (
      <div className="card" style={{ padding: 0, marginBottom: 12 }}>
        <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div style={{ fontWeight: 600 }}>New patient</div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>BMI must be confirmed before this patient can receive a prescription.</div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => setShowNew(false)}>Cancel</button>
        </div>
        <div style={{ padding: 20 }}>
          <div className="field-row" style={{ marginBottom: 12 }}>
            <div className="field"><label>First name *</label><input className="input" value={np.first} onChange={(e) => setNp({...np, first: e.target.value})} /></div>
            <div className="field"><label>Last name *</label><input className="input" value={np.last} onChange={(e) => setNp({...np, last: e.target.value})} /></div>
          </div>
          <div className="field-row" style={{ marginBottom: 12 }}>
            <div className="field"><label>DOB *</label><input className="input" type="date" value={np.dob} onChange={(e) => setNp({...np, dob: e.target.value})} /></div>
            <div className="field"><label>Email</label><input className="input" value={np.email} onChange={(e) => setNp({...np, email: e.target.value})} /></div>
          </div>
          <div className="field-row" style={{ marginBottom: 12 }}>
            <div className="field"><label>Address *</label><input className="input" value={np.address} onChange={(e) => setNp({...np, address: e.target.value})} /></div>
            <div className="field"><label>Postcode *</label><input className="input" value={np.postcode} onChange={(e) => setNp({...np, postcode: e.target.value})} /></div>
          </div>

          <div style={{ marginTop: 18, marginBottom: 12, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
            <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-3)", marginBottom: 10 }}>BMI assessment · required</div>
          </div>
          <div className="field-row-3" style={{ marginBottom: 12 }}>
            <div className="field"><label>Height (cm) *</label><input className="input tnum" placeholder="170" value={np.height} onChange={(e) => setNp({...np, height: e.target.value})} /></div>
            <div className="field"><label>Weight (kg) *</label><input className="input tnum" placeholder="92" value={np.weight} onChange={(e) => setNp({...np, weight: e.target.value})} /></div>
            <div className="field"><label>Calculated BMI</label><div style={{ padding: "10px 12px", background: "var(--canvas-2)", borderRadius: 8, fontWeight: 600, color: bmiNum && bmiNum >= 27 ? "var(--accent)" : bmiNum ? "var(--rust)" : "var(--ink-4)" }} className="tnum">{bmi}</div></div>
          </div>

          {bmiBanner && (
            <div style={{
              padding: "12px 14px",
              borderRadius: 8,
              fontSize: 12,
              lineHeight: 1.5,
              marginBottom: 14,
              background: bmiBanner.kind === "ok" ? "var(--green-soft)" : bmiBanner.kind === "warn" ? "var(--gold-soft)" : "#FBE9E2",
              border: "1px solid " + (bmiBanner.kind === "ok" ? "var(--green)" : bmiBanner.kind === "warn" ? "var(--gold)" : "var(--rust)"),
              color: bmiBanner.kind === "ok" ? "var(--green)" : bmiBanner.kind === "warn" ? "#7A5A00" : "var(--rust)"
            }}>
              {bmiBanner.text}
            </div>
          )}

          {bmiNum !== null && bmiNum >= 27 && bmiNum < 30 && (
            <div className="field" style={{ marginBottom: 14 }}>
              <label>Documented weight-related comorbidity *</label>
              <select className="input" value={np.comorbidity || ""} onChange={(e) => setNp({...np, comorbidity: e.target.value})}>
                <option value="">— Select condition —</option>
                <option value="T2DM">Type 2 diabetes mellitus</option>
                <option value="Pre-diabetes">Pre-diabetes (HbA1c 42–47)</option>
                <option value="Hypertension">Hypertension</option>
                <option value="Dyslipidaemia">Dyslipidaemia</option>
                <option value="OSA">Obstructive sleep apnoea</option>
                <option value="CVD">Established cardiovascular disease</option>
                <option value="PCOS">PCOS with insulin resistance</option>
              </select>
            </div>
          )}

          <button className="btn btn-accent" disabled={!canSave} onClick={() => {
            onAddNew({ ...np, bmi: bmiNum, height: h, weight: w, gp: (np.gpName || "—") + " · " + (np.gpSurgery || "—") });
            setShowNew(false);
            setNp({ first: "", last: "", dob: "", phone: "", email: "", address: "", postcode: "", height: "", weight: "", gpName: "", gpSurgery: "", comorbidity: "" });
          }}>Save patient & start prescription</button>
          {!canSave && bmiNum !== null && bmiNum >= 27 && (
            <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 8 }}>Complete required fields (*) to continue.</div>
          )}
        </div>
      </div>
    );
  }

  if (!showNew && !showNew /* sentinel: render typeahead always */) {
    const ql = q.trim().toLowerCase();
    const filtered = patients.filter(p => !excludeIds.includes(p.id) && (
      ql === "" ||
      (p.first + " " + p.last).toLowerCase().includes(ql) ||
      (p.email || "").toLowerCase().includes(ql) ||
      (p.postcode || "").toLowerCase().includes(ql)
    )).slice(0, 8);

    return (
      <div className="card" style={{ padding: 0, marginBottom: 12, position: "relative" }}>
        <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div style={{ fontWeight: 600 }}>Add another prescription</div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>Search by name, postcode or email — or create a new patient.</div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => { setShowNew(true); setQ(""); }}>
            <Icon.New /> New patient
          </button>
        </div>
        <div style={{ padding: 16, position: "relative" }}>
          <div className="search-bar" style={{ width: "100%", maxWidth: "100%" }}>
            <Icon.Search />
            <input
              ref={inputRef}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onFocus={() => setFocused(true)}
              onBlur={() => setTimeout(() => setFocused(false), 180)}
              placeholder="Start typing a name, postcode, or email…"
              style={{ width: "100%" }}
            />
            {q && <button className="btn btn-link" onClick={() => setQ("")} style={{ fontSize: 11, padding: 4 }}>Clear</button>}
          </div>

          {(focused || q) && (
            <div style={{
              marginTop: 10,
              border: "1px solid var(--line)",
              borderRadius: 10,
              background: "var(--paper)",
              maxHeight: 360,
              overflow: "auto",
              boxShadow: "0 8px 24px -12px rgba(11,31,42,0.18)"
            }}>
              {filtered.length === 0 ? (
                <div style={{ padding: "20px 16px", textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>
                  {q ? <>
                    No patients match <strong>"{q}"</strong>.
                    <div style={{ marginTop: 10 }}>
                      <button className="btn btn-accent btn-sm" onMouseDown={(e) => e.preventDefault()} onClick={() => {
                        // Pre-fill name guess from query
                        const parts = q.trim().split(/\s+/);
                        const first = parts[0] || "";
                        const last = parts.slice(1).join(" ");
                        setNp({ ...np, first: first.charAt(0).toUpperCase() + first.slice(1), last: last.charAt(0).toUpperCase() + last.slice(1) });
                        setShowNew(true);
                        setQ("");
                      }}><Icon.New /> Create "{q}" as new patient</button>
                    </div>
                  </> : "Start typing to search your patient list…"}
                </div>
              ) : (
                filtered.map((p, i) => {
                  const age = calcAge(p.dob);
                  return (
                    <button
                      key={p.id}
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => { onPick(p.id); setQ(""); setFocused(false); }}
                      style={{
                        textAlign: "left",
                        padding: "12px 16px",
                        background: "transparent",
                        border: "none",
                        borderBottom: i < filtered.length - 1 ? "1px solid var(--line)" : "none",
                        cursor: "pointer",
                        fontFamily: "inherit",
                        display: "grid",
                        gridTemplateColumns: "auto 1fr auto",
                        gap: 14,
                        alignItems: "center",
                        width: "100%"
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = "var(--canvas-2)"}
                      onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
                    >
                      <div className="patient-avatar" style={{ width: 36, height: 36 }}>{initials(p.first, p.last)}</div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 3 }}>
                          {highlightMatch(`${p.first} ${p.last}`, q)}
                          <span style={{ color: "var(--ink-4)", fontWeight: 400, marginLeft: 8 }} className="tnum">· {age}y · DOB {formatDate(p.dob)}</span>
                        </div>
                        <div style={{ fontSize: 11.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {p.address || "—"}{p.postcode ? <span style={{ marginLeft: 6, color: "var(--ink-4)" }}>· {highlightMatch(p.postcode, q)}</span> : null}
                        </div>
                      </div>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 11 }}>
                        <span className="tnum" style={{
                          padding: "3px 8px",
                          borderRadius: 999,
                          background: p.bmi >= 27 ? "var(--accent-soft)" : "#FBE9E2",
                          color: p.bmi >= 27 ? "var(--accent)" : "var(--rust)",
                          fontWeight: 600
                        }}>BMI {p.bmi.toFixed(1)}</span>
                        <span style={{ color: "var(--ink-4)" }} className="tnum">{p.orders} orders</span>
                        <Icon.ChevronR />
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          )}

          {!focused && !q && (
            <div style={{ marginTop: 10, fontSize: 11, color: "var(--ink-4)", textAlign: "center" }}>
              {patients.length} patient{patients.length === 1 ? "" : "s"} on file · click the field to browse, or <button className="btn btn-link" onClick={() => setShowNew(true)} style={{ fontSize: 11, padding: 0 }}>create a new one</button>.
            </div>
          )}
        </div>
      </div>
    );
  }
}

// Bold the matched substring in a result row
function highlightMatch(text, q) {
  if (!q) return text;
  const idx = text.toLowerCase().indexOf(q.toLowerCase());
  if (idx === -1) return text;
  return <>
    {text.slice(0, idx)}
    <mark style={{ background: "var(--gold-soft)", color: "inherit", padding: "0 1px", borderRadius: 2 }}>{text.slice(idx, idx + q.length)}</mark>
    {text.slice(idx + q.length)}
  </>;
}

window.BasketScreen = BasketScreen;
window.AllocateScreen = AllocateScreen;
