/* Sweet Haven — "My orders": order history saved on this device */

// Orders live in this browser's localStorage — no account needed. Only what's
// needed to show the history is kept (no email/phone). Every access is guarded
// because storage can be blocked (private mode, strict browser settings).
const SH_ORDERS_KEY = "sh-orders";
const SH_ORDERS_MAX = 50;

const shOrders = {
  load() {
    try {
      const list = JSON.parse(localStorage.getItem(SH_ORDERS_KEY) || "[]");
      return Array.isArray(list) ? list : [];
    } catch (e) {
      return [];
    }
  },
  save(order) {
    const record = {
      ref: order.ref,
      placedAt: new Date().toISOString(),
      method: order.method,
      date: order.date || null,
      time: order.time || null,
      total: order.total,
      paid: !!order.paid,
      items: (order.entries || []).map((e) => ({ name: e.p.name, opt: e.opt || null, qty: e.qty, price: e.price })),
    };
    try {
      // Newest first; a re-save of the same reference replaces the old copy.
      const rest = shOrders.load().filter((o) => o.ref !== record.ref);
      localStorage.setItem(SH_ORDERS_KEY, JSON.stringify([record, ...rest].slice(0, SH_ORDERS_MAX)));
    } catch (e) { /* storage unavailable — the order still went through */ }
  },
};

function OrderHistory({ onNav }) {
  const [orders] = React.useState(() => shOrders.load());

  if (orders.length === 0) {
    return (
      <div className="sh-page">
        <div className="sh-empty-page">
          <Icon name="receipt" size={34} stroke={1.4} />
          <h2 className="sh-section-title">No orders yet</h2>
          <p>Orders you place on this device will show up here.</p>
          <button className="sh-btn primary" onClick={() => onNav("Menu")}>Browse the menu</button>
        </div>
      </div>
    );
  }

  return (
    <div className="sh-page sh-history">
      <div className="sh-overline"><span className="sh-rule" />Saved on this device</div>
      <h1 className="sh-page-title">My orders</h1>
      <p className="sh-page-lede">Your past orders from this phone or browser. Clearing your browser data will clear this list.</p>

      <div className="sh-history-list">
        {orders.map((o) => {
          const placed = new Date(o.placedAt);
          const when = o.date ? dpLabel(dpParse(o.date)) : null;
          return (
            <article className="sh-history-card" key={o.ref + o.placedAt}>
              <div className="sh-history-head">
                <div>
                  <span className="sh-confirm-k">Order</span>
                  <span className="sh-history-ref">{o.ref}</span>
                </div>
                <span className="sh-history-status">{o.paid ? "Paid" : "Pending"}</span>
              </div>
              <div className="sh-history-meta">
                <span>Placed {placed.toLocaleDateString("en-NG", { day: "numeric", month: "short", year: "numeric" })}</span>
                <span>{o.method === "delivery" ? "Delivery" : "Pickup"}{when ? " · " + when : ""}{o.time ? " · " + o.time : ""}</span>
              </div>
              <div className="sh-order-lines">
                {o.items.map((it, i) => (
                  <div className="sh-order-line" key={i}>
                    <span className="sh-order-qty">{it.qty}×</span>
                    <span className="sh-order-name">{it.name}{it.opt && <em>{it.opt}</em>}</span>
                    <span className="sh-order-price">{money(it.price * it.qty)}</span>
                  </div>
                ))}
              </div>
              <div className="sh-history-total"><span>Total</span><span className="sh-price">{money(o.total)}</span></div>
            </article>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { shOrders, OrderHistory });
