"use client";

/**
 * NewOrderSheet — keyboard-first staff order creation.
 *
 * Keyboard flow:
 *   Step 1 (Customer):  Enter in phone → lookup; Tab through fields; Enter in last field → next step
 *   Step 2 (Type):      D / C to toggle type; Enter in time → next step; Enter in empty addr → next step
 *   Step 3 (Items):     ItemCodeInput handles all item entry (see that component for flow)
 *   Step 4 (Payment):   C/A/P to select method; Enter → create order
 *   Any step:           Escape = back one step
 */

import { useCallback, useEffect, useRef, useState } from "react";

import {
  ChevronLeft,
  ChevronRight,
  Minus,
  Plus,
  Search,
  Trash2,
  User,
  X,
} from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import type { MasterAddress } from "@/lib/order/master-addresses";
import { searchMasterAddresses } from "@/lib/order/master-addresses";
import type { Order, OrderItem, OrderType, PaymentMethod } from "@/lib/order/types";
import { useOrdersStore } from "@/stores/orders/orders-store";
import { ItemCodeInput } from "./item-code-input";

type Step = "customer" | "type" | "items" | "payment";

interface CartItem extends OrderItem { _id: string; }
interface NewOrderSheetProps { open: boolean; onClose: () => void; onCreated?: (orderId: string) => void; }

const STEPS: Step[] = ["customer", "type", "items", "payment"];
const STEP_LABELS: Record<Step, string> = {
  customer: "Customer", type: "Type & Address", items: "Items", payment: "Payment",
};
const PAYMENT_KEYS: Record<string, PaymentMethod> = { c: "cash", a: "card", p: "paylink" };

