// Refund flow — pick refundable items + qty, choose method, save.

function RefundSheet({ order, onClose }) {
  const { refundOrder } = usePOS();

  // Build line items: real order items + synthetic unique-code line if present.
  const uniqueCode = order.uniqueCode || 0;
  const syntheticCode = uniqueCode > 0
    ? [{ name: "QRIS unique code", price: uniqueCode, modPrice: 0, qty: 1, _synthetic: true }]
    : [];
  const lineItems = [...order.items, ...syntheticCode];

  const maxByLine = (it) => it.qty;
  const [picks, setPicks] = React.useState(() => lineItems.map(() => 0));
  const [method, setMethod] = React.useState(order.paymentMethod || "cash");
  const [reason, setReason] = React.useState("");

  const setQty = (i, q) => setPicks((p) => p.map((v, idx) => idx === i
    ? Math.max(0, Math.min(maxByLine(lineItems[i]), q)) : v));

  const alreadyRefunded = (order.refundedAmount || 0) > 0 || order.status === "refunded";
  const refundTotal = lineItems.reduce((s, it, i) =>
    s + (it.price + (it.modPrice || 0)) * picks[i], 0);
  const everything = lineItems.every((it, i) => picks[i] === it.qty);
  const nothing = refundTotal === 0;

  const fullRefund = () => setPicks(lineItems.map((it) => it.qty));

  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">REFUND · #{order.shortId}</div>
            <h3>{order.customer || "Walk-in"} · Table {order.table || "—"}</h3>
            <div className="muted mono" style={{ fontSize: 12 }}>
              Original total {money(order.total)} · paid via {(order.paymentMethod || "—").toUpperCase()}
              {order.refundedAmount > 0 && <span> · already refunded {money(order.refundedAmount)}</span>}
            </div>
          </div>
          <button className="icon-x" onClick={onClose}>×</button>
        </header>

        <div className="sheet-body">
          <div className="row" style={{ justifyContent: "flex-end", gap: 8 }}>
            <button className="btn-ghost-sm" onClick={fullRefund}>Refund everything</button>
          </div>
          <table className="data-table" style={{ marginTop: 8 }}>
            <thead><tr><th>Item</th><th style={{ width: 80 }}>Sold</th><th style={{ width: 160 }}>Refund qty</th><th style={{ width: 120, textAlign: "right" }}>Amount</th></tr></thead>
            <tbody>
              {lineItems.map((it, i) => (
                <tr key={i}>
                  <td>
                    <div>{it.name}{it.sku ? ` (${it.sku})` : ""}</div>
                    {it.mods && it.mods.length > 0 && <div className="muted mono" style={{ fontSize: 11 }}>{it.mods.join(" · ")}</div>}
                    {it.notes && <div className="muted mono" style={{ fontSize: 11 }}>* {it.notes}</div>}
                    {it._synthetic && <div className="muted mono" style={{ fontSize: 11 }}>QRIS rounding code</div>}
                  </td>
                  <td><Mono>{it.qty}</Mono></td>
                  <td>
                    <div className="qty-stepper">
                      <button onClick={() => setQty(i, picks[i] - 1)} disabled={picks[i] <= 0}>–</button>
                      <Mono>{picks[i]}</Mono>
                      <button onClick={() => setQty(i, picks[i] + 1)} disabled={picks[i] >= maxByLine(it)}>+</button>
                    </div>
                  </td>
                  <td style={{ textAlign: "right" }}><Mono>{money((it.price + (it.modPrice || 0)) * picks[i])}</Mono></td>
                </tr>
              ))}
            </tbody>
          </table>

          <div className="row" style={{ gap: 12, marginTop: 14, alignItems: "flex-end" }}>
            <label className="field" style={{ flex: 1 }}>
              <span className="field-label mono">Reason (optional)</span>
              <input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Wrong item, customer disliked, ..." />
            </label>
            <label className="field" style={{ flex: "0 0 200px" }}>
              <span className="field-label mono">Refund via</span>
              <select value={method} onChange={(e) => setMethod(e.target.value)}>
                <option value="cash">CASH</option>
                <option value="qris">QRIS</option>
                <option value="card">CARD</option>
              </select>
            </label>
          </div>

          <div className="due-row" style={{ marginTop: 16, fontSize: 16 }}>
            <span>{everything ? "Full refund" : "Partial refund"}</span>
            <Mono style={{ color: "var(--alert)", fontWeight: 600 }}>−{money(refundTotal)}</Mono>
          </div>
        </div>

        <footer className="sheet-foot">
          <button className="btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn-primary" disabled={nothing || alreadyRefunded}
            onClick={async () => {
              const items = lineItems
                .map((it, i) => picks[i] > 0 ? { ...it, qty: picks[i] } : null)
                .filter(Boolean)
                .map(({ _synthetic, ...rest }) => rest);
              await refundOrder(order, { items, reason, method });
              onClose();
            }}>
            Confirm refund
          </button>
        </footer>
      </div>
    </div>
  );
}

