// Cashier shift management — opening float count + close-out reconciliation.

function ShiftOpenSheet({ onConfirm }) {
  const [v, setV] = React.useState("");
  return (
    <div className="sheet-wrap" onMouseDown={() => {}}>
      <div className="sheet" onMouseDown={(e) => e.stopPropagation()}>
        <header className="sheet-head">
          <div>
            <div className="eyebrow mono">START OF SHIFT</div>
            <h3>Count the cash drawer</h3>
          </div>
        </header>
        <div className="sheet-body">
          <p className="muted">
            Enter the cash amount in the drawer right now. This is your opening
            float — we'll compare it against your closing count at end of shift.
          </p>
          <label className="field" style={{ marginTop: 14 }}>
            <span className="field-label mono">Opening cash (Rp)</span>
            <input type="number" inputMode="numeric" autoFocus value={v}
              onChange={(e) => setV(e.target.value.replace(/\D/g, ""))}
              placeholder="500000" />
          </label>
          <div className="muted mono" style={{ fontSize: 12, marginTop: 6 }}>
            Tip: count carefully. You'll be asked to count again at close.
          </div>
        </div>
        <footer className="sheet-foot">
          <button className="btn-primary" disabled={!v}
            onClick={() => onConfirm({ openingCash: Number(v) || 0 })}>
            Start shift
          </button>
        </footer>
      </div>
    </div>
  );
}

function ShiftCloseSheet({ shift, orders, onClose, onConfirm }) {
  const { db } = usePOS();
  const [counted, setCounted] = React.useState("");
  const [cashRefunds, setCashRefunds] = React.useState(0);
  const cashier = shift.cashierUid;

  // Pull cash refunds today for this cashier
  React.useEffect(() => {
    const today = new Date().toISOString().slice(0, 10);
    db.collection("refunds")
      .where("cashierUid", "==", cashier)
      .where("dateKey", "==", today)
      .where("method", "==", "cash").get()
      .then((s) => setCashRefunds(s.docs.reduce((a, d) => a + (d.data().total || 0), 0)));
  }, [cashier]);

  // Sum of cash payment received today by this cashier, on paid orders.
  const cashSales = orders
    .filter((o) => o.paid && o.cashierUid === cashier)
    .reduce((s, o) => {
      const splits = o.payments && o.payments.length ? o.payments : [{ method: o.paymentMethod, amount: o.total }];
      return s + splits.filter((p) => p.method === "cash").reduce((a, p) => a + (Number(p.amount) || 0), 0);
    }, 0);
  const expected = (shift.openingCash || 0) + cashSales - cashRefunds;
  const variance = (Number(counted) || 0) - expected;
  const ordersToday = orders.filter((o) => o.cashierUid === cashier && o.paid).length;

  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">END OF SHIFT</div>
            <h3>Cash drawer reconciliation</h3>
          </div>
          <button className="icon-x" onClick={onClose}>×</button>
        </header>
        <div className="sheet-body">
          <div className="panel-card" style={{ background: "var(--paper)", border: "1px solid var(--line)" }}>
            <div className="reco">
              <div className="reco-row"><span>Opening float</span><Mono>{money(shift.openingCash || 0)}</Mono></div>
              <div className="reco-row"><span>Cash sales · {ordersToday} orders</span><Mono>+{money(cashSales)}</Mono></div>
              {cashRefunds > 0 && <div className="reco-row"><span>Cash refunds</span><Mono>−{money(cashRefunds)}</Mono></div>}
              <div className="reco-row reco-total"><span>Expected in drawer</span><Mono>{money(expected)}</Mono></div>
            </div>
          </div>

          <label className="field" style={{ marginTop: 18 }}>
            <span className="field-label mono">Counted now (Rp)</span>
            <input type="number" inputMode="numeric" autoFocus value={counted}
              onChange={(e) => setCounted(e.target.value.replace(/\D/g, ""))}
              placeholder={String(expected)} />
          </label>

          {counted !== "" && (
            <div className={"variance-pill " + (variance === 0 ? "ok" : variance > 0 ? "over" : "short")}>
              <span>Variance</span>
              <Mono>{variance >= 0 ? "+" : "−"}{money(Math.abs(variance))}</Mono>
              <span className="muted mono" style={{ fontSize: 12 }}>
                {variance === 0 ? "Balanced" : variance > 0 ? "Over (extra cash)" : "Short"}
              </span>
            </div>
          )}
        </div>
        <footer className="sheet-foot">
          <button className="btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn-primary" disabled={counted === ""}
            onClick={() => onConfirm({
              closingCash: Number(counted) || 0,
              expectedCash: expected, cashSales, refunds: cashRefunds,
            })}>
            Close shift
          </button>
        </footer>
      </div>
    </div>
  );
}

Object.assign(window, { ShiftOpenSheet, ShiftCloseSheet });