export function NewOrderSheet({ open, onClose, onCreated }: NewOrderSheetProps) {
  const orders = useOrdersStore((s) => s.orders);
  const [step, setStep] = useState<Step>("customer");

  // ── Customer ────────────────────────────────────────────────────────────────
  const [phone, setPhone]             = useState("");
  const [customerName, setCustomerName] = useState("");
  // Live customer suggestions (always shown on customer step)
  const [custHighlight, setCustHighlight] = useState(0);

  // ── Type + address ────────────────────────────────────────────────────────
  const [orderType, setOrderType]           = useState<OrderType>("delivery");
  const [addrQuery, setAddrQuery]           = useState("");
  const [addrResults, setAddrResults]       = useState<MasterAddress[]>([]);
  const [selectedAddress, setSelectedAddress] = useState<MasterAddress | null>(null);
  const [requestedTime, setRequestedTime]   = useState("");
  const [addrHighlight, setAddrHighlight]   = useState(0);
  const [platformRef, setPlatformRef]       = useState(""); // pn: only for D/U/J orders
  const [deliveryNote, setDeliveryNote]     = useState(""); // per-order note
  const [orderSource, setOrderSource] = useState<"direct" | "deliveroo" | "ubereats" | "justeat" | "kiosk">("direct");

  // ── Items ────────────────────────────────────────────────────────────────
  const [cart, setCart] = useState<CartItem[]>([]);

  // ── Payment ────────────────────────────────────────────────────────────────
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>("cash");

  const phoneRef = useRef<HTMLInputElement>(null);
  const timeRef  = useRef<HTMLInputElement>(null);
  const addrRef  = useRef<HTMLInputElement>(null);

  // ── Reset on open ────────────────────────────────────────────────────────
  useEffect(() => {
    if (!open) return;
    setStep("customer");
    setPhone(""); setCustomerName("");
    setOrderType("delivery"); setAddrQuery(""); setAddrResults([]); setSelectedAddress(null); setRequestedTime(""); setPlatformRef(""); setDeliveryNote(""); setOrderSource("direct");
    setAddrHighlight(0);
    setCustHighlight(0);
    setCart([]);
    setPaymentMethod("cash");
    setTimeout(() => phoneRef.current?.focus(), 100);
  }, [open]);

  // ── Auto-focus first field of each step ─────────────────────────────────
  useEffect(() => {
    if (step === "customer") setTimeout(() => phoneRef.current?.focus(), 100);
    if (step === "type")     setTimeout(() => timeRef.current?.focus(), 100);
    if (step === "type" && orderType === "delivery") setTimeout(() => addrRef.current?.focus(), 120);
  }, [step, orderType]);

  const goNext = useCallback(() => {
    const idx = STEPS.indexOf(step);
    if (idx < STEPS.length - 1) setStep(STEPS[idx + 1]);
  }, [step]);

  const goBack = useCallback(() => {
    const idx = STEPS.indexOf(step);
    if (idx > 0) setStep(STEPS[idx - 1]);
  }, [step]);

  const canNext = () => {
    if (step === "customer") return phone.trim().length >= 10;
    if (step === "type") {
      if (orderSource === "kiosk") return true;
      if (["deliveroo", "ubereats", "justeat"].includes(orderSource)) return platformRef.trim().length > 0;
      return orderType === "collection" || !!selectedAddress;
    }
    if (step === "items")    return cart.length > 0;
    return true;
  };

  // ── Customer suggestions — derived directly, no extra state ─────────────
  const normPhone = (n: string) => {
    const d = n.replace(/\D/g, "");
    if (d.startsWith("44")) return d.slice(2);
    if (d.startsWith("0"))  return d.slice(1);
    return d;
  };

  const allCustomers: CustomerSuggestion[] = (() => {
    const seen = new Set<string>();
    return [...orders]
      .sort((a, b) => new Date(b.orderedAt).getTime() - new Date(a.orderedAt).getTime())
      .flatMap((o) => {
        if (seen.has(o.customer.mo)) return [];
        seen.add(o.customer.mo);
        return [{ mo: o.customer.mo, na: o.customer.na, ph: o.customer.ph, pn: o.customer.pn, cn: o.customer.cn, address: o.address, orderCount: orders.filter((x) => x.customer.mo === o.customer.mo).length }];
      });
  })();

  const pq = normPhone(phone);
  const nq = customerName.trim().toLowerCase();
  const custSuggestions: CustomerSuggestion[] = (() => {
    if (pq.length > 0) return allCustomers.filter((c) => normPhone(c.mo).includes(pq)).slice(0, 6);
    if (nq.length > 0) return allCustomers.filter((c) => c.na.toLowerCase().includes(nq)).slice(0, 6);
    return allCustomers.slice(0, 5);
  })();

  const applySuggestion = (c: CustomerSuggestion) => {
    setPhone(c.mo);
    setCustomerName(c.na);
    if (c.address) { setAddrQuery(c.address.ad); setSelectedAddress(c.address as MasterAddress); }
    // Carry customer note forward as delivery note (editable at step 2)
    if (c.cn) setDeliveryNote(c.cn);
    setCustHighlight(0);
  };

  // ── Phone lookup ──────────────────────────────────────────────────────────
  const lookupPhone = () => {
    const norm = phone.replace(/\s/g, "");
    if (norm.length < 10) return;
    const history = orders
      .filter((o) => o.customer.mo === norm || o.customer.mo === `+44${norm.slice(1)}`)
      .sort((a, b) => new Date(b.orderedAt).getTime() - new Date(a.orderedAt).getTime());
    if (history.length === 0) return;
    const c = history[0].customer;
    setCustomerName(c.na);
    if (c.cn) setDeliveryNote(c.cn);
    if (history[0].address) {
      setAddrQuery(history[0].address.ad);
      setSelectedAddress(history[0].address as MasterAddress);
    }
    toast.success(`Found: ${c.na} · ${history.length} order${history.length !== 1 ? "s" : ""}`);
  };

  // ── Address search ────────────────────────────────────────────────────────
  const handleAddrSearch = (q: string) => {
    setAddrQuery(q);
    setSelectedAddress(null);
    setAddrHighlight(0);
    setAddrResults(q.trim().length >= 2 ? searchMasterAddresses(q) : []);
  };

  const selectAddress = (r: MasterAddress) => {
    setSelectedAddress(r);
    setAddrQuery(r.ad);
    setAddrResults([]);
    if (r.linkedCustomers?.[0] && !customerName) {
      setCustomerName(r.linkedCustomers[0].na);
      if (!phone) setPhone(r.linkedCustomers[0].mo);
    }
  };

  // ── Cart helpers ──────────────────────────────────────────────────────────
  const addToCart = (item: OrderItem) => {
    setCart((prev) => {
      const existing = prev.find((c) => c.code === item.code && (c.notes ?? "") === (item.notes ?? ""));
      if (existing) return prev.map((c) => c._id === existing._id ? { ...c, qty: c.qty + item.qty } : c);
      return [...prev, { ...item, _id: `${item.code}-${Date.now()}` }];
    });
  };
  const removeItem  = (id: string) => setCart((p) => p.filter((c) => c._id !== id));
  const changeQty   = (id: string, delta: number) =>
    setCart((p) => p.map((c) => c._id === id ? { ...c, qty: Math.max(1, c.qty + delta) } : c));

  // ── Costs ─────────────────────────────────────────────────────────────────
  const subtotal    = cart.reduce((acc, i) => acc + i.unitPrice * i.qty, 0);
  const deliveryFee = orderType === "delivery" ? ((selectedAddress?.miles ?? 0) < 2 ? 2.5 : (selectedAddress?.miles ?? 0) < 3 ? 3.5 : 5.0) : 0;
  const total       = subtotal + deliveryFee;

  // ── Submit ────────────────────────────────────────────────────────────────
  const handleSubmit = () => {
    if (cart.length === 0)                              { toast.error("Add at least one item"); return; }
    if (!phone.trim())                                  { toast.error("Phone number required"); return; }
    if (orderType === "delivery" && !selectedAddress)   { toast.error("Select a delivery address"); return; }

    const now    = new Date();
    const yy     = String(now.getFullYear()).slice(2);
    const mm     = String(now.getMonth() + 1).padStart(2, "0");
    const dd     = String(now.getDate()).padStart(2, "0");
    const count  = orders.filter((o) => o.id.startsWith(`${yy}${mm}${dd}`)).length;
    const isPlatform = ["deliveroo", "ubereats", "justeat"].includes(orderSource);
    const suffix: Order["suffix"] =
      orderSource === "deliveroo" ? "D" :
      orderSource === "ubereats"  ? "U" :
      orderSource === "justeat"   ? "J" :
      orderSource === "kiosk"     ? "K" :
      paymentMethod === "card"    ? "C" :
      paymentMethod === "paylink" ? "L" : "S";
    const newId  = `${yy}${mm}${dd}-${String(count + 1).padStart(3, "0")}${suffix}`;

    let requestedAt: string;
    if (requestedTime) {
      const [h, m] = requestedTime.split(":").map(Number);
      const d = new Date(now);
      d.setHours(h, m, 0, 0);
      if (d < now) d.setDate(d.getDate() + 1);
      requestedAt = d.toISOString();
    } else {
      requestedAt = new Date(now.getTime() + 45 * 60_000).toISOString();
    }

    const newOrder: Order = {
      id: newId,
      type: orderType,
      suffix,
      stage: "confirmed",
      orderedAt: now.toISOString(),
      requestedAt,
      customer: {
        na: customerName || "Walk-in",
        mo: phone.replace(/\s/g, ""),
        pn: platformRef.trim() || undefined,
        lifetimeSpend: 0,
        lifetimeOrders: 0,
      },
      customerMessage: deliveryNote.trim() || undefined,
      address: orderType === "delivery" && selectedAddress ? {
        ad: selectedAddress.ad,
        sb: selectedAddress.sb,
        an: selectedAddress.an,
        ge: selectedAddress.ge,
        miles: selectedAddress.miles,
      } : undefined,
      items: cart.map(({ _id: _, ...rest }) => rest),
      charges: {
        subtotal: Math.round(subtotal * 100) / 100,
        deliveryFee: orderType === "delivery" ? deliveryFee : undefined,
        total: Math.round(total * 100) / 100,
        paymentMethod: isPlatform ? "card" : paymentMethod,
        paymentStatus: isPlatform || paymentMethod === "card" ? "paid" : "unpaid",
      },
      events: [
        { at: now.toISOString(), actor: "foh:staff", type: "order_created", label: "Order created by staff" },
      ],
    };

    useOrdersStore.setState((s) => {
      const updated = [...s.orders, newOrder];
      try { localStorage.setItem("orderos_orders", JSON.stringify(updated)); } catch {}
      return { orders: updated };
    });

    toast.success(`Order ${newId} created · £${total.toFixed(2)}`);
    onCreated?.(newId);
    onClose();
  };

  const stepIdx = STEPS.indexOf(step);

  // ── Global keyboard shortcuts for this sheet ──────────────────────────────
  const handleSheetKeyDown = (e: React.KeyboardEvent) => {
    // Escape = go back one step (or close if on first)
    if (e.key === "Escape" && step !== "customer") { e.stopPropagation(); goBack(); return; }
    // Payment step: C=cash, A=card, P=paylink; Enter=submit
    if (step === "payment") {
      const pm = PAYMENT_KEYS[e.key.toLowerCase()];
      if (pm) { setPaymentMethod(pm); return; }
      if (e.key === "Enter") { handleSubmit(); return; }
    }
  };

  return (
    <Sheet open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
      <SheetContent
        side="right"
        className="w-full max-w-sm p-0 flex flex-col overflow-hidden sm:max-w-sm"
        onKeyDown={handleSheetKeyDown}
      >
        {/* ── Header ──────────────────────────────────────────────────────── */}
        <SheetHeader className="shrink-0 border-b bg-primary px-4 py-3">
          <div className="flex items-center justify-between">
            <SheetTitle className="text-primary-foreground text-base">New Order</SheetTitle>
            <button type="button" onClick={onClose} className="text-primary-foreground/70 hover:text-primary-foreground">
              <X className="size-4" />
            </button>
          </div>
          <div className="flex items-center gap-1.5 mt-1">
            {STEPS.map((s, i) => (
              <button
                key={s}
                type="button"
                onClick={() => i < stepIdx && setStep(s)}
                className={`rounded-full px-2.5 py-0.5 text-[10px] font-semibold transition-colors ${
                  s === step ? "bg-white text-primary"
                  : i < stepIdx ? "bg-white/30 text-primary-foreground cursor-pointer hover:bg-white/40"
                  : "bg-white/10 text-primary-foreground/40 cursor-default"
                }`}
              >
                {i + 1}. {STEP_LABELS[s]}
              </button>
            ))}
          </div>
        </SheetHeader>

        {/* ── Body ────────────────────────────────────────────────────────── */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4">

          {/* ── Step 1: Customer ────────────────────────────────────────── */}
          {step === "customer" && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">Type phone or name — matching customers appear instantly.</p>

              {/* Matching customers — always visible, filters as you type */}
              {step === "customer" && custSuggestions.length > 0 && (
                <CustomerDropdown
                  suggestions={custSuggestions}
                  highlight={custHighlight}
                  label={pq.length === 0 && nq.length === 0 ? "Recent customers" : "Matching customers"}
                  onSelect={applySuggestion}
                  onHighlight={setCustHighlight}
                />
              )}

              {/* Phone */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">mo: Mobile *</label>
                <Input
                  ref={phoneRef}
                  className="mt-1"
                  type="tel"
                  placeholder="+447xxx or 07xxx…"
                  value={phone}
                  onChange={(e) => { setPhone(e.target.value); setCustHighlight(0); }}
                  onKeyDown={(e) => {
                    if (e.key === "ArrowDown") { e.preventDefault(); setCustHighlight((h) => Math.min(h + 1, custSuggestions.length - 1)); }
                    if (e.key === "ArrowUp")   { e.preventDefault(); setCustHighlight((h) => Math.max(h - 1, 0)); }
                    if (e.key === "Enter" && custSuggestions.length > 0) { e.preventDefault(); applySuggestion(custSuggestions[custHighlight]); }
                  }}
                />
              </div>

              {/* Name */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">na: Name</label>
                <Input
                  className="mt-1"
                  placeholder="Customer name"
                  value={customerName}
                  onChange={(e) => { setCustomerName(e.target.value); setCustHighlight(0); }}
                  onKeyDown={(e) => {
                    if (e.key === "ArrowDown") { e.preventDefault(); setCustHighlight((h) => Math.min(h + 1, custSuggestions.length - 1)); }
                    if (e.key === "ArrowUp")   { e.preventDefault(); setCustHighlight((h) => Math.max(h - 1, 0)); }
                    if (e.key === "Enter" && custSuggestions.length > 0) { e.preventDefault(); applySuggestion(custSuggestions[custHighlight]); }
                  }}
                />
              </div>

              <p className="text-[11px] text-muted-foreground/60">Enter phone to auto-fill known customer · min 10 digits to continue</p>
            </div>
          )}

          {/* ── Step 2: Type + Address ──────────────────────────────────── */}
          {step === "type" && (
            <div className="space-y-4">
              {/* Order Source */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Order Source</label>
                <div className="mt-2 grid grid-cols-5 gap-1.5">
                  {([
                    { value: "direct",    label: "Direct",    icon: "🏠" },
                    { value: "deliveroo", label: "Deliveroo", icon: "🟣" },
                    { value: "ubereats",  label: "UberEats",  icon: "🟢" },
                    { value: "justeat",   label: "JustEat",   icon: "🟠" },
                    { value: "kiosk",     label: "Kiosk",     icon: "🖥️" },
                  ] as const).map(({ value, label, icon }) => (
                    <button
                      key={value}
                      type="button"
                      onClick={() => {
                        setOrderSource(value);
                        if (value === "kiosk") setOrderType("collection");
                        if (value !== "direct" && value !== "kiosk") setOrderType("delivery");
                      }}
                      className={`rounded-lg border-2 p-1.5 text-center text-[10px] font-bold leading-tight transition-colors ${
                        orderSource === value ? "border-primary bg-primary/5 text-primary" : "border-border text-muted-foreground"
                      }`}
                    >
                      <div className="text-sm mb-0.5">{icon}</div>
                      {label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Order type — direct orders only */}
              {orderSource === "direct" && (
                <div>
                  <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Order Type</label>
                  <div className="grid grid-cols-2 gap-2 mt-2">
                    {(["delivery", "collection"] as OrderType[]).map((t) => (
                      <button
                        key={t}
                        type="button"
                        onClick={() => setOrderType(t)}
                        className={`rounded-lg border-2 p-3 text-center text-sm font-semibold capitalize transition-colors ${
                          orderType === t ? "border-primary bg-primary/5 text-primary" : "border-border text-muted-foreground"
                        }`}
                      >
                        {t === "delivery" ? "🚚 Delivery" : "🏪 Collection"}
                      </button>
                    ))}
                  </div>
                </div>
              )}
              {orderSource === "kiosk" && (
                <div className="rounded-lg border-2 border-primary bg-primary/5 px-3 py-2.5 text-center text-sm font-semibold text-primary">
                  🖥️ Kiosk — In-Store Collection
                </div>
              )}

              {/* Requested time */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Ready / Requested time</label>
                <Input
                  ref={timeRef}
                  type="time"
                  className="mt-1"
                  value={requestedTime}
                  onChange={(e) => setRequestedTime(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      if (orderType === "collection") { goNext(); return; }
                      addrRef.current?.focus();
                    }
                  }}
                />
                <p className="mt-1 text-[11px] text-muted-foreground">Leave blank for +45 min default</p>
              </div>

              {/* Address (delivery only, direct orders) */}
              {orderType === "delivery" && orderSource === "direct" && (
                <div className="space-y-2">
                  <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">sb: Address search</label>
                  <div>
                    <div className="flex items-center gap-1.5 rounded border border-primary/30 bg-primary/5 px-2 py-1.5">
                      <Search className="size-3.5 text-muted-foreground shrink-0" />
                      <input
                        ref={addrRef}
                        type="text"
                        value={addrQuery}
                        onChange={(e) => handleAddrSearch(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === "ArrowDown") { e.preventDefault(); setAddrHighlight((h) => Math.min(h + 1, addrResults.length - 1)); }
                          if (e.key === "ArrowUp")   { e.preventDefault(); setAddrHighlight((h) => Math.max(h - 1, 0)); }
                          if (e.key === "Enter") {
                            if (addrResults.length > 0) { e.preventDefault(); selectAddress(addrResults[addrHighlight]); }
                            else if (selectedAddress) goNext();
                          }
                        }}
                        placeholder="Type postcode fragment (e.g. RG12 or 128AP)…"
                        className="flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground/60"
                      />
                      {addrQuery && (
                        <button type="button" onClick={() => { setAddrQuery(""); setAddrResults([]); setSelectedAddress(null); }}>
                          <X className="size-3.5 text-muted-foreground" />
                        </button>
                      )}
                    </div>

                    {addrResults.length > 0 && (
                      <div className="mt-1 rounded-lg border bg-popover shadow-md overflow-hidden">
                        {addrResults.map((r, i) => (
                          <button
                            key={r.id}
                            type="button"
                            onMouseDown={(e) => { e.preventDefault(); selectAddress(r); }}
                            className={`flex w-full flex-col gap-0.5 border-b px-3 py-2 text-left last:border-0 transition-colors ${i === addrHighlight ? "bg-primary/10" : "hover:bg-muted/50"}`}
                          >
                            {r.sb && <span className="font-mono text-[10px] text-primary">{r.sb}</span>}
                            <span className="text-[12px] font-medium leading-tight">{r.ad}</span>
                            {r.linkedCustomers && r.linkedCustomers.length > 0 && (
                              <span className="flex items-center gap-1 text-[11px] text-muted-foreground">
                                <User className="size-2.5" />
                                {r.linkedCustomers.map((c) => c.na).join(", ")}
                              </span>
                            )}
                            {r.miles !== undefined && (
                              <span className="text-[10px] text-muted-foreground">{r.miles} mi · est. £{r.miles < 2 ? "2.50" : r.miles < 3 ? "3.50" : "5.00"}</span>
                            )}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>

                  {selectedAddress && (
                    <div className="rounded bg-primary/5 border border-primary/20 px-3 py-2 text-[12px]">
                      <p className="font-medium">{selectedAddress.ad}</p>
                      {selectedAddress.an && <p className="text-muted-foreground">{selectedAddress.an}</p>}
                      <p className="text-muted-foreground">{selectedAddress.miles} mi · Delivery fee: £{(selectedAddress.miles ?? 0) < 2 ? "2.50" : (selectedAddress.miles ?? 0) < 3 ? "3.50" : "5.00"}</p>
                    </div>
                  )}
                </div>
              )}

              {/* Platform ref — required for D/U/J */}
              {["deliveroo", "ubereats", "justeat"].includes(orderSource) && (
                <div>
                  <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    {orderSource === "deliveroo" ? "Deliveroo" : orderSource === "ubereats" ? "UberEats" : "JustEat"} Order Ref *
                  </label>
                  <Input
                    className="mt-1 font-mono"
                    placeholder={orderSource === "deliveroo" ? "e.g. D-8823" : orderSource === "ubereats" ? "e.g. U-4491" : "e.g. J-1234AB"}
                    value={platformRef}
                    onChange={(e) => setPlatformRef(e.target.value)}
                    autoFocus
                  />
                  <p className="mt-1 text-[11px] text-muted-foreground font-mono">
                    Platform phone:{" "}
                    <span className="text-foreground font-semibold select-all">
                      {orderSource === "deliveroo" ? "+44 20 3319 5035" : orderSource === "ubereats" ? "+44 1388 436844" : "+7 533 006 408"}
                    </span>
                  </p>
                </div>
              )}

              {/* Delivery / order note */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Delivery note / special instruction</label>
                <textarea
                  className="mt-1 w-full rounded-md border px-3 py-2 text-[13px] resize-none outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 bg-background"
                  rows={2}
                  placeholder="e.g. Don't ring bell, leave at door, ring on arrival…"
                  value={deliveryNote}
                  onChange={(e) => setDeliveryNote(e.target.value)}
                />
              </div>

              <p className="text-[11px] text-muted-foreground/60">
                {["deliveroo", "ubereats", "justeat"].includes(orderSource)
                  ? "Enter platform ref → proceed"
                  : orderType === "collection" || orderSource === "kiosk"
                  ? "Enter time → proceed"
                  : "Select address → proceed"}
              </p>
            </div>
          )}

          {/* ── Step 3: Items ───────────────────────────────────────────── */}
          {step === "items" && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">
                Type code or name, ↑↓ to select, Enter adds. Empty code + Enter = done.
              </p>

              <ItemCodeInput
                onAdd={addToCart}
                onDone={goNext}
                cartSize={cart.length}
                autoFocus
              />

              {/* Cart */}
              {cart.length > 0 && (
                <div className="space-y-1">
                  <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Cart ({cart.length} line{cart.length !== 1 ? "s" : ""})
                  </p>
                  {cart.map((item) => (
                    <div key={item._id} className="flex items-center gap-2 rounded border bg-card px-2 py-1.5">
                      <span className="w-8 shrink-0 font-mono text-[10px] text-muted-foreground">{item.code}</span>
                      <div className="flex-1 min-w-0">
                        <p className="truncate text-[12px] font-medium">{item.description}</p>
                        {item.notes && <p className="text-[11px] font-bold text-amber-700">{item.notes}</p>}
                      </div>
                      <div className="flex items-center gap-1 shrink-0">
                        <button type="button" onClick={() => changeQty(item._id, -1)} className="rounded p-0.5 hover:bg-muted">
                          <Minus className="size-3" />
                        </button>
                        <span className="w-5 text-center text-xs font-bold">{item.qty}</span>
                        <button type="button" onClick={() => changeQty(item._id, 1)} className="rounded p-0.5 hover:bg-muted">
                          <Plus className="size-3" />
                        </button>
                      </div>
                      <span className="w-12 text-right text-[12px] tabular-nums">£{(item.unitPrice * item.qty).toFixed(2)}</span>
                      <button type="button" onClick={() => removeItem(item._id)} className="text-destructive/60 hover:text-destructive">
                        <Trash2 className="size-3.5" />
                      </button>
                    </div>
                  ))}
                  <div className="flex justify-between border-t pt-1.5 text-sm font-bold">
                    <span>Subtotal</span>
                    <span>£{subtotal.toFixed(2)}</span>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* ── Step 4: Payment ─────────────────────────────────────────── */}
          {step === "payment" && (
            <div className="space-y-4">
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                  Payment Method <span className="normal-case font-normal">(C=cash, A=card, P=paylink · Enter=create)</span>
                </label>
                <div className="mt-2 grid grid-cols-3 gap-2">
                  {(["cash", "card", "paylink"] as PaymentMethod[]).map((m) => (
                    <button
                      key={m}
                      type="button"
                      onClick={() => setPaymentMethod(m)}
                      className={`rounded-lg border-2 py-2.5 text-center text-xs font-bold uppercase transition-colors ${
                        paymentMethod === m ? "border-primary bg-primary/5 text-primary" : "border-border text-muted-foreground"
                      }`}
                    >
                      {m === "cash" ? "💵 CASH" : m === "card" ? "💳 CARD" : "🔗 PAY\u2011LINK"}
                    </button>
                  ))}
                </div>
              </div>

              {/* Order summary */}
              <div className="rounded-lg border bg-muted/20 p-3 space-y-1 text-sm">
                <p className="font-semibold mb-2">Order Summary</p>
                {cart.map((item) => (
                  <div key={item._id} className="flex justify-between text-[12px]">
                    <span className="text-muted-foreground">{item.description} ×{item.qty}</span>
                    <span>£{(item.unitPrice * item.qty).toFixed(2)}</span>
                  </div>
                ))}
                <div className="border-t pt-1 mt-1 space-y-0.5">
                  <div className="flex justify-between text-[12px] text-muted-foreground">
                    <span>Subtotal</span><span>£{subtotal.toFixed(2)}</span>
                  </div>
                  {orderType === "delivery" && (
                    <div className="flex justify-between text-[12px] text-muted-foreground">
                      <span>Delivery</span><span>£{deliveryFee.toFixed(2)}</span>
                    </div>
                  )}
                  <div className="flex justify-between font-bold text-base">
                    <span>Total</span><span>£{total.toFixed(2)}</span>
                  </div>
                </div>
                <div className="pt-1 text-[11px] text-muted-foreground space-y-0.5">
                  <p><span className="font-mono">mo:</span> {phone} {customerName && `· ${customerName}`}</p>
                  {orderType === "delivery" && selectedAddress && (
                    <p className="truncate"><span className="font-mono">ad:</span> {selectedAddress.ad}</p>
                  )}
                  <p><span className="font-mono">type:</span> {orderType} · <span className="font-mono">pay:</span> {paymentMethod}</p>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* ── Footer navigation ─────────────────────────────────────────── */}
        <div className="shrink-0 border-t bg-card p-3 flex items-center gap-2">
          {stepIdx > 0 && (
            <Button variant="outline" size="sm" className="gap-1" onClick={goBack}>
              <ChevronLeft className="size-3.5" /> Back
            </Button>
          )}
          <div className="flex-1" />
          {step === "payment" || (step === "items" && ["deliveroo", "ubereats", "justeat"].includes(orderSource)) ? (
            <Button size="sm" className="gap-1 bg-green-600 hover:bg-green-700 text-white" onClick={handleSubmit}>
              Create Order · £{total.toFixed(2)}
            </Button>
          ) : (
            <Button size="sm" className="gap-1" disabled={!canNext()} onClick={goNext}>
              Next <ChevronRight className="size-3.5" />
            </Button>
          )}
        </div>
      </SheetContent>
    </Sheet>
  );
}

// ── Shared customer suggestions dropdown ─────────────────────────────────────
interface CustomerSuggestion {
  mo: string; na: string; orderCount: number;
  ph?: string; pn?: string; cn?: string; lastAt?: string;
  address?: { ad: string; sb?: string; an?: string; ge?: string; miles?: number } | undefined;
}
interface CustomerDropdownProps {
  suggestions: CustomerSuggestion[];
  highlight: number;
  label?: string;
  onSelect: (c: CustomerSuggestion) => void;
  onHighlight?: (i: number) => void;
}

function CustomerDropdown({ suggestions, highlight, label, onSelect, onHighlight }: CustomerDropdownProps) {
  return (
    <div className="rounded-lg border bg-card shadow-sm overflow-hidden">
      {label && (
        <div className="border-b bg-muted/40 px-3 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
          {label} — click or ↑↓ Enter
        </div>
      )}
      {suggestions.map((c, i) => (
        <button
          key={c.mo}
          type="button"
          onClick={() => onSelect(c)}
          onMouseEnter={() => onHighlight?.(i)}
          className={`flex w-full items-start gap-3 border-b px-3 py-2 text-left last:border-0 transition-colors ${i === highlight ? "bg-primary/10" : "hover:bg-muted/40"}`}
        >
          <User className={`size-3.5 mt-0.5 shrink-0 ${i === highlight ? "text-primary" : "text-muted-foreground"}`} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <span className="font-semibold text-[13px]">{c.na}</span>
              <span className="text-[11px] text-muted-foreground">{c.orderCount} order{c.orderCount !== 1 ? "s" : ""}</span>
            </div>
            <span className="font-mono text-[11px] text-muted-foreground">{c.mo}</span>
            {c.address && (
              <p className="truncate text-[11px] text-muted-foreground/70">{c.address.ad}</p>
            )}
          </div>
        </button>
      ))}
    </div>
  );
}
