"use client"

import * as React from "react"
import {
  IconRotateClockwise,
  IconSearch,
  IconSettings,
  IconShoppingCart,
} from "@tabler/icons-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import Link from "next/link"

import { CustomerQuickAddSheet } from "@/components/customers/customer-quick-add-sheet"
import { downloadInvoicePdf } from "@/components/invoices/invoice-pdf-button"
import { PosCartPanel } from "@/components/pos/pos-cart-panel"
import { applyPosDiscount } from "@/components/pos/pos-cart-checkout"
import { PosCatalogTabs } from "@/components/pos/pos-catalog-tabs"
import { PosCustomerSelect } from "@/components/pos/pos-customer-select"
import { PosInvoicePanel } from "@/components/pos/pos-invoice-panel"
import { PosReturnPanel } from "@/components/pos/pos-return-panel"
import { PosProductCard } from "@/components/pos/pos-product-card"
import { SearchInput } from "@/components/ui/search-input"
import { useCustomers } from "@/context/customers-context"
import { useOrders } from "@/context/orders-context"
import { usePosSettings } from "@/context/pos-settings-context"
import { catalogGridClass } from "@/lib/pos-settings"
import { useProducts } from "@/context/products-context"
import { useReturns } from "@/context/returns-context"
import { confirmPosSaleAction, confirmReturnAction } from "@/lib/confirm-action"
import { formatMoney } from "@/lib/customers"
import { type OrderRow } from "@/lib/orders"
import {
  isPosReturn,
  nextReturnNumber,
  type ReturnRow,
} from "@/lib/returns"
import {
  cartLineTotal,
  cartSubtotal,
  computePosTotals,
  isPosOrder,
  nextPosInvoiceNumber,
  posCatalogProducts,
  posReturnCatalogProducts,
  type PosCartLine,
} from "@/lib/pos"
import type { CustomerRow } from "@/lib/customers"
import type { ProductRow } from "@/lib/products"
import { cn } from "@/lib/utils"
import { apiPosCheckout, apiPosReturn } from "@/lib/api/business"
import { ApiClientError } from "@/lib/api/client"
import { mapApiOrderToRow, mapApiReturnToRow, resolveDefaultStoreId } from "@/lib/pos-api"
import { emitProductsChanged } from "@/lib/inventory-product-rows"

function formatPosMoney(value: string) {
  return formatMoney(value)
}

function formatPosReturnMoney(value: string) {
  const amount = Number(value)
  if (!Number.isFinite(amount) || Math.abs(amount) < 0.005) {
    return formatPosMoney("0.00")
  }
  return `−${formatPosMoney(Math.abs(amount).toFixed(2))}`
}

const WALK_IN_CUSTOMER_ID = "walk-in"
const RETURN_MAX_QTY = 9999

const panelClass =
  "rounded-xl bg-card shadow-sm shadow-black/[0.04] ring-1 ring-border/40"

const searchInputClass =
  "h-10 rounded-full text-sm shadow-sm focus-visible:ring-0 focus-visible:ring-offset-0 hover:ring-0 focus:ring-0 focus:outline-none sm:h-9"

