// Cashier — order taking + checkout with modifiers, split pay, tip
// Wrapper: gates the screen behind the shift-open modal so the inner body's
// hooks aren't conditionally mounted (avoids React error #310).
function CashierScreen() {
  const { currentShift, openShift, db, user, role } = usePOS();
  const [foreignShift, setForeignShift] = React.useState(null);

  // Watch for any open shift owned by another user — only one cashier at a time
  // (admins are allowed to log in alongside an active cashier).
  React.useEffect(() => {
    if (!user) return;
    return db.collection("shifts").where("status", "==", "open").onSnapshot((s) => {
      const other = s.docs
        .map((d) => ({ id: d.id, ...d.data() }))
        .find((sh) => sh.cashierUid && sh.cashierUid !== user.uid);
      setForeignShift(other || null);
    });
  }, [user]);

  if (foreignShift && role !== "admin") return <CashierLockedScreen shift={foreignShift} />;
  if (!currentShift) return <ShiftOpenSheet onConfirm={openShift} />;
  return <CashierBody foreignShift={role === "admin" ? foreignShift : null} />;
}

function CashierLockedScreen({ shift }) {
  const opened = shift.openedAt?.toDate ? shift.openedAt.toDate() : null;
  return (
    <div className="cashier-locked">
      <div className="cashier-locked-card">
        <div className="eyebrow mono">CASHIER · LOCKED</div>
        <div className="lock-icon">🔒</div>
        <h2>Another cashier is signed in</h2>
        <p className="muted">
          The POS allows only one open cashier session at a time. The current
          cashier must close their shift before you can take over.
        </p>
        <div className="lock-info mono">
          <div><span className="muted">Cashier</span><strong>{shift.cashierEmail || shift.cashierUid}</strong></div>
          {opened && <div><span className="muted">Opened</span><strong>{opened.toLocaleString("en-GB", { timeZone: "Asia/Jakarta" })} WIB</strong></div>}
        </div>
        <button className="btn-ghost" onClick={() => firebase.auth().signOut()}>Sign out</button>
      </div>
    </div>
  );
}