// Cashier receipts list — today's live orders (from the store) or past N days
// queried directly from Firestore on demand.
function ReceiptsListSheet({ onClose, onRefund }) {
  const { orders, db, showToast } = usePOS();
  const [days, setDays] = React.useState(0); // 0 = today (live), else past N days
  const [pastOrders, setPastOrders] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [detail, setDetail] = React.useState(null);

  React.useEffect(() => {
    if (days === 0) { setPastOrders([]); return; }
    let cancelled = false;
    setLoading(true);
    const to = dayKey();
    const fromDate = new Date(); fromDate.setDate(fromDate.getDate() - days);
    const from = dayKey(fromDate);
    db.collection("orders")
      .where("dateKey", ">=", from)
      .where("dateKey", "<=", to)
      .get()
      .then((s) => {
        if (cancelled) return;
        setPastOrders(s.docs.map((d) => ({ id: d.id, ...d.data() })));
        setLoading(false);
      })
      .catch(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [days]);

  const base = days === 0 ? orders : pastOrders;
  const list = base
    .filter((o) => o.paid !== false && o.status !== "refunded")
    .sort((a, b) => (b.createdAt?.seconds || 0) - (a.createdAt?.seconds || 0));

  const reprint = (o) => {
    if (!window.PRINTER) {
      showToast("Printer not configured");
      return;
    }
    PRINTER.receipt(o);
    showToast("Reprinted #" + o.shortId);
  };

  // Re-send a station ticket (kitchen / bar). PRINTER.kitchen/bar filter the
  // order's items by station internally, so a coffee-only order only ever
  // re-fires the bar ticket. Used to recover a lost station ticket without
  // reprinting the customer receipt.
  const reprintStation = (o, station) => {
    if (!window.PRINTER) {
      showToast("Printer not configured");
      return;
    }
    PRINTER[station](o);
    showToast((station === "kitchen" ? "Kitchen" : "Bar") + " ticket sent · #" + o.shortId);
  };

  const RANGES = [
    { d: 0,  l: "Today" },
    { d: 7,  l: "Last 7d" },
    { d: 30, l: "Last 30d" },
    { d: 90, l: "Last 90d" },
  ];

  return (
    <React.Fragment>
      <div className="sheet-wrap" onMouseDown={onClose}>
        <div className="sheet sheet-wide" onMouseDown={(e) => e.stopPropagation()}>
          <header className="sheet-head">
            <div>
              <div className="eyebrow mono">{days === 0 ? "TODAY'S RECEIPTS" : `RECEIPTS · LAST ${days} DAYS`}</div>
              <h3>Find an order to refund</h3>
            </div>
            <button className="icon-x" onClick={onClose}>×</button>
          </header>
          <div className="sheet-body">
            <div className="row" style={{ gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
              {RANGES.map((p) => (
                <button key={p.d}
                  className={"btn-ghost-sm" + (days === p.d ? " active" : "")}
                  onClick={() => setDays(p.d)}>{p.l}</button>
              ))}
            </div>
            {loading && <div className="muted mono">Loading…</div>}
            {!loading && list.length === 0 && (
              <div className="muted mono">No paid orders in this range.</div>
            )}
            {!loading && list.length > 0 && (
              <table className="data-table">
                <thead><tr><th>When</th><th>#</th><th>Customer</th><th>Table</th><th>Items</th><th>Payment</th><th>Total</th><th>Refunded</th><th></th></tr></thead>
                <tbody>
                  {list.map((o) => (
                    <tr key={o.id}>
                      <td><Mono>{o.createdAt?.toDate ? o.createdAt.toDate().toLocaleString("en-GB", { dateStyle: "short", timeStyle: "short" }) : "—"}</Mono></td>
                      <td><Mono>{o.shortId}</Mono></td>
                      <td>{o.customer}</td>
                      <td><Mono>{o.table}</Mono></td>
                      <td><Mono>{o.items.reduce((a, i) => a + i.qty, 0)}</Mono></td>
                      <td><Mono>{(o.paymentMethod || "—").toUpperCase()}</Mono></td>
                      <td><Mono>{money(o.total)}</Mono></td>
                      <td><Mono className={o.refundedAmount ? "stock-low" : "muted"}>{o.refundedAmount ? "−" + money(o.refundedAmount) : "—"}</Mono></td>
                      <td className="row-actions">
                        <button className="btn-ghost-sm" onClick={() => setDetail(o)}>Details</button>
                        <button className="btn-ghost-sm" onClick={() => reprint(o)}>Print</button>
                        {!o.refundedAmount && o.status !== "refunded"
                          ? <button className="btn-ghost-sm" onClick={() => onRefund(o)}>Refund</button>
                          : <span className="muted mono" style={{ fontSize: 12 }}>Refunded</span>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>
      {detail && (
        <OrderDetailSheet
          order={detail}
          onClose={() => setDetail(null)}
          onReprint={() => reprint(detail)}
          onPrintKitchen={() => reprintStation(detail, "kitchen")}
          onPrintBar={() => reprintStation(detail, "bar")}
          onRefund={() => { onRefund(detail); setDetail(null); }}
        />
      )}
    </React.Fragment>
  );
}

// Order detail viewer — full breakdown of an order, with Print / Refund actions.
function OrderDetailSheet({ order, onClose, onReprint, onPrintKitchen, onPrintBar, onRefund }) {
  const o = order;
  const subtotal = o.items.reduce((s, i) => s + (i.price + (i.modPrice || 0)) * i.qty, 0);
  // Match the station filters in PRINTER.kitchen/bar (js/printer.js): items
  // default to the kitchen, only items explicitly tagged "bar" go to the bar.
  const hasKitchen = (o.items || []).some((i) => (i.station || "kitchen") === "kitchen");
  const hasBar = (o.items || []).some((i) => i.station === "bar");
  const splits = (o.payments && o.payments.length)
    ? o.payments
    : (o.paymentMethod ? [{ method: o.paymentMethod, amount: o.total }] : []);

  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">ORDER · #{o.shortId}</div>
            <h3>{o.customer || "Walk-in"} · Table {o.table || "—"}</h3>
            <div className="muted mono" style={{ fontSize: 12 }}>
              {o.createdAt?.toDate ? o.createdAt.toDate().toLocaleString("en-GB", { timeZone: "Asia/Jakarta" }) + " WIB" : "—"}
              {o.cashierEmail && <span> · cashier {o.cashierEmail}</span>}
            </div>
          </div>
          <button className="icon-x" onClick={onClose}>×</button>
        </header>

        <div className="sheet-body">
          <table className="data-table">
            <thead>
              <tr><th>Qty</th><th>Item</th><th>Modifiers</th><th>Notes</th><th style={{ textAlign: "right" }}>Line total</th></tr>
            </thead>
            <tbody>
              {o.items.map((it, i) => (
                <tr key={i}>
                  <td><Mono>{it.qty}×</Mono></td>
                  <td>{it.name}{it.sku ? <span className="muted mono"> ({it.sku})</span> : null}</td>
                  <td className="mono muted">{(it.mods || []).join(" · ") || "—"}</td>
                  <td className="muted">{it.notes || "—"}</td>
                  <td style={{ textAlign: "right" }}><Mono>{money((it.price + (it.modPrice || 0)) * it.qty)}</Mono></td>
                </tr>
              ))}
            </tbody>
          </table>

          <div className="panel-card" style={{ marginTop: 16 }}>
            <div className="reco">
              <div className="reco-row"><span>Subtotal</span><Mono>{money(subtotal)}</Mono></div>
              {(o.depositApplied || 0) > 0 && (
                <div className="reco-row"><span>Deposit applied</span><Mono>−{money(o.depositApplied)}</Mono></div>
              )}
              {(o.uniqueCode || 0) > 0 && (
                <div className="reco-row"><span>Unique code (QRIS)</span><Mono>+{money(o.uniqueCode)}</Mono></div>
              )}
              {(o.tip || 0) > 0 && (
                <div className="reco-row"><span>Tip</span><Mono>{money(o.tip)}</Mono></div>
              )}
              <div className="reco-row reco-total"><span>TOTAL</span><Mono>{money(o.total)}</Mono></div>
              {(o.refundedAmount || 0) > 0 && (
                <div className="reco-row" style={{ color: "var(--alert)" }}>
                  <span>Already refunded</span><Mono>−{money(o.refundedAmount)}</Mono>
                </div>
              )}
            </div>
          </div>

          {splits.length > 0 && (
            <div className="panel-card" style={{ marginTop: 12 }}>
              <div className="eyebrow mono" style={{ marginBottom: 8 }}>PAYMENT{splits.length > 1 ? " (SPLIT)" : ""}</div>
              {splits.map((p, i) => (
                <div key={i} className="reco-row">
                  <span><Mono>{(p.method || "—").toUpperCase()}</Mono></span>
                  <Mono>{money(p.amount || 0)}</Mono>
                </div>
              ))}
            </div>
          )}
        </div>

        <footer className="sheet-foot">
          <button className="btn-ghost" onClick={onClose}>Close</button>
          <button className="btn-ghost" onClick={onReprint}>Print receipt</button>
          {hasKitchen && (
            <button className="btn-ghost" onClick={onPrintKitchen}>Print kitchen</button>
          )}
          {hasBar && (
            <button className="btn-ghost" onClick={onPrintBar}>Print bar</button>
          )}
          {!o.refundedAmount && o.status !== "refunded" && (
            <button className="btn-primary" onClick={onRefund}>Refund</button>
          )}
        </footer>
      </div>
    </div>
  );
}

Object.assign(window, { RefundSheet, ReceiptsListSheet, OrderDetailSheet });
