// Customer pre-book screen + Receipt preview modal
function PrebookScreen() {
  const { products, addPrebooking } = usePOS();
  const [search, setSearch] = React.useState("");
  const [cart, setCart] = React.useState([]);
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [date, setDate] = React.useState(window.TODAY);
  const [party, setParty] = React.useState(2);
  const [stage, setStage] = React.useState("form"); // form | pay | done

  const filtered = products.filter((p) => !search || p.name.toLowerCase().includes(search.toLowerCase()));
  const subtotal = cart.reduce((s, l) => s + l.price * l.qty, 0);
  const deposit = Math.round(subtotal * 0.2);

  const add = (p) => setCart((prev) => {
    const i = prev.findIndex((x) => x.id === p.id);
    if (i >= 0) { const n = [...prev]; n[i] = { ...n[i], qty: n[i].qty + 1 }; return n; }
    return [...prev, { id: p.id, name: p.name, price: p.price, qty: 1, swatch: p.swatch }];
  });
  const dec = (id) => setCart((prev) => prev.map((x) => x.id === id ? { ...x, qty: x.qty - 1 } : x).filter((x) => x.qty > 0));

  const confirm = () => {
    addPrebooking({
      customerName: name, customerPhone: phone, visitDate: date,
      partySize: party, items: cart, subtotal,
      depositRequired: deposit, depositPaid: deposit, status: "paid_deposit",
    });
    setStage("done");
  };

  return (
    <div className="prebook">
      <div className="prebook-hero">
        <div className="prebook-hero-text">
          <div className="eyebrow mono">PRE-BOOK · KEDAI OMA NANA · kon.cafe Surabaya</div>
          <h1>Reserve your table and pre-order.</h1>
          <p className="muted">Pay a 20% deposit via QRIS. We'll have everything ready when you arrive — no queue.</p>
        </div>
        <div className="prebook-hero-meta mono">
          <div><span className="muted">OPEN</span><span>Daily · 07:00 – 22:00</span></div>
          <div><span className="muted">DEPOSIT</span><span>20% via QRIS</span></div>
          <div><span className="muted">REFUND</span><span>Up to 24h before</span></div>
        </div>
      </div>

      <div className="prebook-grid">
        <section className="panel-card">
          <header className="pane-head">
            <h3>Pick your menu</h3>
            <input className="search search-sm" placeholder="Search…" value={search} onChange={(e) => setSearch(e.target.value)} />
          </header>
          <div className="prebook-menu">
            {filtered.map((p) => (
              <button key={p.id} className="prebook-item" onClick={() => add(p)}>
                <ProductSwatch color={p.swatch} label={p.name} size={48} />
                <div className="prebook-item-body">
                  <div>{p.name}</div>
                  <div className="muted mono">{p.category}</div>
                </div>
                <Mono>{money(p.price)}</Mono>
              </button>
            ))}
          </div>
        </section>

        <section className="panel-card prebook-form">
          <h3>Booking</h3>
          <div className="form-grid">
            <label className="field"><span className="field-label mono">Your name</span><input value={name} onChange={(e) => setName(e.target.value)} /></label>
            <label className="field"><span className="field-label mono">WhatsApp</span><input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="08••" /></label>
            <label className="field"><span className="field-label mono">Visit date</span><input type="date" value={date} onChange={(e) => setDate(e.target.value)} /></label>
            <label className="field"><span className="field-label mono">Party</span><input type="number" min="1" value={party} onChange={(e) => setParty(Number(e.target.value) || 1)} /></label>
          </div>

          <div className="prebook-cart">
            <div className="eyebrow mono">SELECTED</div>
            {cart.length === 0 && <div className="muted">No items yet.</div>}
            {cart.map((l) => (
              <div className="prebook-cart-row" key={l.id}>
                <span>{l.name}</span>
                <div className="qty-stepper qty-sm">
                  <button onClick={() => dec(l.id)}>–</button>
                  <Mono>{l.qty}</Mono>
                  <button onClick={() => add(l)}>+</button>
                </div>
                <Mono>{money(l.price * l.qty)}</Mono>
              </div>
            ))}
          </div>

          <div className="cart-totals">
            <div className="total-row"><span>Subtotal</span><Mono>{money(subtotal)}</Mono></div>
            <div className="total-row total-grand"><span>Deposit (20%)</span><Mono>{money(deposit)}</Mono></div>
          </div>

          {stage === "form" && (
            <button className="btn-primary full" disabled={!name || !phone || !cart.length} onClick={() => setStage("pay")}>
              Confirm & pay deposit →
            </button>
          )}
          {stage === "pay" && (
            <div className="prebook-pay">
              <div className="eyebrow mono">SCAN TO PAY {money(deposit)}</div>
              <QRPlaceholder size={220} />
              <button className="btn-primary full" onClick={confirm}>I've paid the deposit</button>
              <button className="btn-ghost full" onClick={() => setStage("form")}>Back</button>
            </div>
          )}
          {stage === "done" && (
            <div className="prebook-done">
              <div className="empty-mark">✓</div>
              <h3>You're booked.</h3>
              <p className="muted">See you on {date}. We sent a confirmation to {phone}.</p>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}

// Receipt preview — modal triggered after checkout
function ReceiptModal() {
  const { receiptOrder, setReceiptOrder } = usePOS();
  const [settings] = usePrinterSettings();
  const printed = React.useRef(null);

  // Auto-print receipt + kitchen tickets once per new order, if enabled.
  React.useEffect(() => {
    if (!receiptOrder || printed.current === receiptOrder.id) return;
    printed.current = receiptOrder.id;
    if (settings.autoPrintReceipt) setTimeout(() => printPaper(settings.paperWidth), 250);
    if (settings.autoPrintKitchen) {
      const hasKitchen = receiptOrder.items.some((i) => i.station === "kitchen");
      const hasBar = receiptOrder.items.some((i) => i.station === "bar");
      // We render kitchen tickets in a hidden div temporarily then print.
      if (hasKitchen || hasBar) {
        // simple sequential: after the receipt window.print resolves, user
        // can press 'Print kitchen ticket' if needed. Auto is best-effort.
      }
    }
  }, [receiptOrder]);

  if (!receiptOrder) return null;
  const o = receiptOrder;
  const subtotal = o.items.reduce((s, i) => s + (i.price + (i.modPrice || 0)) * i.qty, 0);

  return (
    <div className="sheet-wrap" onMouseDown={() => setReceiptOrder(null)}>
      <div className="receipt" onMouseDown={(e) => e.stopPropagation()}>
        <div className="receipt-paper printable">
          <div className="pr-brand">Kedai Oma Nana</div>
          <div className="pr-sub"><em>* kon.cafe — Surabaya *</em></div>
          <div className="pr-sub">{fmtDay()} · {fmtClock()} WIB</div>
          <div className="pr-rule" />
          <div className="pr-row"><span>Order {o.shortId}</span><span>Table {o.table}</span></div>
          <div className="pr-row"><span>{o.customer}</span><span>{(o.paymentMethod || "").toUpperCase()}</span></div>
          <div className="pr-rule" />
          <table className="pr-items">
            <tbody>
              {o.items.map((it, i) => (
                <React.Fragment key={i}>
                  <tr>
                    <td>{it.qty}× {it.name}{it.sku ? ` (${it.sku})` : ""}</td>
                    <td className="r">{money((it.price + (it.modPrice || 0)) * it.qty)}</td>
                  </tr>
                  {it.mods && it.mods.length > 0 && (
                    <tr><td className="pr-mod" colSpan="2">{it.mods.join(" · ")}</td></tr>
                  )}
                  {it.notes && (
                    <tr><td className="pr-note" colSpan="2">* {it.notes}</td></tr>
                  )}
                </React.Fragment>
              ))}
            </tbody>
          </table>
          <div className="pr-rule" />
          <div className="pr-row"><span>Subtotal</span><span>{money(subtotal)}</span></div>
          {o.depositApplied > 0 && <div className="pr-row"><span>Deposit</span><span>−{money(o.depositApplied)}</span></div>}
          {o.tip > 0 && <div className="pr-row"><span>Tip</span><span>{money(o.tip)}</span></div>}
          {o.uniqueCode > 0 && <div className="pr-row"><span>Unique code (QRIS)</span><span>+{money(o.uniqueCode)}</span></div>}
          <div className="pr-row pr-total"><span>TOTAL</span><span>{money(o.total)}</span></div>
          <div className="pr-rule" />
          <div className="pr-center">— Terima kasih —</div>
          <div className="pr-center">@kedaiomanana</div>
        </div>
        <div className="receipt-actions print-only-hide">
          <button className="btn-ghost" onClick={() => setReceiptOrder(null)}>Close</button>
          <button className="btn-primary" onClick={() => printPaper(settings.paperWidth)}>Print receipt</button>
          <button className="btn-ghost" onClick={() => setReceiptOrder(null)}>Done</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PrebookScreen, ReceiptModal });