function CashierBody({ foreignShift }) {
  const { products, placeOrder, updateOrder, prebookings, consumePrebooking, pushLiveCart, orders,
          currentShift, closeShift, db, showToast } = usePOS();

  const forceCloseForeign = async () => {
    if (!foreignShift) return;
    if (!confirm(`Force-close the shift opened by ${foreignShift.cashierEmail || foreignShift.cashierUid}? They will be signed out of the cashier section.`)) return;
    await db.collection("shifts").doc(foreignShift.id).update({
      status: "closed",
      closedAt: firebase.firestore.FieldValue.serverTimestamp(),
      closedBy: "admin",
      forceClosed: true,
    });
    showToast("Shift force-closed");
  };
  const [closingShift, setClosingShift] = React.useState(false);
  const [receiptsOpen, setReceiptsOpen] = React.useState(false);
  const [refundFor, setRefundFor] = React.useState(null);
  const [search, setSearch] = React.useState("");
  const [cat, setCat] = React.useState("All");
  const [cart, setCart] = React.useState([]);
  const [customer, setCustomer] = React.useState("");
  const [table, setTable] = React.useState("");
  const [modProduct, setModProduct] = React.useState(null);
  const [checkout, setCheckout] = React.useState(null); // {mode:'pay'}
  const [activePrebook, setActivePrebook] = React.useState(null);
  const [editingOrderId, setEditingOrderId] = React.useState(null);

  const openBills = orders.filter((o) => o.paid === false && o.status !== "closed");

  const filtered = products.filter((p) =>
    (cat === "All" || p.category === cat) &&
    (!search || p.name.toLowerCase().includes(search.toLowerCase()))
  );

  const onPick = (p) => {
    const mods = (p.modifiers && p.modifiers.length) ? p.modifiers : window.MODIFIERS[p.category];
    if (mods && mods.length) { setModProduct(p); }
    else { addToCart({ ...p, mods: [], modPrice: 0, qty: 1, cogs: p.cogs || 0, notes: "" }); }
  };

  const addToCart = (line) => {
    setCart((prev) => {
      const key = line.id + "|" + line.mods.join(",") + "|" + (line.notes || "");
      const i = prev.findIndex((x) => x._key === key);
      if (i >= 0) {
        const next = [...prev];
        next[i] = { ...next[i], qty: next[i].qty + line.qty };
        return next;
      }
      return [...prev, { ...line, _key: key, notes: line.notes || "" }];
    });
  };

  const changeQty = (key, d) => setCart((prev) => prev.map((x) =>
    x._key === key ? { ...x, qty: Math.max(0, x.qty + d) } : x).filter((x) => x.qty > 0));
  const removeLine = (key) => setCart((prev) => prev.filter((x) => x._key !== key));
  const setLineNotes = (key, notes) => setCart((prev) => prev.map((x) =>
    x._key === key ? { ...x, notes } : x));

  const subtotal = cart.reduce((s, l) => s + (l.price + l.modPrice) * l.qty, 0);
  const depositCredit = activePrebook ? activePrebook.depositPaid : 0;

  // Push live cart to /displays/main so customer-display mirrors in real time.
  React.useEffect(() => {
    const t = setTimeout(() => {
      pushLiveCart(cart.map((l) => ({
        id: l.id, name: l.name, price: l.price, qty: l.qty,
        station: l.station, mods: l.mods, modPrice: l.modPrice,
      })), {
        subtotal, depositApplied: depositCredit,
        total: Math.max(0, subtotal - depositCredit),
        customer: customer || null, table: table || null,
        shortId: null,
      });
    }, 200);
    return () => clearTimeout(t);
  }, [cart, customer, table, depositCredit]);

  const todayPb = prebookings.filter((p) => p.status === "paid_deposit");

  const loadPb = (pb) => {
    setActivePrebook(pb);
    setCustomer(pb.customerName);
    setCart(pb.items.map((i) => ({
      ...i, mods: [], modPrice: 0, _key: i.id + "|",
      station: (products.find((p) => p.id === i.id) || {}).station || "bar",
    })));
  };

  const resetCart = () => {
    setCart([]); setActivePrebook(null); setCustomer(""); setTable("");
    setEditingOrderId(null); setCheckout(null);
  };

  // Save the cart as an open bill: order is created with paid:false and sent
  // to the kitchen immediately. Cashier can pay later by tapping it in the
  // 'Open bills' banner.
  const saveOpenBill = async () => {
    const shortId = "A" + Math.floor(Math.random() * 90 + 10);
    const hasBar = cart.some((i) => i.station === "bar");
    const hasKitchen = cart.some((i) => i.station === "kitchen");
    if (editingOrderId) {
      // Just update items / totals on the existing open bill
      await updateOrder(editingOrderId, {
        items: cart.map((l) => ({
          id: l.id, sku: l.sku || "", name: l.name, price: l.price, qty: l.qty,
          station: l.station, mods: l.mods || [], modPrice: l.modPrice || 0,
          cogs: l.cogs || 0, notes: l.notes || "",
        })),
        subtotal, total: subtotal - depositCredit,
        customer: customer || "Walk-in", table: table || "T",
      });
    } else {
      await placeOrder({
        shortId, table: table || "T", customer: customer || "Walk-in",
        items: cart.map((l) => ({ ...l })),
        subtotal, depositApplied: depositCredit,
        total: subtotal - depositCredit,
        paid: false,
        barStatus: hasBar ? "new" : null,
        kitchenStatus: hasKitchen ? "new" : null,
        prebookingId: activePrebook?.id || null,
      });
      if (activePrebook) consumePrebooking(activePrebook.id);
    }
    resetCart();
  };

  const placeFinal = async (payments) => {
    const shortId = "A" + Math.floor(Math.random() * 90 + 10);
    const hasBar = cart.some((i) => i.station === "bar");
    const hasKitchen = cart.some((i) => i.station === "kitchen");
    const total = subtotal - depositCredit + (payments.uniqueCode || 0);
    if (editingOrderId) {
      // Pay an existing open bill — keep kitchen status as-is
      await updateOrder(editingOrderId, {
        items: cart.map((l) => ({
          id: l.id, sku: l.sku || "", name: l.name, price: l.price, qty: l.qty,
          station: l.station, mods: l.mods || [], modPrice: l.modPrice || 0,
          cogs: l.cogs || 0, notes: l.notes || "",
        })),
        subtotal, depositApplied: depositCredit,
        uniqueCode: payments.uniqueCode || 0, total,
        tip: payments.tip || 0,
        payments: payments.splits,
        paymentMethod: payments.splits.length === 1 ? payments.splits[0].method : "split",
        paid: true,
        customer: customer || "Walk-in", table: table || "T",
      });
    } else {
      await placeOrder({
        shortId, table: table || "T", customer: customer || "Walk-in",
        items: cart.map((l) => ({ ...l })),
        subtotal, depositApplied: depositCredit,
        uniqueCode: payments.uniqueCode || 0, total,
        tip: payments.tip || 0,
        payments: payments.splits,
        paymentMethod: payments.splits.length === 1 ? payments.splits[0].method : "split",
        paid: true,
        barStatus: hasBar ? "new" : null,
        kitchenStatus: hasKitchen ? "new" : null,
        prebookingId: activePrebook?.id || null,
      });
      if (activePrebook) consumePrebooking(activePrebook.id);
    }
    resetCart();
  };

  const loadBill = (o) => {
    setEditingOrderId(o.id);
    setCustomer(o.customer || "");
    setTable(o.table || "");
    setCart(o.items.map((i) => ({
      ...i, _key: i.id + "|" + (i.mods || []).join(",") + "|" + (i.notes || ""),
    })));
  };

  return (
    <div className="cashier">
      {foreignShift && (
        <div className="admin-override-bar mono">
          <span>👑 Admin override · Active cashier: <strong>{foreignShift.cashierEmail || foreignShift.cashierUid}</strong> (opened {foreignShift.openedAt?.toDate ? foreignShift.openedAt.toDate().toLocaleString("en-GB", { timeZone: "Asia/Jakarta", hour: "2-digit", minute: "2-digit" }) + " WIB" : "—"})</span>
          <button className="btn-ghost-sm danger" onClick={forceCloseForeign}>Force close their shift</button>
        </div>
      )}
      <section className="cashier-menu">
        <div className="menu-head">
          <div className="search-wrap">
            <span className="kbd-hint mono">⌘K</span>
            <input
              className="search" placeholder="Search the menu…"
              value={search} onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <div className="cat-bar">
            {(() => {
              const dynamic = ["All", ...Array.from(new Set(products.map((p) => p.category).filter(Boolean))).sort()];
              return dynamic;
            })().map((c) => (
              <button
                key={c}
                className={"cat-chip" + (cat === c ? " active" : "")}
                onClick={() => setCat(c)}
              >
                {c}
              </button>
            ))}
          </div>
        </div>

        {todayPb.length > 0 && (
          <div className="prebook-banner">
            <span className="banner-label mono">TODAY'S PRE-BOOKS</span>
            {todayPb.map((pb) => (
              <button key={pb.id} className="prebook-chip" onClick={() => loadPb(pb)}>
                <span>{pb.customerName}</span>
                <Mono>{pb.items.reduce((a, i) => a + i.qty, 0)} items · deposit {money(pb.depositPaid)}</Mono>
              </button>
            ))}
          </div>
        )}

        {openBills.length > 0 && (
          <div className="prebook-banner openbill-banner">
            <span className="banner-label mono">OPEN BILLS</span>
            {openBills.map((o) => (
              <button key={o.id} className={"prebook-chip" + (editingOrderId === o.id ? " active" : "")} onClick={() => loadBill(o)}>
                <span>#{o.shortId} · {o.customer}{o.visitTime ? ` · ${o.visitTime}` : ""}</span>
                <Mono>T{o.table} · {money(o.total)}</Mono>
              </button>
            ))}
          </div>
        )}

        <div className="product-grid">
          {filtered.map((p) => (
            <button key={p.id} className="product-card" onClick={() => onPick(p)}>
              <ProductSwatch color={p.swatch} label={p.name} size={64} />
              <div className="product-meta">
                <div className="product-name">{p.name}</div>
                <div className="product-desc">{p.desc}</div>
                <div className="product-foot">
                  <Mono className="product-price">{money(p.price)}</Mono>
                  {p.stock <= 20 && <span className="stock-low mono">{p.stock} left</span>}
                </div>
              </div>
            </button>
          ))}
        </div>
      </section>

      <section className="cashier-cart">
        <header className="cart-head">
          <div>
            <div className="eyebrow mono">CURRENT ORDER</div>
            <h2>{customer || "New ticket"}</h2>
          </div>
          {activePrebook && <span className="badge-prebook mono">PRE-BOOK</span>}
        </header>

        <div className="cart-fields">
          <label className="field">
            <span className="field-label mono">Customer</span>
            <input value={customer} onChange={(e) => setCustomer(e.target.value)} placeholder="Walk-in" />
          </label>
          <label className="field field-table">
            <span className="field-label mono">Table</span>
            <input value={table} onChange={(e) => setTable(e.target.value)} placeholder="—" />
          </label>
        </div>

        <div className="cart-list">
          {cart.length === 0 && (
            <div className="cart-empty">
              <div className="empty-mark">⌘</div>
              <p>Tap a product to start a ticket.</p>
            </div>
          )}
          {cart.map((l) => (
            <div className="cart-line" key={l._key}>
              <div className="cart-line-main">
                <div className="cart-line-name">{l.name}</div>
                {l.mods.length > 0 && (
                  <div className="cart-line-mods mono">{l.mods.join(" · ")}</div>
                )}
                <input
                  className="cart-line-note"
                  placeholder="+ note (e.g. extra hot, no ice)"
                  value={l.notes || ""}
                  onChange={(e) => setLineNotes(l._key, e.target.value)}
                />
              </div>
              <div className="cart-line-qty">
                <button onClick={() => changeQty(l._key, -1)}>–</button>
                <Mono>{l.qty}</Mono>
                <button onClick={() => changeQty(l._key, 1)}>+</button>
              </div>
              <Mono className="cart-line-sub">{money((l.price + l.modPrice) * l.qty)}</Mono>
              <button className="cart-line-x" onClick={() => removeLine(l._key)}>×</button>
            </div>
          ))}
        </div>

        <div className="cart-totals">
          <div className="total-row"><span>Subtotal</span><Mono>{money(subtotal)}</Mono></div>
          {depositCredit > 0 && (
            <div className="total-row total-credit"><span>Deposit applied</span><Mono>−{money(depositCredit)}</Mono></div>
          )}
          <div className="total-row total-grand">
            <span>Due</span><Mono>{money(Math.max(0, subtotal - depositCredit))}</Mono>
          </div>
        </div>

        {cart.length > 0 && (!customer.trim() || !table.trim()) && (
          <div className="cart-required mono">Enter customer name and table to checkout.</div>
        )}
        <div className="cart-actions">
          <button className="btn-ghost" disabled={!cart.length} onClick={resetCart}>Clear</button>
          <button
            className="btn-ghost btn-savebill"
            disabled={!cart.length || !customer.trim() || !table.trim()}
            onClick={saveOpenBill}
            title="Send the order to the kitchen and pay later">
            {editingOrderId ? "Update bill" : "Save & pay later"}
          </button>
          <button
            className="btn-primary"
            disabled={!cart.length || !customer.trim() || !table.trim()}
            onClick={() => setCheckout({})}>
            {editingOrderId ? "Pay this bill →" : "Checkout & pay →"}
          </button>
        </div>
        <div className="shift-bar mono">
          <span className="muted">Shift open · float {money(currentShift.openingCash || 0)}</span>
          <div className="row" style={{ gap: 12 }}>
            <button className="btn-link" onClick={() => setReceiptsOpen(true)}>Refund / receipts</button>
            <button className="btn-link" onClick={() => setClosingShift(true)}>Close shift →</button>
          </div>
        </div>
        <WifiBar />
      </section>

      {modProduct && (
        <ModifierSheet
          product={modProduct}
          onClose={() => setModProduct(null)}
          onAdd={(line) => { addToCart(line); setModProduct(null); }}
        />
      )}

      {checkout && (
        <CheckoutSheet
          total={Math.max(0, subtotal - depositCredit)}
          onClose={() => setCheckout(null)}
          onConfirm={placeFinal}
        />
      )}

      {closingShift && (
        <ShiftCloseSheet
          shift={currentShift}
          orders={orders}
          onClose={() => setClosingShift(false)}
          onConfirm={async (payload) => {
            await closeShift(payload);
            setClosingShift(false);
          }}
        />
      )}

      {receiptsOpen && (
        <ReceiptsListSheet
          onClose={() => setReceiptsOpen(false)}
          onRefund={(o) => { setReceiptsOpen(false); setRefundFor(o); }}
        />
      )}
      {refundFor && (
        <RefundSheet order={refundFor} onClose={() => setRefundFor(null)} />
      )}
    </div>
  );
}

