"use client";

// ─────────────────────────────────────────────────────────────────────────────
// POS v2 — clickable STATIC prototype (mock data, local state only).
// Zero coupling to the live POS: no API, no stores, no SignalR. Purpose: walk the
// full journey — table board → order → pay — on real devices before we wire it.
// Routes: /[locale]/pos2 (auth-guarded) · /[locale]/pos2-preview (dev, no login)
// ─────────────────────────────────────────────────────────────────────────────

import { useMemo, useState } from "react";
import {
  Search, Plus, Minus, Trash2, Send, CreditCard, Pause, SplitSquareHorizontal,
  X, WifiOff, ShoppingCart, Users, Coffee, ArrowRight, LayoutGrid, Armchair,
  Banknote, Check, Delete, Clock, ReceiptText, ShoppingBag,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { notify } from "@/lib/notify";
import { Can } from "@/components/auth/can";

type Item = { id: string; name: string; price: number; cat: string };
type Line = { item: Item; qty: number };

const CATEGORIES = [
  { id: "all", name: "همه" },
  { id: "coffee", name: "قهوه" },
  { id: "tea", name: "دمنوش" },
  { id: "cold", name: "نوشیدنی سرد" },
  { id: "food", name: "غذا" },
  { id: "dessert", name: "دسر" },
];

const ITEMS: Item[] = [
  { id: "1", name: "اسپرسو", price: 55000, cat: "coffee" },
  { id: "2", name: "آمریکانو", price: 65000, cat: "coffee" },
  { id: "3", name: "کاپوچینو", price: 85000, cat: "coffee" },
  { id: "4", name: "لاته", price: 92000, cat: "coffee" },
  { id: "5", name: "موکا", price: 98000, cat: "coffee" },
  { id: "6", name: "چای ماسالا", price: 72000, cat: "tea" },
  { id: "7", name: "دمنوش به‌لیمو", price: 68000, cat: "tea" },
  { id: "8", name: "آیس لاته", price: 105000, cat: "cold" },
  { id: "9", name: "فراپه کارامل", price: 135000, cat: "cold" },
  { id: "10", name: "لیموناد", price: 88000, cat: "cold" },
  { id: "11", name: "سالاد سزار", price: 185000, cat: "food" },
  { id: "12", name: "ساندویچ مرغ", price: 165000, cat: "food" },
  { id: "13", name: "پاستا آلفردو", price: 220000, cat: "food" },
  { id: "14", name: "چیزکیک", price: 145000, cat: "dessert" },
  { id: "15", name: "براونی", price: 120000, cat: "dessert" },
  { id: "16", name: "تیرامیسو", price: 155000, cat: "dessert" },
];

const fmt = (n: number) => n.toLocaleString("fa-IR");
const TAX = 0.09;
const TAKEAWAY = "to";

type Table = { id: string; name: string; seats: number };
const TABLES: Table[] = Array.from({ length: 12 }, (_, i) => ({
  id: String(i + 1),
  name: `میز ${fmt(i + 1)}`,
  seats: [2, 2, 4, 4, 2, 6, 4, 4, 2, 6, 8, 4][i],
}));

// Seeded "live" tables so the board looks real on open.
const SEED_ORDERS: Record<string, Line[]> = {
  "2": [{ item: ITEMS[2], qty: 2 }, { item: ITEMS[8], qty: 1 }],
  "5": [{ item: ITEMS[3], qty: 1 }, { item: ITEMS[10], qty: 1 }, { item: ITEMS[12], qty: 2 }],
  "8": [{ item: ITEMS[0], qty: 3 }, { item: ITEMS[13], qty: 1 }],
  "11": [{ item: ITEMS[1], qty: 4 }, { item: ITEMS[9], qty: 2 }, { item: ITEMS[15], qty: 2 }],
};
const SEED_META: Record<string, { guests: number; min: number }> = {
  "2": { guests: 2, min: 12 }, "5": { guests: 4, min: 35 },
  "8": { guests: 3, min: 48 }, "11": { guests: 7, min: 21 },
};
const SEED_BILL = ["8"];

const sumLines = (ls: Line[]) => ls.reduce((s, l) => s + l.qty * l.item.price, 0);

export function Pos2Prototype() {
  const [orders, setOrders] = useState<Record<string, Line[]>>(SEED_ORDERS);
  const [bill, setBill] = useState<string[]>(SEED_BILL);
  const [activeId, setActiveId] = useState<string | null>(null);

  // order-screen UI state
  const [cat, setCat] = useState("all");
  const [q, setQ] = useState("");
  const [cartOpen, setCartOpen] = useState(false);
  const [payOpen, setPayOpen] = useState(false);
  const [payInit, setPayInit] = useState<"cash" | "split">("cash");

  const isTakeaway = activeId === TAKEAWAY;
  const activeTable: Table | null = !activeId
    ? null
    : isTakeaway
      ? { id: TAKEAWAY, name: "بیرون‌بر", seats: 0 }
      : TABLES.find((t) => t.id === activeId) ?? null;

  const lines = (activeId && orders[activeId]) || [];
  const items = useMemo(
    () => ITEMS.filter((i) => (cat === "all" || i.cat === cat) && (q === "" || i.name.includes(q))),
    [cat, q],
  );
  const count = lines.reduce((s, l) => s + l.qty, 0);
  const subtotal = sumLines(lines);
  const tax = Math.round(subtotal * TAX);
  const total = subtotal + tax;

  const openTable = (id: string) => { setActiveId(id); setCat("all"); setQ(""); setCartOpen(false); };
  const backToBoard = () => { setActiveId(null); setPayOpen(false); setCartOpen(false); };

  const setLines = (fn: (ls: Line[]) => Line[]) =>
    setOrders((o) => ({ ...o, [activeId!]: fn(o[activeId!] ?? []) }));

  const add = (it: Item) =>
    setLines((ls) => {
      const e = ls.find((l) => l.item.id === it.id);
      return e
        ? ls.map((l) => (l.item.id === it.id ? { ...l, qty: l.qty + 1 } : l))
        : [...ls, { item: it, qty: 1 }];
    });
  const bump = (id: string, d: number) =>
    setLines((ls) => ls.flatMap((l) => (l.item.id === id ? (l.qty + d <= 0 ? [] : [{ ...l, qty: l.qty + d }]) : [l])));
  const remove = (id: string) => setLines((ls) => ls.filter((l) => l.item.id !== id));

  const send = () => {
    if (!count) return;
    notify.success(`سفارش ${activeTable?.name} به آشپزخانه ارسال شد (نمونه)`);
    setCartOpen(false);
  };
  const hold = () => { if (count) notify.success("سفارش نگه داشته شد (نمونه)"); };
  const openPay = (method: "cash" | "split") => { if (!count) return; setPayInit(method); setPayOpen(true); };

  const confirmPay = (method: "cash" | "card" | "split") => {
    const label = { cash: "پرداخت نقدی", card: "پرداخت با کارت", split: "پرداخت تقسیمی" }[method];
    notify.success(`${label} ${fmt(total)} تومان ثبت شد — ${activeTable?.name} (نمونه)`);
    setOrders((o) => { const n = { ...o }; delete n[activeId!]; return n; });
    setBill((b) => b.filter((x) => x !== activeId));
    backToBoard();
  };

  // ── TABLE BOARD (entry) ──────────────────────────────────────────────────
  if (!activeTable) {
    const occupied = TABLES.filter((t) => (orders[t.id]?.length ?? 0) > 0).length;
    return (
      <div dir="rtl" className="flex h-svh min-h-0 flex-col bg-background text-foreground">
        <header className="flex shrink-0 items-center gap-3 border-b border-border bg-card px-4 py-3">
          <div className="flex items-center gap-2 text-primary">
            <LayoutGrid className="size-6" />
            <span className="text-lg font-bold">میزها</span>
          </div>
          <span className="rounded-lg bg-muted px-2.5 py-1 text-sm text-muted-foreground">
            {fmt(occupied)} فعال · {fmt(TABLES.length - occupied)} خالی
          </span>
          <div className="flex-1" />
          <span className="flex items-center gap-1.5 rounded-lg bg-amber-100 px-2.5 py-1.5 text-xs font-medium text-amber-800">
            <WifiOff className="size-4" /> آفلاین
          </span>
          <button
            type="button"
            onClick={() => openTable(TAKEAWAY)}
            className="flex min-h-[44px] cursor-pointer items-center gap-2 rounded-xl bg-primary px-4 font-bold text-primary-foreground transition-colors hover:bg-primary/90 active:scale-[0.98]"
          >
            <ShoppingBag className="size-5" /> بیرون‌بر
          </button>
        </header>

        <div className="grid min-h-0 flex-1 auto-rows-min grid-cols-2 gap-3 overflow-y-auto p-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
          {TABLES.map((t) => {
            const ls = orders[t.id] ?? [];
            const busy = ls.length > 0;
            const billed = bill.includes(t.id);
            const meta = SEED_META[t.id];
            return (
              <button
                key={t.id}
                type="button"
                onClick={() => openTable(t.id)}
                className={cn(
                  "flex min-h-[124px] cursor-pointer flex-col justify-between rounded-2xl border-2 p-3 text-start transition-all hover:shadow-md active:scale-[0.97]",
                  billed
                    ? "border-amber-300 bg-amber-50"
                    : busy
                      ? "border-primary/40 bg-primary/5"
                      : "border-border bg-card hover:border-primary/40",
                )}
              >
                <div className="flex items-center justify-between">
                  <span className="text-lg font-extrabold">{t.name}</span>
                  <Armchair className={cn("size-5", busy ? "text-primary" : "text-muted-foreground/50")} />
                </div>
                <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                  <Users className="size-3.5" /> ظرفیت {fmt(t.seats)}
                </div>
                {busy ? (
                  <div className="space-y-1">
                    {billed && (
                      <span className="inline-flex items-center gap-1 rounded-md bg-amber-200/70 px-1.5 py-0.5 text-[11px] font-bold text-amber-900">
                        <ReceiptText className="size-3" /> صورتحساب
                      </span>
                    )}
                    <div className="flex items-center justify-between">
                      <span className="flex items-center gap-1 text-xs text-muted-foreground">
                        <Clock className="size-3.5" /> {fmt(meta?.min ?? 5)} دقیقه
                      </span>
                      <span className="text-sm font-extrabold text-primary">{fmt(sumLines(ls))}</span>
                    </div>
                  </div>
                ) : (
                  <span className="text-sm font-medium text-muted-foreground">خالی</span>
                )}
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  // ── ORDER SCREEN ─────────────────────────────────────────────────────────
  const guests = SEED_META[activeTable.id]?.guests;
  return (
    <div dir="rtl" className="flex h-svh min-h-0 flex-col bg-background text-foreground">
      <header className="flex shrink-0 items-center gap-3 border-b border-border bg-card px-3 py-2.5">
        <button
          type="button"
          onClick={backToBoard}
          className="flex min-h-[44px] cursor-pointer items-center gap-1.5 rounded-xl bg-muted px-3 font-medium text-muted-foreground transition-colors hover:bg-accent active:scale-95"
        >
          <ArrowRight className="size-5" /> <span className="hidden sm:inline">میزها</span>
        </button>
        <div className="flex items-center gap-2 rounded-xl bg-primary/10 px-3 py-1.5 text-primary">
          {isTakeaway ? <ShoppingBag className="size-5" /> : <Coffee className="size-5" />}
          <span className="font-bold">{activeTable.name}</span>
        </div>
        {!isTakeaway && guests != null && (
          <span className="hidden items-center gap-1.5 text-sm text-muted-foreground sm:flex">
            <Users className="size-4" /> {fmt(guests)} نفر
          </span>
        )}
        <div className="relative mx-1 flex-1">
          <Search className="pointer-events-none absolute end-3 top-1/2 size-5 -translate-y-1/2 text-muted-foreground" />
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="جستجوی آیتم…"
            className="h-11 w-full rounded-xl border border-border bg-background pe-10 ps-4 text-base outline-none focus:ring-2 focus:ring-primary/40"
          />
        </div>
        <span className="hidden items-center gap-1.5 rounded-lg bg-amber-100 px-2.5 py-1.5 text-xs font-medium text-amber-800 sm:flex">
          <WifiOff className="size-4" /> آفلاین
        </span>
      </header>

      <div className="flex min-h-0 flex-1">
        <main className="flex min-h-0 min-w-0 flex-1 flex-col">
          <div className="flex shrink-0 gap-2 overflow-x-auto border-b border-border px-4 py-2.5">
            {CATEGORIES.map((c) => (
              <button
                key={c.id}
                type="button"
                onClick={() => setCat(c.id)}
                className={cn(
                  "min-h-[44px] shrink-0 cursor-pointer rounded-full px-4 py-2.5 text-sm font-medium transition-colors",
                  cat === c.id ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-accent",
                )}
              >
                {c.name}
              </button>
            ))}
          </div>
          <div className="grid min-h-0 flex-1 auto-rows-min grid-cols-2 gap-3 overflow-y-auto p-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
            {items.map((it) => (
              <button
                key={it.id}
                type="button"
                onClick={() => add(it)}
                className="flex min-h-[104px] cursor-pointer flex-col justify-between rounded-2xl border border-border bg-card p-3 text-start shadow-sm transition-all hover:border-primary hover:shadow-md active:scale-[0.97]"
              >
                <div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
                  <Coffee className="size-5" />
                </div>
                <div>
                  <p className="line-clamp-1 font-semibold">{it.name}</p>
                  <p className="mt-0.5 text-sm font-bold text-primary">{fmt(it.price)}</p>
                </div>
              </button>
            ))}
            {items.length === 0 && (
              <p className="col-span-full py-10 text-center text-muted-foreground">آیتمی یافت نشد</p>
            )}
          </div>
        </main>

        <aside className="hidden w-[360px] shrink-0 border-s border-border bg-card lg:flex lg:flex-col">
          <Ticket
            lines={lines} subtotal={subtotal} tax={tax} total={total} count={count}
            onBump={bump} onRemove={remove} onSend={send} onHold={hold}
            onPay={() => openPay("cash")} onSplit={() => openPay("split")}
          />
        </aside>
      </div>

      {count > 0 && (
        <button
          type="button"
          onClick={() => setCartOpen(true)}
          className="flex shrink-0 cursor-pointer items-center justify-between gap-3 bg-primary px-4 py-3 text-primary-foreground lg:hidden"
        >
          <span className="flex items-center gap-2 font-bold">
            <ShoppingCart className="size-5" />
            <span className="flex size-6 items-center justify-center rounded-full bg-white/25 text-sm">{fmt(count)}</span>
            مشاهده سفارش
          </span>
          <span className="text-lg font-extrabold">{fmt(total)} تومان</span>
        </button>
      )}

      {cartOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-black/40" onClick={() => setCartOpen(false)} />
          <div className="absolute inset-y-0 end-0 flex w-full max-w-sm flex-col bg-card shadow-xl" dir="rtl">
            <div className="flex items-center justify-between border-b border-border px-4 py-3">
              <span className="font-bold">سفارش {activeTable.name}</span>
              <button type="button" onClick={() => setCartOpen(false)} className="rounded-lg p-2 hover:bg-accent">
                <X className="size-5" />
              </button>
            </div>
            <Ticket
              lines={lines} subtotal={subtotal} tax={tax} total={total} count={count}
              onBump={bump} onRemove={remove} onSend={send} onHold={hold}
              onPay={() => openPay("cash")} onSplit={() => openPay("split")}
            />
          </div>
        </div>
      )}

      {payOpen && (
        <PaySheet
          tableName={activeTable.name}
          total={total}
          guests={guests}
          initialMethod={payInit}
          onClose={() => setPayOpen(false)}
          onConfirm={confirmPay}
        />
      )}
    </div>
  );
}

// ── Order ticket ─────────────────────────────────────────────────────────────
function Ticket({
  lines, subtotal, tax, total, count, onBump, onRemove, onSend, onHold, onPay, onSplit,
}: {
  lines: Line[]; subtotal: number; tax: number; total: number; count: number;
  onBump: (id: string, d: number) => void; onRemove: (id: string) => void;
  onSend: () => void; onHold: () => void; onPay: () => void; onSplit: () => void;
}) {
  return (
    <div className="flex min-h-0 flex-1 flex-col">
      <div className="min-h-0 flex-1 overflow-y-auto p-3">
        {lines.length === 0 ? (
          <div className="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
            <ShoppingCart className="size-10 opacity-40" />
            <p>سبد خالی است</p>
            <p className="text-xs">برای افزودن، روی آیتم‌ها بزنید</p>
          </div>
        ) : (
          <ul className="space-y-2">
            {lines.map((l) => (
              <li key={l.item.id} className="flex items-center gap-2 rounded-xl border border-border/70 p-2">
                <div className="min-w-0 flex-1">
                  <p className="line-clamp-1 font-medium">{l.item.name}</p>
                  <p className="text-xs text-muted-foreground">{fmt(l.item.price)} تومان</p>
                </div>
                <div className="flex items-center gap-1">
                  <button type="button" onClick={() => onBump(l.item.id, -1)} className="flex size-11 items-center justify-center rounded-lg bg-muted hover:bg-accent active:scale-95" aria-label="کم">
                    <Minus className="size-4" />
                  </button>
                  <span className="w-7 text-center font-bold">{fmt(l.qty)}</span>
                  <button type="button" onClick={() => onBump(l.item.id, 1)} className="flex size-11 items-center justify-center rounded-lg bg-primary/10 text-primary hover:bg-primary/20 active:scale-95" aria-label="زیاد">
                    <Plus className="size-4" />
                  </button>
                </div>
                <button type="button" onClick={() => onRemove(l.item.id)} className="flex size-9 items-center justify-center rounded-lg text-red-500 hover:bg-red-50" aria-label="حذف">
                  <Trash2 className="size-4" />
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>

      <div className="space-y-1 border-t border-border px-4 py-3 text-sm">
        <Row label="جمع" value={`${fmt(subtotal)} تومان`} />
        <Row label="مالیات ۹٪" value={`${fmt(tax)} تومان`} />
        <div className="flex items-center justify-between pt-1 text-lg font-extrabold">
          <span>مبلغ کل</span>
          <span className="text-primary">{fmt(total)} تومان</span>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-2 border-t border-border p-3">
        <button type="button" disabled={!count} onClick={onSend}
          className="flex min-h-[56px] items-center justify-center gap-2 rounded-xl bg-primary text-base font-bold text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-40 active:scale-[0.98]">
          <Send className="size-5" /> ارسال
        </button>
        <Can permission="HandlePayments">
          <button type="button" disabled={!count} onClick={onPay}
            className="flex min-h-[56px] items-center justify-center gap-2 rounded-xl border-2 border-primary text-base font-bold text-primary transition-colors hover:bg-primary/10 disabled:opacity-40 active:scale-[0.98]">
            <CreditCard className="size-5" /> پرداخت
          </button>
        </Can>
        <button type="button" disabled={!count} onClick={onHold}
          className="flex min-h-[48px] items-center justify-center gap-1.5 rounded-xl bg-muted text-sm font-medium text-muted-foreground hover:bg-accent disabled:opacity-40">
          <Pause className="size-4" /> نگه‌داشتن
        </button>
        <Can permission="HandlePayments">
          <button type="button" disabled={!count} onClick={onSplit}
            className="flex min-h-[48px] items-center justify-center gap-1.5 rounded-xl bg-muted text-sm font-medium text-muted-foreground hover:bg-accent disabled:opacity-40">
            <SplitSquareHorizontal className="size-4" /> تقسیم
          </button>
        </Can>
      </div>
    </div>
  );
}

// ── Payment sheet (cash / card / split + numpad + change) ────────────────────
function PaySheet({
  tableName, total, guests, initialMethod, onClose, onConfirm,
}: {
  tableName: string; total: number; guests?: number;
  initialMethod: "cash" | "split";
  onClose: () => void;
  onConfirm: (method: "cash" | "card" | "split") => void;
}) {
  const [method, setMethod] = useState<"cash" | "card" | "split">(initialMethod);
  const [recv, setRecv] = useState("");
  const [splitN, setSplitN] = useState(Math.min(Math.max(guests ?? 2, 2), 6));

  const received = Number(recv || 0);
  const change = received - total;
  const press = (d: string) => setRecv((r) => (r + d).replace(/^0+(?=\d)/, "").slice(0, 12));
  const backspace = () => setRecv((r) => r.slice(0, -1));
  const roundUp = (step: number) => Math.ceil(total / step) * step;
  const perPerson = Math.ceil(total / splitN / 1000) * 1000;
  const canConfirm = method === "cash" ? received >= total : true;

  const TABS = [
    { id: "cash", name: "نقدی", icon: Banknote },
    { id: "card", name: "کارت", icon: CreditCard },
    { id: "split", name: "تقسیم", icon: SplitSquareHorizontal },
  ] as const;

  return (
    <div dir="rtl" className="fixed inset-0 z-[60] flex items-stretch justify-center sm:items-center sm:p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative flex w-full flex-col bg-card shadow-2xl sm:max-w-md sm:rounded-2xl">
        {/* header */}
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <div>
            <p className="text-xs text-muted-foreground">پرداخت — {tableName}</p>
            <p className="text-xl font-extrabold text-primary">{fmt(total)} تومان</p>
          </div>
          <button type="button" onClick={onClose} className="rounded-lg p-2 hover:bg-accent" aria-label="بستن">
            <X className="size-5" />
          </button>
        </div>

        {/* method tabs */}
        <div className="grid grid-cols-3 gap-2 p-3">
          {TABS.map((t) => (
            <button
              key={t.id}
              type="button"
              onClick={() => setMethod(t.id)}
              className={cn(
                "flex min-h-[52px] cursor-pointer flex-col items-center justify-center gap-1 rounded-xl border-2 text-sm font-bold transition-colors",
                method === t.id ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-accent",
              )}
            >
              <t.icon className="size-5" /> {t.name}
            </button>
          ))}
        </div>

        <div className="min-h-0 flex-1 overflow-y-auto px-3 pb-3">
          {/* CASH */}
          {method === "cash" && (
            <div className="space-y-3">
              <div className="rounded-xl bg-muted/60 p-3">
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>دریافتی</span>
                  <span className="text-lg font-extrabold text-foreground">{fmt(received)} تومان</span>
                </div>
                <div className="mt-1 flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">{change >= 0 ? "باقی‌مانده (بازگشت)" : "کسری پرداخت"}</span>
                  <span className={cn("text-lg font-extrabold", change >= 0 ? "text-emerald-600" : "text-red-500")}>
                    {fmt(Math.abs(change))} تومان
                  </span>
                </div>
              </div>

              <div className="flex flex-wrap gap-2">
                <Chip onClick={() => setRecv(String(total))}>مبلغ دقیق</Chip>
                <Chip onClick={() => setRecv(String(roundUp(50000)))}>{fmt(roundUp(50000))}</Chip>
                <Chip onClick={() => setRecv(String(roundUp(100000)))}>{fmt(roundUp(100000))}</Chip>
                <Chip onClick={() => setRecv(String(roundUp(500000))) }>{fmt(roundUp(500000))}</Chip>
              </div>

              <div className="grid grid-cols-3 gap-2">
                {["7", "8", "9", "4", "5", "6", "1", "2", "3"].map((d) => (
                  <Key key={d} onClick={() => press(d)}>{fmt(Number(d))}</Key>
                ))}
                <Key onClick={() => press("000")}>۰۰۰</Key>
                <Key onClick={() => press("0")}>۰</Key>
                <Key onClick={backspace} aria-label="حذف"><Delete className="size-5" /></Key>
              </div>
            </div>
          )}

          {/* CARD */}
          {method === "card" && (
            <div className="flex flex-col items-center gap-3 py-6 text-center">
              <div className="flex size-16 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <CreditCard className="size-8" />
              </div>
              <p className="font-medium">مبلغ روی دستگاه کارت‌خوان ارسال می‌شود</p>
              <p className="text-2xl font-extrabold text-primary">{fmt(total)} تومان</p>
              <p className="text-sm text-muted-foreground">پس از تأیید تراکنش، دکمهٔ زیر را بزنید (نمونه)</p>
            </div>
          )}

          {/* SPLIT */}
          {method === "split" && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-muted-foreground">تقسیم بین</span>
                <div className="flex items-center gap-2">
                  {[2, 3, 4, 5, 6].map((n) => (
                    <button
                      key={n}
                      type="button"
                      onClick={() => setSplitN(n)}
                      className={cn(
                        "size-11 cursor-pointer rounded-xl border-2 font-bold transition-colors",
                        splitN === n ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-accent",
                      )}
                    >
                      {fmt(n)}
                    </button>
                  ))}
                </div>
              </div>
              <div className="rounded-xl bg-muted/60 p-3 text-center">
                <p className="text-sm text-muted-foreground">سهم هر نفر</p>
                <p className="text-2xl font-extrabold text-primary">{fmt(perPerson)} تومان</p>
              </div>
              <ul className="space-y-2">
                {Array.from({ length: splitN }, (_, i) => (
                  <li key={i} className="flex items-center justify-between rounded-xl border border-border/70 px-3 py-2.5">
                    <span className="flex items-center gap-2 font-medium">
                      <span className="flex size-7 items-center justify-center rounded-full bg-primary/10 text-sm font-bold text-primary">{fmt(i + 1)}</span>
                      نفر {fmt(i + 1)}
                    </span>
                    <span className="font-bold">{fmt(perPerson)} تومان</span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>

        {/* confirm */}
        <div className="border-t border-border p-3">
          <button
            type="button"
            disabled={!canConfirm}
            onClick={() => onConfirm(method)}
            className="flex min-h-[56px] w-full items-center justify-center gap-2 rounded-xl bg-primary text-lg font-extrabold text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-40 active:scale-[0.99]"
          >
            <Check className="size-6" />
            {method === "cash" && change >= 0
              ? `تأیید — بازگشت ${fmt(change)}`
              : `تأیید پرداخت ${fmt(total)} تومان`}
          </button>
        </div>
      </div>
    </div>
  );
}

function Key({ children, onClick, ...rest }: { children: React.ReactNode; onClick: () => void } & React.ButtonHTMLAttributes<HTMLButtonElement>) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex min-h-[56px] cursor-pointer items-center justify-center rounded-xl bg-muted text-xl font-bold transition-colors hover:bg-accent active:scale-95"
      {...rest}
    >
      {children}
    </button>
  );
}

function Chip({ children, onClick }: { children: React.ReactNode; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="cursor-pointer rounded-full border border-border bg-background px-3 py-2 text-sm font-medium transition-colors hover:border-primary hover:text-primary active:scale-95"
    >
      {children}
    </button>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between text-muted-foreground">
      <span>{label}</span>
      <span>{value}</span>
    </div>
  );
}