export function PosTerminal() {
  const { t } = useTranslation("pos")
  const { products, getProduct, getApiProductId, refreshProducts } = useProducts()
  const { customers } = useCustomers()
  const { orders, addOrder } = useOrders()
  const { returns, addReturn } = useReturns()
  const { settings, hydrated, storeId: settingsStoreId } = usePosSettings()
  const searchInputRef = React.useRef<HTMLInputElement>(null)

  const [mode, setMode] = React.useState<"sale" | "return">("sale")
  const [mobilePane, setMobilePane] = React.useState<"catalog" | "cart">("catalog")
  const [search, setSearch] = React.useState("")
  const [brand, setBrand] = React.useState<string>("all")
  const [cart, setCart] = React.useState<PosCartLine[]>([])
  const [selectedProductId, setSelectedProductId] = React.useState<number | null>(null)
  const [discountAmount, setDiscountAmount] = React.useState("0.00")
  const [discountDraft, setDiscountDraft] = React.useState("")
  const [customerId, setCustomerId] = React.useState(WALK_IN_CUSTOMER_ID)
  const [customerQuickAddOpen, setCustomerQuickAddOpen] = React.useState(false)
  const [paymentMethod, setPaymentMethod] =
    React.useState<OrderRow["paymentMethod"]>("Cash")
  const [documentStatus, setDocumentStatus] =
    React.useState<OrderRow["status"]>("completed")
  const [lastSale, setLastSale] = React.useState<OrderRow | null>(null)
  const [lastReturn, setLastReturn] = React.useState<ReturnRow | null>(null)
  const [processing, setProcessing] = React.useState(false)
  const [paidAmountDraft, setPaidAmountDraft] = React.useState("")

  const isSale = mode === "sale"

  React.useEffect(() => {
    if (!hydrated) return
    setMode(settings.defaultRegisterMode)
    setPaymentMethod(settings.defaultPaymentMethod)
    setDocumentStatus(
      settings.defaultRegisterMode === "sale"
        ? settings.defaultSaleStatus
        : settings.defaultReturnStatus
    )
  }, [hydrated, settings.defaultPaymentMethod, settings.defaultRegisterMode, settings.defaultReturnStatus, settings.defaultSaleStatus])

  const catalog = React.useMemo(
    () =>
      isSale
        ? posCatalogProducts(products, {
            hideOutOfStock: settings.hideOutOfStockOnSale,
          })
        : posReturnCatalogProducts(products),
    [isSale, products, settings.hideOutOfStockOnSale]
  )

  const customerName = React.useMemo(() => {
    if (customerId === WALK_IN_CUSTOMER_ID) return t("walkIn")
    const customer = customers.find((item) => String(item.id) === customerId)
    return customer?.name ?? t("walkIn")
  }, [customerId, customers, t])

  const customerOptions = React.useMemo(
    () => [
      { value: WALK_IN_CUSTOMER_ID, label: t("walkIn"), description: t("noCustomerRecord") },
      ...customers.map((customer) => ({
        value: String(customer.id),
        label: customer.name,
        description: customer.phone !== "—" ? customer.phone : customer.description,
      })),
    ],
    [customers, t]
  )

  const cartQtyByProductId = React.useMemo(() => {
    const map = new Map<number, number>()
    for (const line of cart) {
      map.set(line.productId, line.quantity)
    }
    return map
  }, [cart])

  const brands = React.useMemo(() => {
    const set = new Set(
      catalog
        .map((product) => product.brand)
        .filter((name) => Boolean(name) && name !== "—")
    )
    return ["all", ...Array.from(set).sort()]
  }, [catalog])

  const filteredProducts = React.useMemo(() => {
    const query = search.trim().toLowerCase()
    return catalog.filter((product) => {
      if (brand !== "all" && product.brand !== brand) return false
      if (!query) return true
      return (
        product.name.toLowerCase().includes(query) ||
        product.sku.toLowerCase().includes(query) ||
        product.brand.toLowerCase().includes(query) ||
        product.category.toLowerCase().includes(query)
      )
    })
  }, [brand, catalog, search])

  const subtotal = React.useMemo(() => cartSubtotal(cart), [cart])
  const checkoutTotals = React.useMemo(
    () => computePosTotals(subtotal, discountAmount),
    [discountAmount, subtotal]
  )

  React.useEffect(() => {
    if (settings.allowPartialPayment && isSale) {
      setPaidAmountDraft(checkoutTotals.total)
    }
  }, [checkoutTotals.total, isSale, settings.allowPartialPayment])

  const posOrders = React.useMemo(() => {
    return orders
      .filter(isPosOrder)
      .sort((a, b) => {
        const dateCompare = b.orderDate.localeCompare(a.orderDate)
        if (dateCompare !== 0) return dateCompare
        return b.id - a.id
      })
  }, [orders])

  const nextInvoice = React.useMemo(
    () => nextPosInvoiceNumber(orders, settings.receiptPrefix),
    [orders, settings.receiptPrefix]
  )

  const lastCreatedInvoice = posOrders[0] ?? null

  const nextReturn = React.useMemo(
    () => nextReturnNumber(returns, "sales"),
    [returns]
  )

  const posReturns = React.useMemo(() => {
    return returns
      .filter(isPosReturn)
      .sort((a, b) => {
        const dateCompare = b.returnDate.localeCompare(a.returnDate)
        if (dateCompare !== 0) return dateCompare
        return b.id - a.id
      })
  }, [returns])

  const lastCreatedReturn = posReturns[0] ?? null

  const formatRegisterMoney = isSale ? formatPosMoney : formatPosReturnMoney

  const addToCart = React.useCallback(
    (product: ProductRow) => {
      if (isSale) {
        const canOversell = settings.allowOverselling
        if (!canOversell && product.stock <= 0) {
          toast.error(t("toasts.outOfStock", { name: product.name }))
          return
        }

        const maxStock = canOversell ? RETURN_MAX_QTY : product.stock

        setCart((prev) => {
          const existing = prev.find((line) => line.productId === product.id)
          if (existing) {
            if (!canOversell && existing.quantity >= product.stock) {
              toast.error(t("toasts.onlyInStock", { count: product.stock, name: product.name }))
              return prev
            }
            return prev.map((line) =>
              line.productId === product.id
                ? { ...line, quantity: line.quantity + 1, maxStock }
                : line
            )
          }
          return [
            ...prev,
            {
              productId: product.id,
              productName: product.name,
              sku: product.sku,
              quantity: 1,
              unitPrice: product.salePrice,
              maxStock,
            },
          ]
        })
      } else {
        setCart((prev) => {
          const existing = prev.find((line) => line.productId === product.id)
          if (existing) {
            return prev.map((line) =>
              line.productId === product.id
                ? {
                    ...line,
                    quantity: line.quantity + 1,
                    maxStock: RETURN_MAX_QTY,
                  }
                : line
            )
          }
          return [
            ...prev,
            {
              productId: product.id,
              productName: product.name,
              sku: product.sku,
              quantity: 1,
              unitPrice: product.salePrice,
              maxStock: RETURN_MAX_QTY,
            },
          ]
        })
      }
      setSelectedProductId(product.id)
    },
    [isSale, settings.allowOverselling, t]
  )

  const setLineQuantity = React.useCallback(
    (productId: number, quantity: number) => {
      setCart((prev) =>
        prev
          .map((line) => {
            if (line.productId !== productId) return line
            if (quantity <= 0) return null
            if (
              isSale &&
              !settings.allowOverselling &&
              quantity > line.maxStock
            ) {
              toast.error(t("toasts.onlyInStockGeneric", { count: line.maxStock }))
              return line
            }
            return { ...line, quantity }
          })
          .filter((line): line is PosCartLine => line !== null)
      )
    },
    [isSale, settings.allowOverselling, t]
  )

  const setLineFinalPrice = React.useCallback(
    (productId: number, finalLineTotal: string | undefined) => {
      if (!settings.allowLinePriceEdit) return
      setCart((prev) =>
        prev.map((line) =>
          line.productId === productId ? { ...line, finalLineTotal } : line
        )
      )
    },
    [settings.allowLinePriceEdit]
  )

  const removeFromCart = React.useCallback((productId: number) => {
    setCart((prev) => {
      const next = prev.filter((line) => line.productId !== productId)
      setSelectedProductId((current) => {
        if (current !== productId) return current
        return next[next.length - 1]?.productId ?? null
      })
      return next
    })
  }, [])

  const clearCart = React.useCallback(() => {
    setCart([])
    setSelectedProductId(null)
    setDiscountAmount("0.00")
    setDiscountDraft("")
  }, [])

  const clearCustomer = React.useCallback(() => {
    setCustomerId(WALK_IN_CUSTOMER_ID)
  }, [])

  const resetRegister = React.useCallback(() => {
    setCart([])
    setSelectedProductId(null)
    setDiscountAmount("0.00")
    setDiscountDraft("")
    setCustomerId(WALK_IN_CUSTOMER_ID)
    setPaymentMethod(settings.defaultPaymentMethod)
    setDocumentStatus(
      isSale ? settings.defaultSaleStatus : settings.defaultReturnStatus
    )
    setPaidAmountDraft("")
    setMobilePane("catalog")
  }, [
    isSale,
    settings.defaultPaymentMethod,
    settings.defaultReturnStatus,
    settings.defaultSaleStatus,
  ])

  const switchMode = React.useCallback(
    (nextMode: "sale" | "return") => {
      if (nextMode === mode) return
      clearCart()
      setSearch("")
      setBrand("all")
      setMobilePane("catalog")
      setDocumentStatus(
        nextMode === "sale"
          ? settings.defaultSaleStatus
          : settings.defaultReturnStatus
      )
      setMode(nextMode)
    },
    [
      clearCart,
      mode,
      settings.defaultReturnStatus,
      settings.defaultSaleStatus,
    ]
  )

  const cartItemCount = React.useMemo(
    () => cart.reduce((sum, line) => sum + line.quantity, 0),
    [cart]
  )

  const applyDiscount = React.useCallback(() => {
    let applied = applyPosDiscount(subtotal, discountDraft)
    if (settings.maxDiscountPercent > 0) {
      const cap =
        Number(subtotal) * (settings.maxDiscountPercent / 100)
      applied = Math.min(Number(applied), cap).toFixed(2)
    }
    setDiscountAmount(applied)
    setDiscountDraft(applied === "0.00" ? "" : applied)
  }, [discountDraft, settings.maxDiscountPercent, subtotal])

  const clearDiscount = React.useCallback(() => {
    setDiscountAmount("0.00")
    setDiscountDraft("")
  }, [])

  const handleCustomerCreated = React.useCallback((customer: CustomerRow) => {
    setCustomerId(String(customer.id))
  }, [])

  const resolveStoreId = React.useCallback(async () => {
    if (settingsStoreId) return settingsStoreId
    return resolveDefaultStoreId()
  }, [settingsStoreId])

  const buildCheckoutLines = React.useCallback(() => {
    const lines: {
      productId: string
      productName: string
      sku: string
      quantity: number
      unitPrice: number
    }[] = []
    for (const line of cart) {
      const apiId = getApiProductId(line.productId)
      if (!apiId) {
        throw new Error(`Product "${line.productName}" is not synced. Refresh inventory and try again.`)
      }
      const lineTotal = Number(cartLineTotal(line))
      const unitPrice =
        line.quantity > 0 ? lineTotal / line.quantity : Number(line.unitPrice) || 0
      lines.push({
        productId: apiId,
        productName: line.productName,
        sku: line.sku,
        quantity: line.quantity,
        unitPrice: Number(unitPrice.toFixed(2)),
      })
    }
    return lines
  }, [cart, getApiProductId])

  const completeSale = React.useCallback(async () => {
    if (cart.length === 0) {
      toast.error(t("toasts.addProduct"))
      return
    }

    if (settings.requireCustomer && customerId === WALK_IN_CUSTOMER_ID) {
      toast.error(t("toasts.selectCustomerSale"))
      return
    }

    const shouldDeductStock =
      documentStatus === "completed" ||
      (documentStatus === "pending" && settings.deductStockOnPending)
    const adjustStock = documentStatus !== "cancelled" && shouldDeductStock

    if (adjustStock && !settings.allowOverselling) {
      for (const line of cart) {
        const product = getProduct(line.productId)
        if (!product || product.stock < line.quantity) {
          toast.error(t("toasts.notEnoughStock", { name: line.productName }))
          return
        }
      }
    }

    const invoiceNumber = nextPosInvoiceNumber(orders, settings.receiptPrefix)

    if (settings.confirmBeforeComplete) {
      const confirmed = await confirmPosSaleAction({
        invoiceNumber,
        totalAmount: formatPosMoney(checkoutTotals.total),
        customerName,
        status: documentStatus,
      })
      if (!confirmed) return
    }

    setProcessing(true)
    try {
      const paidAmount = settings.allowPartialPayment
        ? Math.min(
            Number(checkoutTotals.total),
            Math.max(0, Number(paidAmountDraft) || 0)
          ).toFixed(2)
        : documentStatus === "completed"
          ? checkoutTotals.total
          : "0.00"

      const customer =
        customerId === WALK_IN_CUSTOMER_ID
          ? null
          : customers.find((item) => String(item.id) === customerId)
      const storeId = await resolveStoreId()
      const lines = buildCheckoutLines()

      const apiOrder = await apiPosCheckout({
        storeId,
        buyerId: customer?.apiId || null,
        buyerName: customerName,
        paymentMethod,
        paidAmount: Number(paidAmount),
        discountAmount: Number(checkoutTotals.discount) || 0,
        status: documentStatus,
        deductStock: adjustStock,
        allowOverselling: settings.allowOverselling,
        lines,
      })

      const created = addOrder(mapApiOrderToRow(apiOrder))
      void refreshProducts({ silent: true })
      emitProductsChanged()

      setLastSale(created)
      resetRegister()

      if (settings.autoOpenReceiptPdf && documentStatus === "completed") {
        try {
          await downloadInvoicePdf(created)
        } catch {
          toast.error(t("toasts.receiptFailed"))
        }
      }

      if (settings.autoFocusSearchAfterSale) {
        searchInputRef.current?.focus()
      }

      toast.success(
        documentStatus === "completed"
          ? `Sale ${created.invoiceNumber} completed.`
          : `Sale ${created.invoiceNumber} saved as ${documentStatus}.`
      )
    } catch (error) {
      const message =
        error instanceof ApiClientError
          ? error.message
          : error instanceof Error
            ? error.message
            : "Sale failed"
      toast.error(message)
    } finally {
      setProcessing(false)
    }
  }, [
    addOrder,
    buildCheckoutLines,
    cart,
    checkoutTotals.discount,
    checkoutTotals.total,
    customerId,
    customerName,
    customers,
    documentStatus,
    getProduct,
    orders,
    paymentMethod,
    refreshProducts,
    resetRegister,
    resolveStoreId,
    settings.allowOverselling,
    settings.allowPartialPayment,
    settings.autoFocusSearchAfterSale,
    settings.autoOpenReceiptPdf,
    settings.confirmBeforeComplete,
    settings.deductStockOnPending,
    settings.receiptPrefix,
    settings.requireCustomer,
    paidAmountDraft,
    t,
  ])

  const completeReturn = React.useCallback(async () => {
    if (cart.length === 0) {
      toast.error(t("toasts.addReturnProduct"))
      return
    }

    if (settings.requireCustomer && customerId === WALK_IN_CUSTOMER_ID) {
      toast.error(t("toasts.selectCustomerReturn"))
      return
    }

    const returnNumber = nextReturnNumber(returns, "sales")

    if (settings.confirmBeforeComplete) {
      if (
        !(await confirmReturnAction({
          scope: "invoice",
          itemName: returnNumber,
          referenceNumber: returnNumber,
          totalAmount: checkoutTotals.total,
          refundDue: checkoutTotals.total,
        }))
      ) {
        return
      }
    }

    setProcessing(true)
    try {
      const storeId = await resolveStoreId()
      const lines = cart.map((line) => {
        const apiId = getApiProductId(line.productId)
        const lineTotal = Number(cartLineTotal(line))
        const unitPrice =
          line.quantity > 0 ? lineTotal / line.quantity : Number(line.unitPrice) || 0
        return {
          productId: apiId ?? null,
          productName: line.productName,
          quantity: line.quantity,
          unitPrice: Number(unitPrice.toFixed(2)),
        }
      })

      if (lines.some((line) => !line.productId)) {
        throw new Error("One or more products are not synced. Refresh inventory and try again.")
      }

      const apiReturn = await apiPosReturn({
        storeId,
        sourceOrderId: null,
        partyName: customerName,
        description:
          Number(checkoutTotals.discount) > 0
            ? `POS return · Discount ${checkoutTotals.discount}`
            : "POS return",
        status: documentStatus,
        restock: documentStatus === "completed",
        lines,
      })

      const created = addReturn({
        ...mapApiReturnToRow(apiReturn),
        status: documentStatus,
      })

      void refreshProducts({ silent: true })
      emitProductsChanged()

      setLastReturn(created)
      resetRegister()
      toast.success(
        documentStatus === "completed"
          ? `Return ${created.returnNumber} completed.`
          : `Return ${created.returnNumber} saved as ${documentStatus}.`
      )
    } catch (error) {
      const message =
        error instanceof ApiClientError
          ? error.message
          : error instanceof Error
            ? error.message
            : "Return failed"
      toast.error(message)
    } finally {
      setProcessing(false)
    }
  }, [
    addReturn,
    cart,
    checkoutTotals.discount,
    checkoutTotals.total,
    customerId,
    customerName,
    documentStatus,
    getApiProductId,
    refreshProducts,
    resetRegister,
    resolveStoreId,
    returns,
    settings.confirmBeforeComplete,
    settings.requireCustomer,
    t,
  ])

  return (
    <div className="flex h-full min-h-0 flex-1 flex-col overflow-hidden p-2 sm:p-3">
      <CustomerQuickAddSheet
        open={customerQuickAddOpen}
        onOpenChange={setCustomerQuickAddOpen}
        formId="pos-customer-quick-add"
        onCreated={handleCustomerCreated}
      />

      <div className="grid min-h-0 flex-1 grid-cols-1 grid-rows-[minmax(0,1fr)] gap-2 sm:gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(320px,400px)]">
          <div
            className={cn(
              panelClass,
              "flex h-full min-h-0 flex-col overflow-hidden",
              mobilePane !== "catalog" && "max-lg:hidden"
            )}
          >
            <div className="border-border/40 flex flex-col gap-2 border-b px-2.5 py-2 sm:gap-2.5 sm:px-3 sm:py-2.5 lg:flex-row lg:items-center">
              <div className="flex items-center gap-2">
                <div className="bg-muted/70 inline-flex h-10 min-h-10 flex-1 items-center rounded-full p-0.5 ring-1 ring-border/40 sm:h-9 sm:min-h-9 sm:flex-none">
                  {(
                    [
                      { value: "sale", label: t("newSale"), icon: IconShoppingCart },
                      { value: "return", label: t("returns"), icon: IconRotateClockwise },
                    ] as const
                  ).map(({ value, label, icon: Icon }) => (
                    <button
                      key={value}
                      type="button"
                      onClick={() => switchMode(value)}
                      className={cn(
                        "inline-flex h-full min-h-9 flex-1 items-center justify-center gap-1.5 rounded-full px-3 text-xs font-medium transition-colors sm:flex-none sm:px-3.5",
                        mode === value
                          ? "bg-background text-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      )}
                    >
                      <Icon className="size-3.5" stroke={1.75} />
                      {label}
                    </button>
                  ))}
                </div>
                <Link
                  href="/pos/settings"
                  aria-label={t("openPosSettings")}
                  className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex size-10 shrink-0 items-center justify-center rounded-full sm:size-9 lg:hidden"
                >
                  <IconSettings className="size-4" stroke={1.75} />
                </Link>
              </div>
              <div className="flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center">
                <PosCustomerSelect
                  customerId={customerId}
                  customerName={customerName}
                  onCustomerChange={setCustomerId}
                  onClearCustomer={clearCustomer}
                  onAddCustomer={() => setCustomerQuickAddOpen(true)}
                  customerOptions={customerOptions}
                  walkInCustomerId={WALK_IN_CUSTOMER_ID}
                  className="w-full min-w-0 sm:w-[12.5rem] sm:shrink-0"
                />
                <div className="min-w-0 w-full flex-1">
                  <SearchInput
                    ref={searchInputRef}
                    placeholder={t("searchCatalog")}
                    value={search}
                    onChange={(event) => setSearch(event.target.value)}
                    icon={<IconSearch className="size-3.5" />}
                    className={searchInputClass}
                  />
                </div>
              </div>
              <Link
                href="/pos/settings"
                aria-label={t("openPosSettings")}
                className="text-muted-foreground hover:bg-muted hover:text-foreground hidden size-9 shrink-0 items-center justify-center rounded-full lg:inline-flex"
              >
                <IconSettings className="size-3.5" stroke={1.75} />
              </Link>
            </div>

            <PosCatalogTabs
              brand={brand}
              onBrandChange={setBrand}
              brands={brands}
              className="px-2 sm:px-3"
            />

            {filteredProducts.length > 0 ? (
              <div className="bg-muted/20 min-h-0 flex-1 overflow-y-auto overscroll-contain p-2 sm:min-h-[12rem] sm:p-3 lg:min-h-[18rem]">
                <div className={cn("grid auto-rows-fr gap-2 sm:gap-3", catalogGridClass(settings.catalogColumns))}>
                  {filteredProducts.map((product) => (
                    <PosProductCard
                      key={product.id}
                      product={product}
                      inCartQty={cartQtyByProductId.get(product.id) ?? 0}
                      formatPrice={formatRegisterMoney}
                      onAdd={addToCart}
                      disableWhenOutOfStock={
                        isSale ? !settings.allowOverselling : false
                      }
                      showSku={settings.showSkuOnCards}
                      showStock={settings.showStockOnCards}
                      lowStockThreshold={settings.lowStockThreshold}
                    />
                  ))}
                </div>
              </div>
            ) : (
              <div className="bg-muted/20 flex flex-1 flex-col items-center justify-center gap-2 px-4 py-10 text-center sm:py-16">
                <div className="bg-muted/60 text-muted-foreground flex size-12 items-center justify-center rounded-2xl">
                  {isSale ? (
                    <IconShoppingCart className="size-5" />
                  ) : (
                    <IconRotateClockwise className="size-5" />
                  )}
                </div>
                <p className="text-sm font-medium">{t("noProductsMatch")}</p>
                <p className="text-muted-foreground max-w-xs text-sm">
                  {isSale
                    ? settings.hideOutOfStockOnSale
                      ? t("emptySaleInStock")
                      : t("emptySaleAll")
                    : t("emptyReturn")}
                </p>
                <Link
                  href="/pos/settings"
                  className="text-primary mt-1 text-xs font-medium underline underline-offset-2"
                >
                  {t("openPosSettings")}
                </Link>
              </div>
            )}
          </div>

          <div
            className={cn(
              panelClass,
              "flex h-full min-h-0 flex-col overflow-hidden",
              mobilePane !== "cart" && "max-lg:hidden"
            )}
          >
            {isSale ? (
              <PosInvoicePanel
                nextInvoiceNumber={nextInvoice}
                lastCreated={lastCreatedInvoice}
                justCreated={lastSale}
                formatMoney={formatPosMoney}
                onDismissJustCreated={() => setLastSale(null)}
                className="rounded-none shadow-none ring-0 border-b border-border/40"
              />
            ) : (
              <PosReturnPanel
                nextReturnNumber={nextReturn}
                lastCreated={lastCreatedReturn}
                justCreated={lastReturn}
                formatMoney={formatPosReturnMoney}
                onDismissJustCreated={() => setLastReturn(null)}
                className="rounded-none shadow-none ring-0 border-b border-border/40"
              />
            )}

            <PosCartPanel
              className="min-h-0 flex-1 rounded-none shadow-none ring-0"
              cart={cart}
              selectedProductId={selectedProductId}
              onSelectLine={setSelectedProductId}
              onQuantityChange={setLineQuantity}
              onFinalPriceChange={setLineFinalPrice}
              onRemoveLine={removeFromCart}
              onClearCart={clearCart}
              formatMoney={formatRegisterMoney}
              paymentMethod={paymentMethod}
              onPaymentMethodChange={setPaymentMethod}
              status={documentStatus}
              onStatusChange={setDocumentStatus}
              discountDraft={discountDraft}
              onDiscountDraftChange={setDiscountDraft}
              onApplyDiscount={applyDiscount}
              onClearDiscount={clearDiscount}
              appliedDiscount={checkoutTotals.discount}
              subtotal={checkoutTotals.subtotal}
              total={checkoutTotals.total}
              disabled={cart.length === 0}
              processing={processing}
              onCompleteSale={isSale ? completeSale : completeReturn}
              variant={isSale ? "sale" : "return"}
              enabledPaymentMethods={settings.enabledPaymentMethods}
              allowDiscounts={settings.allowDiscounts}
              allowLinePriceEdit={settings.allowLinePriceEdit}
              allowPartialPayment={settings.allowPartialPayment}
              paidAmountDraft={paidAmountDraft}
              onPaidAmountDraftChange={setPaidAmountDraft}
            />
          </div>
        </div>

      <nav
        className="border-border/50 bg-card/95 mt-2 grid shrink-0 grid-cols-2 gap-1 rounded-xl p-1 shadow-sm ring-1 ring-border/40 backdrop-blur lg:hidden"
        aria-label={t("register")}
      >
        <button
          type="button"
          onClick={() => setMobilePane("catalog")}
          className={cn(
            "inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg px-3 text-sm font-medium transition-colors",
            mobilePane === "catalog"
              ? "bg-primary text-primary-foreground shadow-sm"
              : "text-muted-foreground hover:bg-muted hover:text-foreground"
          )}
        >
          <IconSearch className="size-4" stroke={1.75} />
          {t("products")}
        </button>
        <button
          type="button"
          onClick={() => setMobilePane("cart")}
          className={cn(
            "inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg px-3 text-sm font-medium transition-colors",
            mobilePane === "cart"
              ? "bg-primary text-primary-foreground shadow-sm"
              : "text-muted-foreground hover:bg-muted hover:text-foreground"
          )}
        >
          <IconShoppingCart className="size-4" stroke={1.75} />
          <span>{isSale ? t("cart") : t("return")}</span>
          {cartItemCount > 0 ? (
            <span
              className={cn(
                "inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[11px] font-semibold tabular-nums",
                mobilePane === "cart"
                  ? "bg-primary-foreground/20 text-primary-foreground"
                  : "bg-primary/10 text-primary"
              )}
            >
              {cartItemCount}
            </span>
          ) : null}
        </button>
      </nav>
    </div>
  )
}