// Modifier popover
function ModifierSheet({ product, onClose, onAdd }) {
  const groups = (product.modifiers && product.modifiers.length)
    ? product.modifiers
    : (window.MODIFIERS[product.category] || []);
  const [picks, setPicks] = React.useState(() => {
    const init = {};
    groups.forEach((g) => { init[g.group] = g.type === "single" ? [g.options[0].id] : []; });
    return init;
  });
  const [qty, setQty] = React.useState(1);

  const toggle = (group, optId, type) => {
    setPicks((p) => {
      if (type === "single") return { ...p, [group]: [optId] };
      const cur = p[group] || [];
      return { ...p, [group]: cur.includes(optId) ? cur.filter((x) => x !== optId) : [...cur, optId] };
    });
  };

  let modPrice = 0;
  const labels = [];
  groups.forEach((g) => {
    (picks[g.group] || []).forEach((id) => {
      const opt = g.options.find((o) => o.id === id);
      if (!opt) return;
      modPrice += opt.delta;
      if (opt.delta !== 0 || g.options.length > 1) labels.push(opt.label);
    });
  });

  return (
    <div className="sheet-wrap" onMouseDown={onClose}>
      <div className="sheet" onMouseDown={(e) => e.stopPropagation()}>
        <header className="sheet-head">
          <div className="sheet-product">
            <ProductSwatch color={product.swatch} label={product.name} size={56} />
            <div>
              <div className="eyebrow mono">{product.category}</div>
              <h3>{product.name}</h3>
              <div className="muted">{product.desc}</div>
            </div>
          </div>
          <button className="icon-x" onClick={onClose}>×</button>
        </header>

        <div className="sheet-body">
          {groups.map((g) => (
            <div className="mod-group" key={g.group}>
              <div className="mod-group-head">
                <span className="mono eyebrow">{g.group}</span>
                <span className="muted mono">{g.type === "single" ? "Pick one" : "Multiple"}</span>
              </div>
              <div className="mod-options">
                {g.options.map((o) => {
                  const picked = (picks[g.group] || []).includes(o.id);
                  return (
                    <button
                      key={o.id}
                      className={"mod-opt" + (picked ? " picked" : "")}
                      onClick={() => toggle(g.group, o.id, g.type)}
                    >
                      <span>{o.label}</span>
                      <Mono>{o.delta > 0 ? "+" + money(o.delta) : o.delta < 0 ? money(o.delta) : "·"}</Mono>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <footer className="sheet-foot">
          <div className="qty-stepper">
            <button onClick={() => setQty((q) => Math.max(1, q - 1))}>–</button>
            <Mono>{qty}</Mono>
            <button onClick={() => setQty((q) => q + 1)}>+</button>
          </div>
          <button
            className="btn-primary"
            onClick={() => onAdd({ ...product, mods: labels, modPrice, qty, cogs: product.cogs || 0, notes: "" })}
          >
            Add — <Mono>{money((product.price + modPrice) * qty)}</Mono>
          </button>
        </footer>
      </div>
    </div>
  );
}

// Checkout: split pay + tip + Indonesian-style 2-digit unique code added
// only when QRIS is the payment method (for bank reconciliation).
function CheckoutSheet({ total, onClose, onConfirm }) {
  const { db } = usePOS();
  const [uniqueCode, setUniqueCode] = React.useState(() => Math.floor(Math.random() * 100));
  const rerollCode = () => setUniqueCode(Math.floor(Math.random() * 100));
  const [splits, setSplits] = React.useState([{ method: "cash", amount: total }]);

  const hasQris = splits.some((s) => s.method === "qris");
  const appliedCode = hasQris ? uniqueCode : 0;
  const due = total + appliedCode;

  React.useEffect(() => {
    setSplits((prev) => {
      if (prev.length === 1) return [{ ...prev[0], amount: due }];
      const head = prev.slice(0, -1);
      const sumHead = head.reduce((s, p) => s + p.amount, 0);
      return [...head, { ...prev[prev.length - 1], amount: Math.max(0, due - sumHead) }];
    });
  }, [total, appliedCode]);

  const paid = splits.reduce((s, p) => s + (Number(p.amount) || 0), 0);
  const balance = due - paid;

  // Push QRIS payment + unique code + final total to customer display.
  const qrisSplit = splits.find((s) => s.method === "qris");
  React.useEffect(() => {
    const payload = qrisSplit
      ? { method: "qris", amount: Number(qrisSplit.amount) || due, ready: true }
      : null;
    db.collection("displays").doc("main").set({
      payment: payload,
      uniqueCode: appliedCode,
      total: due,
    }, { merge: true });
    return () => {
      db.collection("displays").doc("main").set({ payment: null, uniqueCode: 0 }, { merge: true });
    };
  }, [qrisSplit?.amount, !!qrisSplit, due, appliedCode]);

  const setSplitAmount = (i, v) => {
    setSplits((prev) => {
      const next = [...prev];
      next[i] = { ...next[i], amount: Math.max(0, Math.floor(Number(v) || 0)) };
      return next;
    });
  };
  const setSplitMethod = (i, m) => setSplits((prev) => prev.map((p, idx) => idx === i ? { ...p, method: m } : p));

  return (
    <div className="sheet-wrap" onMouseDown={onClose}>
      <div className="sheet sheet-wide" onMouseDown={(e) => e.stopPropagation()}>
        <header className="sheet-head">
          <div>
            <div className="eyebrow mono">CHECKOUT</div>
            <h3>Take payment</h3>
          </div>
          <button className="icon-x" onClick={onClose}>×</button>
        </header>

        <div className="checkout-body">
          <div className="checkout-summary">
            <div className="big-due">
              <span className="eyebrow mono">DUE</span>
              <Mono className="big-num">{money(due)}</Mono>
            </div>
            <div className="due-rows">
              <div className="due-row"><span>Subtotal</span><Mono>{money(total)}</Mono></div>
              {hasQris && (
                <div className="due-row">
                  <span>Unique code (QRIS) <button type="button" className="btn-link" style={{ marginLeft: 6 }} onClick={rerollCode}>↻</button></span>
                  <Mono>+{money(uniqueCode)}</Mono>
                </div>
              )}
            </div>
          </div>

          <div className="checkout-splits">
            <div className="split-head">
              <span className="eyebrow mono">PAYMENT {splits.length > 1 ? "(SPLIT)" : ""}</span>
              <button
                className="btn-link"
                onClick={() => setSplits((p) => [...p, { method: "card", amount: 0 }])}
              >+ split</button>
            </div>
            {splits.map((s, i) => (
              <div className="split-row" key={i}>
                <div className="method-toggle">
                  {["cash", "qris", "card"].map((m) => (
                    <button
                      key={m}
                      className={"method" + (s.method === m ? " active" : "")}
                      onClick={() => setSplitMethod(i, m)}
                    >{m.toUpperCase()}</button>
                  ))}
                </div>
                <input
                  className="amount-input mono"
                  inputMode="numeric"
                  value={s.amount}
                  onChange={(e) => setSplitAmount(i, e.target.value.replace(/\D/g, ""))}
                />
                {splits.length > 1 && (
                  <button className="row-x" onClick={() => setSplits((p) => p.filter((_, k) => k !== i))}>×</button>
                )}
              </div>
            ))}
            <div className={"balance " + (balance === 0 ? "ok" : balance > 0 ? "short" : "over")}>
              <span>Balance</span>
              <Mono>{balance >= 0 ? money(balance) : "+ " + money(-balance) + " change"}</Mono>
            </div>
          </div>
        </div>

        <footer className="sheet-foot">
          <button className="btn-ghost" onClick={onClose}>Cancel</button>
          <button
            className="btn-primary"
            disabled={balance > 0}
            onClick={() => onConfirm({ tip: 0, splits, uniqueCode: appliedCode })}
          >
            Confirm payment
          </button>
        </footer>
      </div>
    </div>
  );
}

function WifiBar() {
  const { db, showToast } = usePOS();
  const [wifi, setWifi] = React.useState({ ssid: "Kedai Rona", password: "" });
  const [draft, setDraft] = React.useState("");
  const [editing, setEditing] = React.useState(false);

  React.useEffect(() => {
    return db.collection("displays").doc("wifi").onSnapshot((doc) => {
      if (doc.exists) {
        const d = doc.data();
        setWifi({ ssid: d.ssid || "Kedai Rona", password: d.password || "" });
      }
    });
  }, []);

  const save = async () => {
    await db.collection("displays").doc("wifi").set(
      { ssid: "Kedai Rona", password: draft.trim(), updatedAt: firebase.firestore.FieldValue.serverTimestamp() },
      { merge: true }
    );
    setEditing(false);
    showToast("WiFi password updated");
  };

  return (
    <div className="wifi-bar mono">
      <span className="muted">📶 Wi-Fi · {wifi.ssid}</span>
      {editing ? (
        <React.Fragment>
          <input
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="today's password"
            autoFocus
            style={{ flex: 1, padding: "4px 8px", fontSize: 13 }}
          />
          <button className="btn-link" onClick={save}>Save</button>
          <button className="btn-link" onClick={() => setEditing(false)}>Cancel</button>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <span>Password: <strong>{wifi.password || "—"}</strong></span>
          <button className="btn-link" onClick={() => { setDraft(wifi.password || ""); setEditing(true); }}>
            {wifi.password ? "Change" : "Set"}
          </button>
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { CashierScreen, WifiBar });
