'use client';

import { useMemo, useState, useTransition, useRef, useEffect, Fragment } from 'react';
import { useForm, useFieldArray, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';

import { formatDateTimeStable, formatTimeStable } from '@/lib/formatters';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Separator } from '@/components/ui/separator';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { PlusCircle, Trash2, Loader2, CreditCard, UserPlus, ScanLine, ReceiptText, Calculator, LayoutGrid, Plus, AlertTriangle, Check, ChevronsUpDown, Printer, Maximize2, Minimize2, Table2 } from 'lucide-react';

import { type Bank, type Campaign, type Currency, type Customer, type CustomerPayment, type CustomerPricing, type ItemGroup, type ItemUnit, type ProductShape, type ProductionItem, type PurchaseOrder, type SalesInvoice, type SalesRep, type StockLocationBalance, type Supplier, type SupplierPayment, type Warehouse, type PaymentBreakdown, type PrintingSettings } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';
import { handleClosePosShift, handleCreateSaleInvoice, handleGetEmployeeCashboxSummary, handleGetPosShiftStatus, handleOpenPosShift } from '@/lib/actions';
import { formatCurrency } from '@/lib/currency-formatter';
import { MaterialItemDialog } from '@/components/admin/list-manager';
import AddCustomerDialog from '@/components/admin/add-customer-dialog';
import PartyStatement from '@/components/admin/party-statement';
import PaymentVoucherForm from '@/components/admin/payment-voucher-form';
import { PaymentMethodModal } from '@/components/admin/payment-method-modal';
import { cn } from '@/lib/utils';
import { computeCampaignLivePreview } from '@/lib/campaign-live-preview';
import { getPosDraftSocket } from '@/lib/pos-draft-socket-client';

const ADD_NEW_CUSTOMER_VALUE = '__add_new_customer__';

const escapePrintHtml = (value: unknown) => String(value ?? '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#39;');

const openPrintPreviewWindow = (html: string) => {
  if (typeof window === 'undefined') return false;
  const win = window.open('', '', 'height=720,width=960');
  if (!win) return false;
  win.document.write(html);
  win.document.close();
  win.focus();
  win.print();
  win.close();
  return true;
};

const posSchema = z.object({
  customerId: z.string().optional().default(''),
  amountPaid: z.coerce.number().min(0).default(0),
  payments: z.array(z.object({
    method: z.enum(['cash', 'visa', 'receivables', 'coupon']),
    amount: z.coerce.number().min(0),
    customerName: z.string().optional(),
    bankAccountId: z.string().optional(),
    couponCode: z.string().optional(),
  })).optional().default([]),
  discountAmount: z.coerce.number().min(0).default(0),
  isReturn: z.coerce.boolean().optional().default(false),
  items: z.array(z.object({
    materialId: z.string().min(1),
    quantity: z.coerce.number().min(0.001),
    unitPrice: z.coerce.number().min(0),
    description: z.string().optional().default(''),
    discount: z.coerce.number().min(0).default(0),
    itemUnitId: z.string().optional().default(''),
    serialNumber: z.string().optional().default(''),
    rfidCode: z.string().optional().default(''),
    warehouseId: z.string().optional().default(''),
    shelfId: z.string().optional().default(''),
  })).min(1),
});

type PosPaymentBreakdown = z.infer<typeof posSchema>['payments'];

type PosVisibleColumns = {
  itemNumber?: boolean;
  unit?: boolean;
  description?: boolean;
  barcode?: boolean;
  quantity?: boolean;
  price?: boolean;
  itemDiscount?: boolean;
  bonus?: boolean;
  total?: boolean;
  actions?: boolean;
  weighedItemsButton?: boolean;
};

type PosShiftSession = {
  id: string;
  userId?: string;
  userName?: string;
  status: 'active' | 'closed';
  startedAt: string;
  endedAt?: string;
  openingCash: number;
  openingVisa: number;
  expectedCashAtClose: number;
  expectedVisaAtClose: number;
  countedCashAtClose?: number;
  countedVisaAtClose?: number;
  cashVariance?: number;
  visaVariance?: number;
  invoicesCount: number;
  returnsCount: number;
  totalSalesAmount: number;
  cashSalesAmount: number;
  visaSalesAmount: number;
  receivablesAmount: number;
  couponAmount: number;
  requiresApproval?: boolean;
};

type CashboxSummary = {
  openingCash: number;
  cashSalesAmount: number;
  expectedCashAtClose: number;
};

type SuspendedInvoiceDraft = {
  id: string;
  customerId: string;
  amountPaid: number;
  payments?: PosPaymentBreakdown;
  discountAmount?: number;
  items: { materialId: string; quantity: number; unitPrice: number; description?: string; discount?: number; itemUnitId?: string; serialNumber?: string; rfidCode?: string; warehouseId?: string; shelfId?: string }[];
  createdAt: string;
  tableId?: string;
  tableName?: string;
  areaName?: string;
};

type PosSalesProps = {
  customers: Customer[];
  suppliers?: Supplier[];
  materials: ProductionItem[];
  itemUnits?: ItemUnit[];
  itemGroups?: ItemGroup[];
  invoices?: SalesInvoice[];
  orders?: PurchaseOrder[];
  customerPayments?: CustomerPayment[];
  supplierPayments?: SupplierPayment[];
  campaigns?: Campaign[];
  banks: Bank[];
  currencies: Currency[];
  defaultCurrency: Currency | null;
  allCustomerPricing: CustomerPricing[];
  salesReps?: SalesRep[];
  warehouses?: Warehouse[];
  warehouseConfig?: {
    enabled: boolean;
    allowOutOfStockSales?: boolean;
    defaultWarehouseId?: string;
    defaultShelfId?: string;
  };
  stockLocationsByMaterial?: Record<string, StockLocationBalance[]>;
  t: any;
  tStatement: any;
  tGlobal: any;
  locale: string;
  currencySymbol?: string;
  cashierName?: string;
  employeeCashAccountCode?: string;
  scaleSettings?: {
    mode?: 'manual' | 'hid' | 'serial';
    readRegex?: string;
    decimalSeparator?: 'auto' | 'dot' | 'comma';
    hidMinLength?: number;
    serialBaudRate?: number;
    serialDataBits?: number;
    serialStopBits?: number;
    serialParity?: 'none' | 'even' | 'odd';
    serialAutoConnect?: boolean;
  };
  posPaymentMethods?: {
    allowCash?: boolean;
    allowVisa?: boolean;
    allowReceivables?: boolean;
    defaultVisaBankAccountId?: string;
  };
  visibleColumns?: PosVisibleColumns;
  printingSettings?: PrintingSettings;
  restaurantConfig?: {
    enabled?: boolean;
    areasEnabled?: boolean;
    splitBillEnabled?: boolean;
    mergeTablesEnabled?: boolean;
    transferItemEnabled?: boolean;
    partialCheckoutEnabled?: boolean;
    kotEnabled?: boolean;
    autoReserveMinutes?: number;
    defaultGuestCount?: number;
    areas?: Array<{ id?: string; name?: string; sortOrder?: number }>;
    tables?: Array<{ id?: string; tableCode?: string; name?: string; areaId?: string; seats?: number }>;
  };
};

export default function PosSales({ customers, suppliers = [], materials, itemUnits = [], itemGroups = [], invoices = [], orders = [], customerPayments = [], supplierPayments = [], campaigns = [], banks, currencies, defaultCurrency, allCustomerPricing, salesReps = [], warehouses = [], warehouseConfig, stockLocationsByMaterial = {}, t, tStatement, tGlobal, locale, currencySymbol = '$', cashierName, employeeCashAccountCode = '', scaleSettings, posPaymentMethods = { allowCash: true, allowVisa: true, allowReceivables: true }, visibleColumns = {}, printingSettings = { customPrintersEnabled: false, printerConfigs: [], printSections: [] }, restaurantConfig = { enabled: false } }: PosSalesProps) {
  const leftPanelWidthRef = useRef(320);
  const summaryPanelWidthRef = useRef(360);
  const { toast } = useToast();
  const [, startInvoiceTransition] = useTransition();
  const [isSaveInvoicePending, setIsSaveInvoicePending] = useState(false);
  const [isPartialPaymentPending, setIsPartialPaymentPending] = useState(false);
  const [isShiftPending, startShiftTransition] = useTransition();
  const [customerList, setCustomerList] = useState(customers);
  const [barcodeInput, setBarcodeInput] = useState('');
  const [showItemPicker, setShowItemPicker] = useState(false);
  const [itemSearch, setItemSearch] = useState('');
  const [itemSearchDraft, setItemSearchDraft] = useState('');
  const [showWeighedItemsDialog, setShowWeighedItemsDialog] = useState(false);
  const [weighedSearch, setWeighedSearch] = useState('');
  const [weighedGroupFilter, setWeighedGroupFilter] = useState('__all__');
  const [showGroupsPicker, setShowGroupsPicker] = useState(false);
  const [showRestaurantTablesDialog, setShowRestaurantTablesDialog] = useState(false);
  const [pendingTableIdOnSwitch, setPendingTableIdOnSwitch] = useState<string | null>(null);
  const [showTableSwitchConfirmDialog, setShowTableSwitchConfirmDialog] = useState(false);
  const [showPartialCheckoutInfoDialog, setShowPartialCheckoutInfoDialog] = useState(false);
  const [partialPaySelectedIndexes, setPartialPaySelectedIndexes] = useState<number[]>([]);
  const [showPartialPayDialog, setShowPartialPayDialog] = useState(false);
  const storageUserScope = useMemo(() => {
    const raw = String(employeeCashAccountCode || cashierName || 'default').trim();
    return raw.replace(/[^a-zA-Z0-9_-]/g, '_') || 'default';
  }, [employeeCashAccountCode, cashierName]);
  const posDraftInvoiceStorageKey = useMemo(() => `posDraftInvoice:${storageUserScope}`, [storageUserScope]);
  const posSuspendedInvoicesStorageKey = useMemo(() => `posSuspendedInvoices:${storageUserScope}`, [storageUserScope]);
  const posActiveRestaurantTableStorageKey = useMemo(() => `posActiveRestaurantTableId:${storageUserScope}`, [storageUserScope]);
  const isAnyPartialPaySelected = partialPaySelectedIndexes.length > 0;
  // partial pay per-row quantity ask
  const [partialPayRowIndex, setPartialPayRowIndex] = useState<number | null>(null);
  const [partialPayRowQty, setPartialPayRowQty] = useState<string>('1');
  const [showPartialPayRowQtyDialog, setShowPartialPayRowQtyDialog] = useState(false);
  const handleOpenPartialPayRow = (index: number) => {
    const lineQty = Number(watchAllItems[index]?.quantity || 1);
    if (lineQty > 1) {
      setPartialPayRowIndex(index);
      setPartialPayRowQty(String(lineQty));
      setShowPartialPayRowQtyDialog(true);
    } else {
      setPartialPaySelectedIndexes([index]);
      setShowPartialPayDialog(true);
    }
  };
  const handleConfirmPartialPayRowQty = () => {
    if (partialPayRowIndex === null) return;
    setShowPartialPayRowQtyDialog(false);
    setPartialPaySelectedIndexes([partialPayRowIndex]);
    setShowPartialPayDialog(true);
  };
  const [groupItemSearch, setGroupItemSearch] = useState('');
  const [groupKeyboardVisible, setGroupKeyboardVisible] = useState(true);
  const [groupKeyboardLanguage, setGroupKeyboardLanguage] = useState<'ar' | 'en'>(locale === 'en' ? 'en' : 'ar');
  const [showInvoices, setShowInvoices] = useState(false);
  const [showAddCustomerDialog, setShowAddCustomerDialog] = useState(false);
  const [showAccounting, setShowAccounting] = useState(false);
  const [accountingView, setAccountingView] = useState<'statement' | 'payment'>('statement');
  const [showAddBarcodeDialog, setShowAddBarcodeDialog] = useState(false);
  const [notFoundBarcode, setNotFoundBarcode] = useState('');
  const [showAddMaterialDialog, setShowAddMaterialDialog] = useState(false);
  const [addMaterialInitialValues, setAddMaterialInitialValues] = useState<Partial<ProductionItem> | undefined>(undefined);
  const [extraMaterials, setExtraMaterials] = useState<ProductionItem[]>([]);
  const [showWeightDialog, setShowWeightDialog] = useState(false);
  const [weightInput, setWeightInput] = useState('');
  const [pendingWeightMaterial, setPendingWeightMaterial] = useState<ProductionItem | null>(null);
  const [pendingWeightUnitPrice, setPendingWeightUnitPrice] = useState(0);
  const [pendingWeightPrimaryPrice, setPendingWeightPrimaryPrice] = useState(0);
  const [pendingWeightDescription, setPendingWeightDescription] = useState('');
  const [pendingMeasurementMode, setPendingMeasurementMode] = useState<'weight' | 'volume'>('weight');
  const [pendingVolumeOptions, setPendingVolumeOptions] = useState<Array<{ key: string; label: string; price: number; barcode?: string }>>([]);
  const [selectedVolumeOptionKey, setSelectedVolumeOptionKey] = useState('');
  const [isSerialSupported, setIsSerialSupported] = useState(false);
  const [isSerialConnected, setIsSerialConnected] = useState(false);
  const [isSerialConnecting, setIsSerialConnecting] = useState(false);
  const serialPortRef = useRef<any>(null);
  const serialReaderRef = useRef<any>(null);
  const serialAbortRef = useRef<boolean>(false);
  const hidBufferRef = useRef('');
  const hidTimerRef = useRef<any>(null);
  const weightInputRef = useRef<HTMLInputElement | null>(null);
  const [showShapeDialog, setShowShapeDialog] = useState(false);
  const [pendingShapeMaterial, setPendingShapeMaterial] = useState<ProductionItem | null>(null);
  const [pendingShapeBasePrice, setPendingShapeBasePrice] = useState(0);
  const [pendingShapeBarcode, setPendingShapeBarcode] = useState<string | undefined>(undefined);
  const [selectedShapeId, setSelectedShapeId] = useState('');
  const [allItemUnits, setAllItemUnits] = useState<ItemUnit[]>(itemUnits);
  const [showTrackedUnitDialog, setShowTrackedUnitDialog] = useState(false);
  const [pendingTrackedMaterial, setPendingTrackedMaterial] = useState<ProductionItem | null>(null);
  const [pendingTrackedUnitPrice, setPendingTrackedUnitPrice] = useState(0);
  const [pendingTrackedDescription, setPendingTrackedDescription] = useState('');
  const [trackedUnitSearch, setTrackedUnitSearch] = useState('');
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [pendingFinalizeAction, setPendingFinalizeAction] = useState<'save' | 'savePrint' | null>(null);
  const [showCustomerPickerDialog, setShowCustomerPickerDialog] = useState(false);
  const [customerSearchQuery, setCustomerSearchQuery] = useState('');
  const [payments, setPayments] = useState<PosPaymentBreakdown>([]);
  const [compactRowLayout, setCompactRowLayout] = useState<boolean>(true);
  useEffect(() => {
    try {
      const stored = localStorage.getItem('posItemsRowLayout');
      if (stored === 'expanded') setCompactRowLayout(false);
      else if (stored === 'compact') setCompactRowLayout(true);
    } catch {}
  }, []);
  useEffect(() => {
    try {
      localStorage.setItem('posItemsRowLayout', compactRowLayout ? 'compact' : 'expanded');
    } catch {}
  }, [compactRowLayout]);
  const barcodeRef = useRef<HTMLInputElement | null>(null);
  const shouldPrintAfterSaveRef = useRef(false);
  const [isReturn, setIsReturn] = useState(false);
  const isWarehouseEnabled = warehouseConfig?.enabled === true;
  const allowOutOfStockSales = warehouseConfig?.allowOutOfStockSales === true;
  const defaultWarehouseId = isWarehouseEnabled ? String(warehouseConfig?.defaultWarehouseId || '') : '';
  const defaultShelfId = isWarehouseEnabled ? String(warehouseConfig?.defaultShelfId || '') : '';
  const showItemNumberColumn = visibleColumns.itemNumber !== false;
  const showUnitColumn = visibleColumns.unit !== false;
  const showDescriptionColumn = visibleColumns.description !== false;
  const showBarcodeColumn = visibleColumns.barcode !== false;
  const showQuantityColumn = visibleColumns.quantity !== false;
  const showPriceColumn = visibleColumns.price !== false;
  const showItemDiscountColumn = visibleColumns.itemDiscount !== false;

  const getDisplayCustomerName = (invoiceCustomerName?: string, linkedCustomerName?: string) => {
    const normalized = String(invoiceCustomerName || linkedCustomerName || '').trim();
    if (!normalized) return t?.unknownCustomer ?? 'زبون غير معروف';
    if (normalized === 'Cash Customer' || normalized === 'cash customer') return 'زبون نقدي';
    if (normalized === 'زبون غير معروف') return 'زبون نقدي';
    return normalized;
  };
  const showBonusColumn = visibleColumns.bonus !== false;
  const showTotalColumn = visibleColumns.total !== false;
  const showActionsColumn = visibleColumns.actions !== false;
  const showWeighedItemsButton = visibleColumns.weighedItemsButton === true;
  const restaurantPosEnabled = restaurantConfig?.enabled === true;
  const restaurantAreasCount = Array.isArray(restaurantConfig?.areas) ? restaurantConfig.areas.length : 0;
  const restaurantTablesCount = Array.isArray(restaurantConfig?.tables) ? restaurantConfig.tables.length : 0;
  const restaurantAreas = useMemo(
    () => (Array.isArray(restaurantConfig?.areas) ? restaurantConfig.areas : [])
      .map((area, index) => ({
        id: String(area?.id || '').trim(),
        name: String(area?.name || '').trim() || `منطقة ${index + 1}`,
        sortOrder: Number(area?.sortOrder || 0),
      }))
      .filter((area) => area.id.length > 0)
      .sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name, 'ar')),
    [restaurantConfig?.areas],
  );
  const restaurantTables = useMemo(
    () => (Array.isArray(restaurantConfig?.tables) ? restaurantConfig.tables : [])
      .map((table, index) => ({
        id: String(table?.id || '').trim(),
        tableCode: String((table as any)?.tableCode || '').trim() || undefined,
        name: String(table?.name || '').trim() || `طاولة ${index + 1}`,
        areaId: String(table?.areaId || '').trim(),
        seats: Math.max(1, Number(table?.seats || 4)),
      }))
      .filter((table) => table.id.length > 0),
    [restaurantConfig?.tables],
  );
  const visibleColumnCount = [
    true,
    showItemNumberColumn,
    showUnitColumn,
    isWarehouseEnabled,
    showDescriptionColumn,
    showBarcodeColumn,
    showQuantityColumn,
    showPriceColumn,
    showItemDiscountColumn,
    showBonusColumn,
    showTotalColumn,
    showActionsColumn,
  ].filter(Boolean).length;
  const enabledPrinters = useMemo(
    () => (Array.isArray(printingSettings?.printerConfigs) ? printingSettings.printerConfigs : []).filter((printer) => printer?.enabled !== false),
    [printingSettings],
  );
  const activePrintSections = useMemo(
    () => (Array.isArray(printingSettings?.printSections) ? printingSettings.printSections : [])
      .filter((section) => section?.enabled !== false && String(section?.name || '').trim().length > 0),
    [printingSettings],
  );
  const printerNameById = useMemo(
    () => new Map(enabledPrinters.map((printer) => [String(printer?.id || ''), String(printer?.name || printer?.id || '')])),
    [enabledPrinters],
  );
  const printSectionById = useMemo(
    () => new Map(activePrintSections.map((section) => [String(section?.id || ''), section])),
    [activePrintSections],
  );
  const defaultReceiptPrinterName = useMemo(() => {
    const printerId = String(printingSettings?.defaultCustomerReceiptPrinterId || '').trim();
    return printerId ? (printerNameById.get(printerId) || '') : '';
  }, [printingSettings, printerNameById]);
  const [showSuspended, setShowSuspended] = useState(false);
  const [activeShift, setActiveShift] = useState<PosShiftSession | null>(null);
  const [cashboxSummary, setCashboxSummary] = useState<CashboxSummary>({ openingCash: 0, cashSalesAmount: 0, expectedCashAtClose: 0 });
  const [lastClosedShift, setLastClosedShift] = useState<PosShiftSession | null>(null);
  const [isShiftLoading, setIsShiftLoading] = useState(true);
  const [showOpenShiftDialog, setShowOpenShiftDialog] = useState(false);
  const [showCloseShiftDialog, setShowCloseShiftDialog] = useState(false);
  const [showShiftConflictDialog, setShowShiftConflictDialog] = useState(false);
  const [showPendingInvoiceBeforeCloseDialog, setShowPendingInvoiceBeforeCloseDialog] = useState(false);
  const [liveTime, setLiveTime] = useState('');
  const [shiftElapsed, setShiftElapsed] = useState('00:00:00');
  const [isFullscreenMode, setIsFullscreenMode] = useState(false);
  const [openShiftCash, setOpenShiftCash] = useState('0');
  const [openShiftVisa, setOpenShiftVisa] = useState('0');
  const [openShiftNotes, setOpenShiftNotes] = useState('');
  const [closeShiftCash, setCloseShiftCash] = useState('0');
  const [closeShiftVisa, setCloseShiftVisa] = useState('0');
  const [closeShiftNotes, setCloseShiftNotes] = useState('');
  const [suspendedInvoices, setSuspendedInvoices] = useState<SuspendedInvoiceDraft[]>([]);
  const [selectedAreaFilter, setSelectedAreaFilter] = useState<string>('__all__');
  const [activeRestaurantTableId, setActiveRestaurantTableId] = useState<string>('');
  const [lastAutosaveAt, setLastAutosaveAt] = useState<string | null>(null);
  const [activeGroupId, setActiveGroupId] = useState<string>('');
  const [showAllGroups, setShowAllGroups] = useState(false);
  const [leftPanelWidth, setLeftPanelWidth] = useState(320);
  const [summaryPanelWidth, setSummaryPanelWidth] = useState(360);
  const isAnyBlockingDialogOpen =
    showItemPicker ||
    showGroupsPicker ||
    showRestaurantTablesDialog ||
    showTableSwitchConfirmDialog ||
    showPartialCheckoutInfoDialog ||
    showAddCustomerDialog ||
    showAddBarcodeDialog ||
    showAddMaterialDialog ||
    showWeightDialog ||
    showShapeDialog ||
    showTrackedUnitDialog ||
    showSuspended ||
    showInvoices ||
    showPendingInvoiceBeforeCloseDialog ||
    paymentModalOpen;
  const [invoiceDateFilter, setInvoiceDateFilter] = useState(() => {
    const now = new Date();
    const local = new Date(now.getTime() - now.getTimezoneOffset() * 60000);
    return local.toISOString().slice(0, 10);
  });
  const isShiftOpen = !!activeShift;

  const requestFullscreenMode = async () => {
    if (typeof document === 'undefined') return;
    if (document.fullscreenElement) return;
    try {
      await document.documentElement.requestFullscreen();
    } catch {
      toast({
        title: 'تعذر تفعيل ملء الشاشة',
        description: 'اضغط الزر مرة أخرى بعد أي تفاعل، أو استخدم F11 من المتصفح.',
        variant: 'destructive',
      });
    }
  };

  const toggleFullscreenMode = async () => {
    if (typeof document === 'undefined') return;
    try {
      if (document.fullscreenElement) {
        await document.exitFullscreen();
      } else {
        await requestFullscreenMode();
      }
    } catch {
      toast({
        title: 'تعذر تغيير وضع الشاشة',
        description: 'تأكد أن المتصفح يسمح بوضع ملء الشاشة.',
        variant: 'destructive',
      });
    }
  };

  useEffect(() => {
    if (typeof document === 'undefined') return;

    const syncFullscreenState = () => setIsFullscreenMode(Boolean(document.fullscreenElement));
    syncFullscreenState();
    document.addEventListener('fullscreenchange', syncFullscreenState);

    return () => {
      document.removeEventListener('fullscreenchange', syncFullscreenState);
    };
  }, []);

  const form = useForm<z.infer<typeof posSchema>>({
    resolver: zodResolver(posSchema),
    defaultValues: {
      customerId: '',
      amountPaid: 0,
      payments: [],
      discountAmount: 0,
      isReturn: false,
      items: [],
    },
  });

  const { fields, append, replace } = useFieldArray({
    control: form.control,
    name: 'items',
  });

  const watchAllItems = useWatch({
    control: form.control,
    name: 'items',
  });
  const watchedAmountPaid = useWatch({
    control: form.control,
    name: 'amountPaid',
  });
  const watchedDiscountAmount = useWatch({
    control: form.control,
    name: 'discountAmount',
  });
  const selectedCustomerId = useWatch({
    control: form.control,
    name: 'customerId',
  });

  useEffect(() => {
    setIsSerialSupported(typeof window !== 'undefined' && !!(navigator as any)?.serial);
  }, []);

  const loadShiftStatus = async () => {
    setIsShiftLoading(true);
    try {
      const [result, cashboxResult] = await Promise.all([
        Promise.race([
        handleGetPosShiftStatus(),
        new Promise((resolve) => setTimeout(() => resolve({ success: false, error: 'SHIFT_STATUS_TIMEOUT' }), 5000)),
        ]),
        handleGetEmployeeCashboxSummary(employeeCashAccountCode),
      ]);
      if ((result as any)?.success) {
        setActiveShift(((result as any).activeShift || null) as PosShiftSession | null);
        setLastClosedShift(((result as any).lastClosedShift || null) as PosShiftSession | null);
      } else if ((result as any)?.error === 'SHIFT_STATUS_TIMEOUT') {
        setActiveShift(null);
      }

      if ((cashboxResult as any)?.success) {
        setCashboxSummary(((cashboxResult as any).summary || { openingCash: 0, cashSalesAmount: 0, expectedCashAtClose: 0 }) as CashboxSummary);
      } else {
        setCashboxSummary({ openingCash: 0, cashSalesAmount: 0, expectedCashAtClose: 0 });
      }
    } catch {
      setActiveShift(null);
      setCashboxSummary({ openingCash: 0, cashSalesAmount: 0, expectedCashAtClose: 0 });
    } finally {
      setIsShiftLoading(false);
    }
  };

  useEffect(() => {
    loadShiftStatus();
  }, []);

  const requestOpenShiftDialog = async (options?: { silent?: boolean }) => {
    if (isShiftPending) return;
    const silent = options?.silent === true;
    // Reset both dialogs before resolving the current runtime status.
    setShowOpenShiftDialog(false);
    setShowShiftConflictDialog(false);
    setIsShiftLoading(true);
    try {
      const status = await Promise.race([
        handleGetPosShiftStatus(),
        new Promise((resolve) => setTimeout(() => resolve({ success: false, error: 'SHIFT_STATUS_TIMEOUT' }), 10000)),
      ]);
      if ((status as any)?.success) {
        const runtimeUserActive = (((status as any).activeShift || null) as PosShiftSession | null);
        if (runtimeUserActive) {
          setShowOpenShiftDialog(false);
          setShowShiftConflictDialog(true);
          const activeShiftOwner = String(runtimeUserActive.userName || cashierName || '').trim() || 'المستخدم الحالي';
          toast({
            title: t?.shiftAlreadyOpen ?? 'لا يمكن افتتاح وردية جديدة قبل إغلاق الوردية الحالية.',
            description: t?.shiftAlreadyOpenCurrentUser ?? `لديك وردية نشطة حالياً باسم: ${activeShiftOwner}. يمكنك الاستمرار بها أو إغلاقها وبدء وردية جديدة.`,
            variant: 'destructive',
          });
          return;
        }

        // No active shift for current user -> safe to open a new shift for this user.
        setShowOpenShiftDialog(true);
        return;
      }

      // If status check timed out/failed, do not open shift dialog before verification.
      if (!silent) {
        toast({
          title: t?.unexpectedError ?? 'تعذر التحقق من حالة الوردية',
          description: t?.shiftStatusUnavailable ?? 'تعذر التأكد من وجود وردية نشطة حالياً. حاول مرة أخرى.',
          variant: 'destructive',
        });
      }
    } catch {
      if (!silent) {
        toast({
          title: t?.unexpectedError ?? 'تعذر التحقق من حالة الوردية',
          description: t?.shiftStatusUnavailable ?? 'تعذر التأكد من وجود وردية نشطة حالياً. حاول مرة أخرى.',
          variant: 'destructive',
        });
      }
    } finally {
      setIsShiftLoading(false);
    }
  };

  // Auto-open shift dialog on first load only — ref prevents re-triggering on subsequent loadShiftStatus calls
  const initialShiftCheckDoneRef = useRef(false);
  useEffect(() => {
    if (isShiftLoading) return;                        // wait until loading finishes
    if (initialShiftCheckDoneRef.current) return;      // already checked once
    initialShiftCheckDoneRef.current = true;
    // Skip the auto-prompt when loadShiftStatus already resolved an active shift for this user;
    // there is nothing to confirm and no need to make a second round-trip.
    if (activeShift) return;
    // Always run the shift check once on startup:
    // - shows conflict dialog first if a shift is already open
    // - otherwise shows open-shift dialog
    // Silent on auto-fire so a slow/unauthorized response on first paint does not flash a destructive toast.
    void requestOpenShiftDialog({ silent: true });
  }, [isShiftLoading]);

  // Live clock — initialized only after mount to avoid SSR/hydration mismatch
  useEffect(() => {
    const fmt = () => new Date().toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
    setLiveTime(fmt());
    const timer = setInterval(() => setLiveTime(fmt()), 1000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const formatElapsed = (totalSeconds: number) => {
      const safe = Math.max(0, Math.floor(totalSeconds));
      const hours = Math.floor(safe / 3600).toString().padStart(2, '0');
      const minutes = Math.floor((safe % 3600) / 60).toString().padStart(2, '0');
      const seconds = (safe % 60).toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    };

    const updateElapsed = () => {
      if (!activeShift?.startedAt) {
        setShiftElapsed('00:00:00');
        return;
      }
      const startedAtMs = new Date(activeShift.startedAt).getTime();
      if (!Number.isFinite(startedAtMs)) {
        setShiftElapsed('00:00:00');
        return;
      }
      const nowMs = Date.now();
      setShiftElapsed(formatElapsed((nowMs - startedAtMs) / 1000));
    };

    updateElapsed();
    const timer = setInterval(updateElapsed, 1000);
    return () => clearInterval(timer);
  }, [activeShift?.startedAt]);

  const handleOpenShiftSubmit = () => {
    const openingCash = Number(openShiftCash || 0);
    const openingVisa = Number(openShiftVisa || 0);
    if (!Number.isFinite(openingCash) || openingCash < 0 || !Number.isFinite(openingVisa) || openingVisa < 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.invalidAmount ?? 'الرجاء إدخال مبالغ صحيحة.',
        variant: 'destructive',
      });
      return;
    }

    startShiftTransition(async () => {
      const status = await handleGetPosShiftStatus();
      if ((status as any)?.success) {
        const runtimeUserActive = (((status as any).activeShift || null) as PosShiftSession | null);
        if (runtimeUserActive) {
          setShowOpenShiftDialog(false);
          setShowShiftConflictDialog(true);
          const activeShiftOwner = String(runtimeUserActive.userName || cashierName || '').trim() || 'المستخدم الحالي';
          toast({
            title: t?.shiftAlreadyOpen ?? 'لا يمكن افتتاح وردية جديدة قبل إغلاق الوردية الحالية.',
            description: t?.shiftAlreadyOpenCurrentUser ?? `لديك وردية نشطة حالياً باسم: ${activeShiftOwner}. يمكنك الاستمرار بها أو إغلاقها وبدء وردية جديدة.`,
            variant: 'destructive',
          });
          return;
        }
      }

      const result = await handleOpenPosShift({
        openingCash,
        openingVisa,
        notes: openShiftNotes,
      });

      if ((result as any)?.success) {
        setShowOpenShiftDialog(false);
        setOpenShiftNotes('');
        setCloseShiftCash('0');
        setCloseShiftVisa('0');
        loadShiftStatus(); // fire-and-forget so transition ends immediately
        toast({ title: t?.success ?? 'نجاح', description: t?.shiftOpenedSuccess ?? 'تم افتتاح الوردية بنجاح.' });
        return;
      }

      if ((result as any)?.error === 'POS_SHIFT_ALREADY_ACTIVE') {
        await loadShiftStatus();
        setShowShiftConflictDialog(true);
      }

      toast({
        title: t?.saveInvoiceError ?? 'فشل العملية',
        description: (result as any)?.error === 'POS_SHIFT_ALREADY_ACTIVE'
          ? (t?.shiftAlreadyOpen ?? 'لا يمكن افتتاح وردية جديدة قبل إغلاق الوردية الحالية.')
          : ((result as any)?.error || (t?.unexpectedError ?? 'حدث خطأ غير متوقع.')),
        variant: 'destructive',
      });
    });
  };

  const handleContinueExistingShift = () => {
    setShowShiftConflictDialog(false);
    setShowOpenShiftDialog(false);
    loadShiftStatus();
    toast({
      title: t?.success ?? 'نجاح',
      description: t?.shiftContinueExisting ?? 'تم الاستمرار بالوردية الحالية.',
    });
  };

  const handleClosePreviousAndOpenNewShift = () => {
    startShiftTransition(async () => {
      let runtimeActiveShift = activeShift;
      if (!runtimeActiveShift) {
        const status = await handleGetPosShiftStatus();
        if ((status as any)?.success) {
          runtimeActiveShift = ((status as any).activeShift || null) as PosShiftSession | null;
        }
      }

      if (runtimeActiveShift) {
        const closeResult = await handleClosePosShift({
          countedCash: Number(runtimeActiveShift.expectedCashAtClose || 0),
          countedVisa: Number(runtimeActiveShift.expectedVisaAtClose || 0),
          notes: t?.shiftAutoCloseForReopen ?? 'إغلاق تلقائي قبل افتتاح وردية جديدة',
        });

        if (!(closeResult as any)?.success) {
          const closeErrorCode = String((closeResult as any)?.error || '');
          toast({
            title: t?.saveInvoiceError ?? 'فشل العملية',
            description: closeErrorCode === 'POS_SHIFT_VARIANCE_NOT_ALLOWED'
              ? (t?.shiftVarianceNotAllowed ?? 'لا يمكن إغلاق الوردية مع وجود فروقات حسب الإعدادات.')
              : (closeErrorCode || (t?.unexpectedError ?? 'حدث خطأ غير متوقع.')),
            variant: 'destructive',
          });
          return;
        }
      }

      setActiveShift(null);
      setShowShiftConflictDialog(false);
      setOpenShiftCash('0');
      setOpenShiftVisa('0');
      setOpenShiftNotes('');
      setShowOpenShiftDialog(true);
      loadShiftStatus();
      toast({
        title: t?.success ?? 'نجاح',
        description: t?.shiftClosedPrepareNew ?? 'تم إغلاق الوردية السابقة. أدخل الأرصدة الافتتاحية لفتح وردية جديدة.',
      });
    });
  };

  const pendingInvoiceLineCount = (watchAllItems || []).filter((item) => String(item?.materialId || '').trim() && Number(item?.quantity || 0) > 0).length;
  const hasPendingInvoiceLines = pendingInvoiceLineCount > 0;
  const activeRestaurantTable = restaurantTables.find((table) => table.id === activeRestaurantTableId) || null;
  const activeRestaurantAreaName = activeRestaurantTable
    ? (restaurantAreas.find((area) => area.id === activeRestaurantTable.areaId)?.name || 'بدون منطقة')
    : '';
  const activeRestaurantAreaId = activeRestaurantTable?.areaId || '';
  const filteredRestaurantTables = useMemo(() => {
    if (selectedAreaFilter === '__all__') return restaurantTables;
    return restaurantTables.filter((table) => String(table.areaId || '') === selectedAreaFilter);
  }, [restaurantTables, selectedAreaFilter]);
  const occupiedTableIds = useMemo(
    () => new Set(suspendedInvoices.map((invoice) => String(invoice.tableId || '').trim()).filter(Boolean)),
    [suspendedInvoices],
  );

  const openCloseShiftDialogWithDefaults = async () => {
    setIsShiftLoading(true);
    try {
      const [statusResult, cashboxResult] = await Promise.all([
        Promise.race([
          handleGetPosShiftStatus(),
          new Promise((resolve) => setTimeout(() => resolve({ success: false, error: 'SHIFT_STATUS_TIMEOUT' }), 8000)),
        ]),
        handleGetEmployeeCashboxSummary(employeeCashAccountCode),
      ]);

      const runtimeActiveShift = ((statusResult as any)?.success
        ? ((statusResult as any).activeShift || null)
        : null) as PosShiftSession | null;

      if (!runtimeActiveShift) {
        setActiveShift(null);
        setShowCloseShiftDialog(false);
        toast({
          title: t?.shiftNotOpen ?? 'لا توجد وردية نشطة',
          description: t?.shiftNotOpenDesc ?? 'تعذر تحميل وردية نشطة قبل الإغلاق. حاول مرة أخرى.',
          variant: 'destructive',
        });
        return;
      }

      setActiveShift(runtimeActiveShift);

      if ((cashboxResult as any)?.success) {
        setCashboxSummary(((cashboxResult as any).summary || { openingCash: 0, cashSalesAmount: 0, expectedCashAtClose: 0 }) as CashboxSummary);
      }

      setCloseShiftCash(String(runtimeActiveShift.expectedCashAtClose || 0));
      setCloseShiftVisa(String(runtimeActiveShift.expectedVisaAtClose || 0));
      setCloseShiftNotes('');
      setShowCloseShiftDialog(true);
    } catch {
      toast({
        title: t?.saveInvoiceError ?? 'فشل العملية',
        description: t?.unexpectedError ?? 'حدث خطأ غير متوقع.',
        variant: 'destructive',
      });
    } finally {
      setIsShiftLoading(false);
    }
  };

  const clearPendingInvoiceDraft = () => {
    form.reset({ customerId: '', amountPaid: 0, payments: [], discountAmount: 0, items: [], isReturn });
    setPayments([]);
    localStorage.removeItem(posDraftInvoiceStorageKey);
    const socket = getPosDraftSocket(storageUserScope);
    socket.emit('auth', { userId: storageUserScope });
    socket.emit('draft:clear');
  };

  const handleSuspendPendingInvoiceAndContinueClose = () => {
    handleSuspend();
    setShowPendingInvoiceBeforeCloseDialog(false);
    void openCloseShiftDialogWithDefaults();
  };

  const handleDiscardPendingInvoiceAndContinueClose = () => {
    clearPendingInvoiceDraft();
    setShowPendingInvoiceBeforeCloseDialog(false);
    toast({ title: t?.invoiceCancelled ?? 'تم إلغاء الفاتورة الحالية وتفريغ الجدول.' });
    void openCloseShiftDialogWithDefaults();
  };

  const handleCloseShiftOpen = async () => {
    if (!activeShift) return;
    if (hasPendingInvoiceLines) {
      setShowPendingInvoiceBeforeCloseDialog(true);
      return;
    }
    await openCloseShiftDialogWithDefaults();
  };

  const printShiftSummary = () => {
    if (!activeShift) return;
    const totalSales = (activeShift.cashSalesAmount || 0) + (activeShift.visaSalesAmount || 0) + (activeShift.receivablesAmount || 0) + (activeShift.couponAmount || 0);
    const countedCash = Number(closeShiftCash || 0);
    const countedVisa = Number(closeShiftVisa || 0);
    const cashDiff = countedCash - (activeShift.expectedCashAtClose || 0);
    const visaDiff = countedVisa - (activeShift.expectedVisaAtClose || 0);
    const row = (label: string, value: string, bold = false) =>
      `<tr><td style="padding:4px 8px;border-bottom:1px solid #eee;color:#555">${escapePrintHtml(label)}</td><td style="padding:4px 8px;border-bottom:1px solid #eee;text-align:end;font-family:monospace;${bold ? 'font-weight:700' : ''}">${escapePrintHtml(value)}</td></tr>`;
    const divider = `<tr><td colspan="2" style="padding:2px 0"><hr style="border:none;border-top:1px solid #ddd"></td></tr>`;
    const html = `<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="UTF-8"><title>ملخص الوردية</title><style>body{font-family:Arial,sans-serif;font-size:13px;margin:20px}h2{margin:0 0 12px;font-size:16px}table{width:100%;border-collapse:collapse}@media print{body{margin:4mm}}</style></head><body><h2>ملخص الوردية</h2><table>${row('الكاشير', cashierName || '—')}${row('بداية الوردية', formatDateTimeStable(activeShift.startedAt))}${divider}${row('نقدي افتتاحي', formatCurrency(cashboxSummary.openingCash, currencySymbol))}${row('بطاقة افتتاحية', formatCurrency(activeShift.openingVisa || 0, currencySymbol))}${divider}${row('مبيعات نقدية', formatCurrency(cashboxSummary.cashSalesAmount, currencySymbol))}${row('مبيعات بطاقة', formatCurrency(activeShift.visaSalesAmount || 0, currencySymbol))}${activeShift.receivablesAmount ? row('مبيعات آجلة', formatCurrency(activeShift.receivablesAmount, currencySymbol)) : ''}${activeShift.couponAmount ? row('كوبونات', formatCurrency(activeShift.couponAmount, currencySymbol)) : ''}${row('إجمالي المبيعات', formatCurrency(totalSales, currencySymbol), true)}${divider}${row('نقدي متوقع', formatCurrency(cashboxSummary.expectedCashAtClose, currencySymbol))}${row('بطاقة متوقعة', formatCurrency(activeShift.expectedVisaAtClose || 0, currencySymbol))}${divider}${row('جرد نقدي فعلي', formatCurrency(countedCash, currencySymbol))}${row('جرد بطاقة فعلي', formatCurrency(countedVisa, currencySymbol))}${row('فرق النقد', formatCurrency(cashDiff, currencySymbol), true)}${row('فرق البطاقة', formatCurrency(visaDiff, currencySymbol), true)}${closeShiftNotes ? divider + row('ملاحظات', closeShiftNotes) : ''}</table></body></html>`;
    openPrintPreviewWindow(html);
  };

  const handleCloseShiftSubmit = () => {
    if (hasPendingInvoiceLines) {
      setShowCloseShiftDialog(false);
      setShowPendingInvoiceBeforeCloseDialog(true);
      toast({
        title: t?.closeShiftRequiresEmptyTable ?? 'لا يمكن إغلاق الوردية',
        description: t?.closeShiftRequiresEmptyTableDesc ?? 'جدول الفاتورة يحتوي أصنافاً. قم بتعليق الفاتورة أو إلغائها قبل إغلاق الوردية.',
        variant: 'destructive',
      });
      return;
    }

    if (suspendedInvoices.length > 0) {
      setShowCloseShiftDialog(false);
      toast({
        title: 'لا يمكن إغلاق الوردية',
        description: `يوجد ${suspendedInvoices.length} فاتورة/فواتير معلقة. يجب محاسبتها أو حذفها قبل إغلاق الوردية.`,
        variant: 'destructive',
      });
      return;
    }

    const countedCash = Number(closeShiftCash || 0);
    const countedVisa = Number(closeShiftVisa || 0);
    if (!Number.isFinite(countedCash) || countedCash < 0 || !Number.isFinite(countedVisa) || countedVisa < 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.invalidAmount ?? 'الرجاء إدخال مبالغ صحيحة.',
        variant: 'destructive',
      });
      return;
    }

    startShiftTransition(async () => {
      const result = await handleClosePosShift({
        countedCash,
        countedVisa,
        notes: closeShiftNotes,
      });

      if ((result as any)?.success) {
        setShowCloseShiftDialog(false);
        loadShiftStatus(); // fire-and-forget so transition ends immediately
        toast({
          title: t?.success ?? 'نجاح',
          description: (result as any)?.requiresApproval
            ? (t?.shiftClosedPendingApproval ?? 'تم إغلاق الوردية مع فروقات وتنتظر الاعتماد.')
            : (t?.shiftClosedSuccess ?? 'تم إغلاق الوردية بنجاح.'),
        });
        return;
      }

      const errorCode = String((result as any)?.error || '');
      toast({
        title: t?.saveInvoiceError ?? 'فشل العملية',
        description: errorCode === 'POS_SHIFT_NOT_ACTIVE'
          ? (t?.shiftNotOpen ?? 'لا توجد وردية نشطة لهذا المستخدم.')
          : errorCode === 'POS_SHIFT_VARIANCE_NOT_ALLOWED'
            ? (t?.shiftVarianceNotAllowed ?? 'لا يمكن إغلاق الوردية مع وجود فروقات حسب الإعدادات.')
            : (errorCode || (t?.unexpectedError ?? 'حدث خطأ غير متوقع.')),
        variant: 'destructive',
      });
    });
  };

  const effectiveScaleMode = (scaleSettings?.mode || 'manual') as 'manual' | 'hid' | 'serial';
  const isManualVolumeDialog = pendingMeasurementMode === 'volume';

  const parseScaleWeight = (raw: string): number | null => {
    const source = String(raw || '').trim();
    if (!source) return null;

    const pattern = String(scaleSettings?.readRegex || '([0-9]+(?:[\\.,][0-9]+)?)');
    let extracted = source;
    try {
      const regex = new RegExp(pattern);
      const match = source.match(regex);
      extracted = String(match?.[1] || match?.[0] || source);
    } catch {
      extracted = source;
    }

    const decimalMode = scaleSettings?.decimalSeparator || 'auto';
    let normalized = extracted;
    if (decimalMode === 'dot') {
      normalized = normalized.replace(/,/g, '.');
    } else if (decimalMode === 'comma') {
      normalized = normalized.replace(/\./g, '').replace(',', '.');
    } else {
      normalized = normalized.replace(',', '.');
    }

    const parsed = Number.parseFloat(normalized);
    if (!Number.isFinite(parsed) || parsed <= 0) return null;
    return parsed;
  };

  const applyScaleWeight = (raw: string) => {
    const parsed = parseScaleWeight(raw);
    if (parsed === null) return;
    setWeightInput(String(parsed));
  };

  const closeSerialReader = async () => {
    serialAbortRef.current = true;
    try {
      if (serialReaderRef.current) {
        await serialReaderRef.current.cancel();
        serialReaderRef.current.releaseLock();
      }
    } catch {
      // ignore
    }
    serialReaderRef.current = null;

    try {
      if (serialPortRef.current) {
        await serialPortRef.current.close();
      }
    } catch {
      // ignore
    }
    serialPortRef.current = null;
    setIsSerialConnected(false);
  };

  const startSerialReadLoop = async (port: any) => {
    serialAbortRef.current = false;
    const reader = port.readable?.getReader();
    if (!reader) return;
    serialReaderRef.current = reader;
    const decoder = new TextDecoder();
    let buffer = '';

    try {
      while (!serialAbortRef.current) {
        const { value, done } = await reader.read();
        if (done) break;
        if (!value) continue;
        buffer += decoder.decode(value, { stream: true });

        const parts = buffer.split(/\r?\n/);
        buffer = parts.pop() || '';
        for (const line of parts) {
          applyScaleWeight(line);
        }
      }
    } catch {
      // ignore disconnection/read errors
    } finally {
      try {
        reader.releaseLock();
      } catch {
        // ignore
      }
      if (serialReaderRef.current === reader) {
        serialReaderRef.current = null;
      }
      setIsSerialConnected(false);
    }
  };

  const connectSerialPort = async (preferGranted = false) => {
    if (!(navigator as any)?.serial) return;
    setIsSerialConnecting(true);
    try {
      let port: any = null;
      if (preferGranted) {
        const grantedPorts = await (navigator as any).serial.getPorts();
        if (Array.isArray(grantedPorts) && grantedPorts.length > 0) {
          port = grantedPorts[0];
        }
      }
      if (!port) {
        port = await (navigator as any).serial.requestPort();
      }

      await port.open({
        baudRate: Number(scaleSettings?.serialBaudRate || 9600),
        dataBits: Number(scaleSettings?.serialDataBits || 8),
        stopBits: Number(scaleSettings?.serialStopBits || 1),
        parity: scaleSettings?.serialParity || 'none',
      });

      serialPortRef.current = port;
      setIsSerialConnected(true);
      startSerialReadLoop(port);
    } catch {
      setIsSerialConnected(false);
    } finally {
      setIsSerialConnecting(false);
    }
  };

  useEffect(() => {
    if (!showWeightDialog) return;
    weightInputRef.current?.focus();
  }, [showWeightDialog]);

  useEffect(() => {
    if (!showWeightDialog || isManualVolumeDialog || effectiveScaleMode !== 'hid') return;
    const minLen = Number(scaleSettings?.hidMinLength || 3);

    const commit = () => {
      const chunk = hidBufferRef.current;
      hidBufferRef.current = '';
      if (!chunk || chunk.length < minLen) return;
      applyScaleWeight(chunk);
    };

    const onKeyDown = (event: KeyboardEvent) => {
      const key = event.key;
      if (/^[0-9.,-]$/.test(key)) {
        hidBufferRef.current += key;
        if (hidTimerRef.current) clearTimeout(hidTimerRef.current);
        hidTimerRef.current = setTimeout(commit, 120);
        return;
      }
      if (key === 'Enter') {
        event.preventDefault();
        commit();
      }
    };

    window.addEventListener('keydown', onKeyDown);
    return () => {
      window.removeEventListener('keydown', onKeyDown);
      if (hidTimerRef.current) clearTimeout(hidTimerRef.current);
      hidBufferRef.current = '';
    };
  }, [showWeightDialog, isManualVolumeDialog, effectiveScaleMode, scaleSettings?.hidMinLength]);

  useEffect(() => {
    if (!showWeightDialog || isManualVolumeDialog || effectiveScaleMode !== 'serial') return;
    if (!isSerialSupported) return;
    if (scaleSettings?.serialAutoConnect) {
      connectSerialPort(true);
    }
    return () => {
      closeSerialReader();
    };
  }, [showWeightDialog, isManualVolumeDialog, effectiveScaleMode, isSerialSupported, scaleSettings?.serialAutoConnect]);

  useEffect(() => {
    return () => {
      closeSerialReader();
    };
  }, []);

  useEffect(() => {
    if (!isAnyBlockingDialogOpen) {
      barcodeRef.current?.focus();
    }
  }, [isAnyBlockingDialogOpen]);

  useEffect(() => {
    if (!isAnyBlockingDialogOpen) return;
    const activeElement = document.activeElement;
    if (activeElement instanceof HTMLElement) {
      activeElement.blur();
    }
  }, [isAnyBlockingDialogOpen]);

  useEffect(() => {
    setAllItemUnits(itemUnits || []);
  }, [itemUnits]);

  useEffect(() => {
    const storedLeft = localStorage.getItem('posLayoutLeftPanelWidth');
    const storedSummary = localStorage.getItem('posLayoutSummaryPanelWidth');
    if (storedLeft) {
      const parsed = Number(storedLeft);
      if (Number.isFinite(parsed)) {
        setLeftPanelWidth(Math.min(Math.max(parsed, 260), 640));
      }
    }
    if (storedSummary) {
      const parsed = Number(storedSummary);
      if (Number.isFinite(parsed)) {
        setSummaryPanelWidth(Math.min(Math.max(parsed, 280), 520));
      }
    }
  }, []);

  useEffect(() => {
    form.setValue('isReturn', isReturn);
  }, [isReturn, form]);

  useEffect(() => {
    leftPanelWidthRef.current = leftPanelWidth;
  }, [leftPanelWidth]);

  useEffect(() => {
    summaryPanelWidthRef.current = summaryPanelWidth;
  }, [summaryPanelWidth]);

  useEffect(() => {
    const saved = localStorage.getItem(posSuspendedInvoicesStorageKey);
    if (saved) {
      try {
        setSuspendedInvoices(JSON.parse(saved));
      } catch {
        setSuspendedInvoices([]);
      }
      return;
    }
    setSuspendedInvoices([]);
  }, [posSuspendedInvoicesStorageKey]);

  useEffect(() => {
    if (!restaurantPosEnabled) return;
    const savedTable = String(localStorage.getItem(posActiveRestaurantTableStorageKey) || '').trim();
    if (!savedTable) return;
    if (!restaurantTables.some((table) => table.id === savedTable)) return;
    setActiveRestaurantTableId(savedTable);
  }, [restaurantPosEnabled, restaurantTables, posActiveRestaurantTableStorageKey]);

  useEffect(() => {
    if (!restaurantPosEnabled) return;
    if (!activeRestaurantTableId) {
      localStorage.removeItem(posActiveRestaurantTableStorageKey);
      return;
    }
    localStorage.setItem(posActiveRestaurantTableStorageKey, activeRestaurantTableId);
  }, [restaurantPosEnabled, activeRestaurantTableId, posActiveRestaurantTableStorageKey]);

  useEffect(() => {
    const draft = localStorage.getItem(posDraftInvoiceStorageKey);
    if (draft) {
      try {
        const parsed = JSON.parse(draft);
        if (parsed && typeof parsed === 'object') {
          form.reset({
            customerId: parsed.customerId || '',
            amountPaid: parsed.amountPaid || 0,
            payments: Array.isArray(parsed.payments) ? parsed.payments : [],
            discountAmount: parsed.discountAmount || 0,
            items: Array.isArray(parsed.items) ? parsed.items : [],
            isReturn: !!parsed.isReturn,
          });
          setPayments(Array.isArray(parsed.payments) ? parsed.payments : []);
          setIsReturn(!!parsed.isReturn);
        }
      } catch {
        // ignore invalid draft
      }
      return;
    }
    form.reset({
      customerId: '',
      amountPaid: 0,
      payments: [],
      discountAmount: 0,
      items: [],
      isReturn: false,
    });
    setPayments([]);
    setIsReturn(false);
  }, [form, posDraftInvoiceStorageKey]);

  useEffect(() => {
    if (!storageUserScope) return;

    const socket = getPosDraftSocket(storageUserScope);
    socket.emit('auth', { userId: storageUserScope });

    const handleDraftInit = (draft: any) => {
      if (!draft || typeof draft !== 'object') return;

      if ('customerId' in draft) form.setValue('customerId', String(draft.customerId || ''));
      if ('amountPaid' in draft) form.setValue('amountPaid', Number(draft.amountPaid || 0));
      if ('items' in draft) form.setValue('items', Array.isArray(draft.items) ? draft.items : []);
      if ('discountAmount' in draft) form.setValue('discountAmount', Number(draft.discountAmount || 0));
      if ('payments' in draft) {
        const nextPayments = Array.isArray(draft.payments) ? draft.payments : [];
        form.setValue('payments', nextPayments);
        setPayments(nextPayments as any);
      }
      if ('isReturn' in draft) {
        const nextIsReturn = Boolean(draft.isReturn);
        form.setValue('isReturn', nextIsReturn);
        setIsReturn(nextIsReturn);
      }
    };

    socket.on('draft:init', handleDraftInit);

    const subscription = form.watch((values, { name }) => {
      if (!name) return;

      if (name === 'customerId') {
        socket.emit('draft:diff', { op: 'set', path: 'customerId', value: values.customerId || '' });
      }
      if (name === 'amountPaid') {
        socket.emit('draft:diff', { op: 'set', path: 'amountPaid', value: values.amountPaid || 0 });
      }
      if (name === 'items') {
        socket.emit('draft:diff', { op: 'set', path: 'items', value: values.items || [] });
      }
      if (name === 'discountAmount') {
        socket.emit('draft:diff', { op: 'set', path: 'discountAmount', value: values.discountAmount || 0 });
      }
      if (name === 'payments') {
        socket.emit('draft:diff', { op: 'set', path: 'payments', value: values.payments || [] });
      }
      if (name === 'isReturn') {
        socket.emit('draft:diff', { op: 'set', path: 'isReturn', value: Boolean(values.isReturn) });
      }
    });

    return () => {
      socket.off('draft:init', handleDraftInit);
      subscription?.unsubscribe?.();
    };
  }, [form, storageUserScope]);

  useEffect(() => {
    localStorage.setItem(posSuspendedInvoicesStorageKey, JSON.stringify(suspendedInvoices));
  }, [suspendedInvoices, posSuspendedInvoicesStorageKey]);

  useEffect(() => {
    const interval = setInterval(() => {
      const payload = {
        customerId: form.getValues('customerId'),
        amountPaid: form.getValues('amountPaid') || 0,
        payments: form.getValues('payments') || [],
        discountAmount: form.getValues('discountAmount') || 0,
        items: form.getValues('items') || [],
        isReturn,
        savedAt: new Date().toISOString(),
      };
      localStorage.setItem(posDraftInvoiceStorageKey, JSON.stringify(payload));
      setLastAutosaveAt(payload.savedAt);
    }, 1000);
    return () => clearInterval(interval);
  }, [form, isReturn, payments, posDraftInvoiceStorageKey]);

  const allMaterials = useMemo(() => {
    const merged: ProductionItem[] = [];
    const seen = new Set<string>();
    for (const item of materials) {
      if (!item?.id || seen.has(item.id)) continue;
      merged.push(item);
      seen.add(item.id);
    }
    for (const item of extraMaterials) {
      if (!item?.id || seen.has(item.id)) continue;
      merged.push(item);
      seen.add(item.id);
    }
    return merged;
  }, [extraMaterials, materials]);

  const availableLocationsByMaterial = useMemo(() => {
    const map = new Map<string, StockLocationBalance[]>();
    Object.entries(stockLocationsByMaterial || {}).forEach(([materialId, locations]) => {
      const validLocations = (locations || [])
        .filter((location) => Number(location.quantity || 0) > 0)
        .sort((a, b) => Number(b.quantity || 0) - Number(a.quantity || 0));
      map.set(materialId, validLocations);
    });
    return map;
  }, [stockLocationsByMaterial]);

  const warehouseNameById = useMemo(() => {
    const map = new Map<string, string>();
    (warehouses || []).forEach((warehouse) => {
      map.set(warehouse.id, warehouse.name);
    });
    return map;
  }, [warehouses]);

  const shelfNameById = useMemo(() => {
    const map = new Map<string, string>();
    (warehouses || []).forEach((warehouse) => {
      (warehouse.shelves || []).forEach((shelf) => {
        map.set(shelf.id, shelf.name);
      });
    });
    return map;
  }, [warehouses]);

  const resolveDefaultSourceForMaterial = (materialId: string) => {
    if (!isWarehouseEnabled) {
      return { warehouseId: '', shelfId: '' };
    }

    const locations = availableLocationsByMaterial.get(materialId) || [];
    if (locations.length === 1) {
      return {
        warehouseId: locations[0].warehouseId,
        shelfId: locations[0].shelfId,
      };
    }

    if (defaultWarehouseId && defaultShelfId) {
      const match = locations.find(
        (location) => location.warehouseId === defaultWarehouseId && location.shelfId === defaultShelfId
      );
      if (match) {
        return {
          warehouseId: match.warehouseId,
          shelfId: match.shelfId,
        };
      }

      if (allowOutOfStockSales) {
        return {
          warehouseId: defaultWarehouseId,
          shelfId: defaultShelfId,
        };
      }
    }

    return { warehouseId: '', shelfId: '' };
  };

  useEffect(() => {
    if (!isWarehouseEnabled) return;

    (watchAllItems || []).forEach((item, index) => {
      const materialId = String(item?.materialId || '').trim();
      if (!materialId) return;

      const locations = availableLocationsByMaterial.get(materialId) || [];
      if (locations.length !== 1) return;

      const autoLocation = locations[0];
      const currentWarehouseId = String((item as any)?.warehouseId || '').trim();
      const currentShelfId = String((item as any)?.shelfId || '').trim();
      if (currentWarehouseId !== autoLocation.warehouseId) {
        form.setValue(`items.${index}.warehouseId`, autoLocation.warehouseId);
      }
      if (currentShelfId !== autoLocation.shelfId) {
        form.setValue(`items.${index}.shelfId`, autoLocation.shelfId);
      }
    });
  }, [watchAllItems, isWarehouseEnabled, availableLocationsByMaterial, form]);

  const selectedCustomer = useMemo(() => customerList.find(c => c.id === selectedCustomerId), [customerList, selectedCustomerId]);
  const customerPricing = useMemo(() => {
    const category = selectedCustomer?.category || 'general';
    return allCustomerPricing.find(p => p.category === category);
  }, [selectedCustomer, allCustomerPricing]);

  const customerPriceByMaterialId = useMemo(() => {
    const map = new Map<string, number>();
    const prices = Array.isArray(customerPricing?.prices) ? customerPricing.prices : [];
    prices.forEach((price) => {
      const materialId = String(price?.materialId || '').trim();
      if (!materialId) return;
      map.set(materialId, Number(price?.price || 0));
    });
    return map;
  }, [customerPricing]);

  const campaignPreview = useMemo(() => {
    return computeCampaignLivePreview({
      lines: (watchAllItems || []).map((item, index) => ({
        lineKey: String(index),
        materialId: String(item?.materialId || '').trim(),
        quantity: Number(item?.quantity || 0),
        unitPrice: Number(item?.unitPrice || 0),
        currentDiscount: Number(item?.discount || 0),
      })),
      campaigns,
      customerCategory: String(selectedCustomer?.category || 'general'),
      atIso: new Date().toISOString(),
      forPos: true,
      isReturn,
    });
  }, [watchAllItems, campaigns, selectedCustomer, isReturn]);

  const posGroups = useMemo(() => (itemGroups || []).filter(g => g.isPosEnabled), [itemGroups]);
  const visibleGroups = useMemo(() => {
    if (showAllGroups) return posGroups;
    if (!activeGroupId) return posGroups.slice(0, 1);
    return posGroups.filter(g => g.id === activeGroupId);
  }, [posGroups, showAllGroups, activeGroupId]);
  const measuredItemsCount = useMemo(() => allMaterials.filter((material) => isMaterialMeasured(material)).length, [allMaterials]);
  const trackedItemsCount = useMemo(() => allMaterials.filter((material) => isTrackedMaterial(material)).length, [allMaterials]);

  useEffect(() => {
    if (posGroups.length === 0) {
      setActiveGroupId('');
    }
  }, [posGroups.length]);

  useEffect(() => {
    if (!showGroupsPicker) return;
    if (!activeGroupId || !posGroups.find(g => g.id === activeGroupId)) {
      setActiveGroupId(posGroups[0]?.id || '');
    }
  }, [showGroupsPicker, posGroups, activeGroupId]);

  const getMaterialUnitPricing = (material: ProductionItem) => {
    const priceInfo = customerPricing?.prices.find(p => p.materialId === material.id);
    const primaryPrice = Number(priceInfo?.price ?? material.salePrice ?? 0);
    const firstSecondary = Array.isArray(material.secondaryUnits) && material.secondaryUnits.length > 0
      ? material.secondaryUnits[0]
      : undefined;
    const conversionQty = Number(firstSecondary?.quantity ?? material.secondaryUnitQuantity ?? 0);
    const explicitSecondaryPrice = firstSecondary?.price;
    const secondaryPrice = Number.isFinite(Number(explicitSecondaryPrice))
      ? Number(explicitSecondaryPrice)
      : (typeof material.secondaryUnitPrice === 'number'
          ? material.secondaryUnitPrice
          : (conversionQty > 0 ? primaryPrice / conversionQty : undefined));

    return {
      primaryPrice,
      conversionQty,
      secondaryPrice: typeof secondaryPrice === 'number' && Number.isFinite(secondaryPrice) ? secondaryPrice : undefined,
      primaryUnitLabel: material.primaryUnit || '-',
      secondaryUnitLabel: String(firstSecondary?.unit || material.secondaryUnit || material.primaryUnit || '-'),
    };
  };

  const getSecondaryVolumeOptions = (material: ProductionItem, primaryPrice: number) => {
    const fromArray = Array.isArray(material.secondaryUnits)
      ? material.secondaryUnits
          .map((entry, index) => {
            const unitLabel = String(entry?.unit || '').trim();
            if (!unitLabel) return null;
            const quantity = Number(entry?.quantity || 0);
            const explicit = Number(entry?.price);
            const computedPrice = Number.isFinite(explicit)
              ? explicit
              : (quantity > 0 ? (primaryPrice / quantity) : primaryPrice);
            return {
              key: `secondary-${index}`,
              label: unitLabel,
              price: computedPrice,
              barcode: String(entry?.barcode || '').trim(),
            };
          })
          .filter((entry): entry is { key: string; label: string; price: number; barcode: string } => !!entry)
      : [];

    if (fromArray.length > 0) return fromArray;

    const legacyLabel = String(material.secondaryUnit || '').trim();
    if (!legacyLabel) return [];
    const qty = Number(material.secondaryUnitQuantity || 0);
    const price = typeof material.secondaryUnitPrice === 'number'
      ? Number(material.secondaryUnitPrice)
      : (qty > 0 ? (primaryPrice / qty) : primaryPrice);
    return [{ key: 'legacy-secondary', label: legacyLabel, price, barcode: String(material.secondaryBarcode || '').trim() }];
  };

  const getUnitPriceForMaterial = (material: ProductionItem) => {
    return getMaterialUnitPricing(material).primaryPrice;
  };

  const getMaterialDisplayLabel = (material?: ProductionItem | null) => {
    const name = String(material?.name || '').trim();
    const symbol = String(material?.itemSymbolName || '').trim();
    if (!name) return '';
    return symbol ? `${name} - ${symbol}` : name;
  };

  function isTrackedMaterial(material: ProductionItem) {
    return material?.hasSerialNumber === true || material?.hasRfid === true;
  }

  const normalizeCode = (value: string) => String(value || '').trim().toLowerCase();

  const getAvailableUnitsForMaterial = (material: ProductionItem | null) => {
    if (!material) return [] as ItemUnit[];
    const alreadySelected = new Set(
      (watchAllItems || [])
        .map((line) => String((line as any)?.itemUnitId || '').trim())
        .filter(Boolean)
    );
    return (allItemUnits || []).filter((unit) => {
      if (unit.itemId !== material.id) return false;
      if (unit.status === 'sold' || unit.status === 'damaged') return false;
      if (alreadySelected.has(unit.id)) return false;
      return true;
    });
  };

  const getTrackedUnitLabel = (unit: ItemUnit) => {
    const serial = String(unit.serialNumber || '').trim();
    const rfid = String(unit.rfidCode || '').trim();
    if (serial && rfid) return `${serial} / ${rfid}`;
    return serial || rfid || unit.id;
  };

  const getTrackedUnitForLine = (line: any) => {
    const unitId = String(line?.itemUnitId || '').trim();
    if (!unitId) return null;
    return (allItemUnits || []).find((unit) => unit.id === unitId) || null;
  };

  const isTrackedLineMissingUnit = (line: any) => {
    const materialId = String(line?.materialId || '').trim();
    if (!materialId) return false;
    const material = allMaterials.find((entry) => entry.id === materialId);
    if (!material || !isTrackedMaterial(material)) return false;
    return !String(line?.itemUnitId || '').trim();
  };

  const filteredTrackedUnits = useMemo(() => {
    const units = getAvailableUnitsForMaterial(pendingTrackedMaterial);
    const query = normalizeCode(trackedUnitSearch);
    if (!query) return units;
    return units.filter((unit) => {
      const haystack = [
        unit.serialNumber,
        unit.rfidCode,
        unit.notes,
        unit.location,
        unit.status,
      ]
        .map((value) => normalizeCode(String(value || '')))
        .join(' ');
      return haystack.includes(query);
    });
  }, [pendingTrackedMaterial, trackedUnitSearch, allItemUnits, watchAllItems]);

  const closeTrackedUnitDialog = () => {
    setShowTrackedUnitDialog(false);
    setPendingTrackedMaterial(null);
    setPendingTrackedUnitPrice(0);
    setPendingTrackedDescription('');
    setTrackedUnitSearch('');
    requestAnimationFrame(() => barcodeRef.current?.focus());
  };

  const openTrackedUnitDialog = (material: ProductionItem, unitPrice: number, description: string, initialSearch = '') => {
    setPendingTrackedMaterial(material);
    setPendingTrackedUnitPrice(unitPrice);
    setPendingTrackedDescription(description || material.name);
    setTrackedUnitSearch(initialSearch);
    setShowTrackedUnitDialog(true);
  };

  const handleSelectTrackedUnit = (unit: ItemUnit) => {
    if (!pendingTrackedMaterial) return;
    const description = (pendingTrackedDescription || pendingTrackedMaterial.name || '').trim();
    const sourceLocation = resolveDefaultSourceForMaterial(pendingTrackedMaterial.id);
    addOrIncrementItem(
      pendingTrackedMaterial.id,
      pendingTrackedUnitPrice,
      1,
      description,
      {
        itemUnitId: unit.id,
        serialNumber: unit.serialNumber,
        rfidCode: unit.rfidCode,
      },
      sourceLocation
    );
    toast({
      title: t?.itemAdded ?? 'تمت إضافة الصنف',
      description: `${description}: ${getTrackedUnitLabel(unit)}`,
    });
    closeTrackedUnitDialog();
  };

  const getActiveProductShapes = (material: ProductionItem): ProductShape[] => {
    if (!material?.usesProductShapes || !Array.isArray(material.productShapes)) return [];
    return material.productShapes.filter((shape) => {
      const name = String(shape?.name || '').trim();
      const salePrice = Number(shape?.salePrice);
      return shape?.isActive !== false && name.length > 0 && Number.isFinite(salePrice) && salePrice >= 0;
    });
  };

  const toLocalDateKey = (value: string | Date) => {
    const dt = typeof value === 'string' ? new Date(value) : value;
    if (Number.isNaN(dt.getTime())) return '';
    const local = new Date(dt.getTime() - dt.getTimezoneOffset() * 60000);
    return local.toISOString().slice(0, 10);
  };

  const resolveMaterialByBarcode = (barcode: string) => {
    const normalized = barcode.trim();
    for (const material of allMaterials) {
      const primaryBarcodes = [material.barcode, ...(material.additionalBarcodes || [])].filter(Boolean);
      const isPrimary = primaryBarcodes.includes(normalized);
      const secondaryOptions = getSecondaryVolumeOptions(material, Number(material.salePrice || 0));
      const matchedSecondary = secondaryOptions.find((option) => option.barcode && option.barcode === normalized);
      const isSecondary = material.secondaryBarcode === normalized || !!matchedSecondary;
      if (!isPrimary && !isSecondary) continue;

      const pricing = getMaterialUnitPricing(material);
      const primaryPrice = pricing.primaryPrice;
      const secondaryPrice = typeof pricing.secondaryPrice === 'number' ? pricing.secondaryPrice : primaryPrice;

      return {
        material,
        unitPrice: isSecondary
          ? Number(matchedSecondary?.price ?? secondaryPrice)
          : primaryPrice,
        unitType: isSecondary ? 'secondary' : 'primary',
        matchedSecondaryKey: matchedSecondary?.key,
      } as const;
    }
    return null;
  };

  function isMaterialWeighed(material: ProductionItem) {
    return material.isWeighed === true;
  }

  function isMaterialSized(material: ProductionItem) {
    return (material as any).isSized === true;
  }

  function isMaterialMeasured(material: ProductionItem) {
    return isMaterialWeighed(material) || isMaterialSized(material);
  }

  function resolveMeasurementMode(material: ProductionItem): 'weight' | 'volume' {
    if (isMaterialWeighed(material)) return 'weight';
    if (isMaterialSized(material)) return 'volume';
    return 'weight';
  }

  const openMeasurementDialog = (
    material: ProductionItem,
    description: string,
    source?: { unitType?: 'primary' | 'secondary'; matchedSecondaryKey?: string }
  ) => {
    const pricing = getMaterialUnitPricing(material);
    const mode = resolveMeasurementMode(material);

    setPendingMeasurementMode(mode);
    setPendingWeightMaterial(material);
    setPendingWeightPrimaryPrice(pricing.primaryPrice);
    setWeightInput('');

    if (mode === 'volume') {
      const options = getSecondaryVolumeOptions(material, pricing.primaryPrice);
      setPendingVolumeOptions(options);
      const preferredKey = source?.unitType === 'secondary'
        ? (source?.matchedSecondaryKey || options[0]?.key || '')
        : (options[0]?.key || '');
      setSelectedVolumeOptionKey(preferredKey);
      const selected = options.find((option) => option.key === preferredKey) || options[0];
      const selectedPrice = Number(selected?.price ?? pricing.secondaryPrice ?? pricing.primaryPrice);
      const selectedLabel = String(selected?.label || '').trim();
      setPendingWeightUnitPrice(selectedPrice);
      setPendingWeightDescription(selectedLabel ? `${description} - ${selectedLabel}` : description);
    } else {
      setPendingVolumeOptions([]);
      setSelectedVolumeOptionKey('');
      setPendingWeightUnitPrice(typeof pricing.secondaryPrice === 'number' ? pricing.secondaryPrice : pricing.primaryPrice);
      setPendingWeightDescription(description);
    }

    setShowWeightDialog(true);
  };

  const addOrIncrementItem = (
    materialId: string,
    unitPrice: number,
    quantity: number,
    description: string,
    tracked?: { itemUnitId?: string; serialNumber?: string; rfidCode?: string },
    sourceLocation?: { warehouseId?: string; shelfId?: string }
  ) => {
    const normalizedDescription = (description || '').trim();
    const normalizedUnitId = String(tracked?.itemUnitId || '').trim();
    const targetWarehouseId = isWarehouseEnabled ? String(sourceLocation?.warehouseId || '').trim() : '';
    const targetShelfId = isWarehouseEnabled ? String(sourceLocation?.shelfId || '').trim() : '';
    const existingItemIndex = watchAllItems.findIndex(
      item => item.materialId === materialId
        && Number(item.unitPrice) === Number(unitPrice)
        && String((item as any).itemUnitId || '').trim() === normalizedUnitId
        && ((item.description || '').trim() === normalizedDescription)
        && (!isWarehouseEnabled || (
          String((item as any).warehouseId || '').trim() === targetWarehouseId
          && String((item as any).shelfId || '').trim() === targetShelfId
        ))
    );

    if (existingItemIndex >= 0) {
      const currentQuantity = form.getValues(`items.${existingItemIndex}.quantity`) || 0;
      form.setValue(`items.${existingItemIndex}.quantity`, currentQuantity + quantity);
      return currentQuantity + quantity;
    }

    append({
      materialId,
      quantity,
      unitPrice,
      description: normalizedDescription,
      discount: 0,
      itemUnitId: normalizedUnitId || '',
      serialNumber: String(tracked?.serialNumber || '').trim(),
      rfidCode: String(tracked?.rfidCode || '').trim(),
      warehouseId: targetWarehouseId,
      shelfId: targetShelfId,
    } as any);
    return quantity;
  };

  const openShapeDialogForMaterial = (material: ProductionItem, baseUnitPrice: number, barcode?: string) => {
    const activeShapes = getActiveProductShapes(material);
    if (activeShapes.length === 0) {
      return false;
    }

    setPendingShapeMaterial(material);
    setPendingShapeBasePrice(baseUnitPrice);
    setPendingShapeBarcode(barcode);
    setSelectedShapeId(activeShapes[0]?.id || '');
    setShowShapeDialog(true);
    return true;
  };

  const handleBarcodeScanned = (barcode: string) => {
    const normalizedBarcode = normalizeCode(barcode);
    const matchedUnit = (allItemUnits || []).find((unit) => {
      const serial = normalizeCode(unit.serialNumber || '');
      const rfid = normalizeCode(unit.rfidCode || '');
      return (serial && serial === normalizedBarcode) || (rfid && rfid === normalizedBarcode);
    });

    if (matchedUnit) {
      const material = allMaterials.find((item) => item.id === matchedUnit.itemId);
      if (!material) {
        toast({
          title: t?.validationError ?? 'خطأ في التحقق',
          description: t?.trackedMaterialMissing ?? 'الوحدة مرتبطة بصنف غير موجود.',
          variant: 'destructive',
        });
        setBarcodeInput('');
        requestAnimationFrame(() => barcodeRef.current?.focus());
        return;
      }

      const alreadySelected = (watchAllItems || []).some((line) => String((line as any)?.itemUnitId || '').trim() === matchedUnit.id);
      if (alreadySelected) {
        toast({
          title: t?.validationError ?? 'خطأ في التحقق',
          description: t?.trackedUnitAlreadySelected ?? 'تمت إضافة هذه الوحدة بالفعل في الفاتورة.',
          variant: 'destructive',
        });
        setBarcodeInput('');
        requestAnimationFrame(() => barcodeRef.current?.focus());
        return;
      }

      if (matchedUnit.status === 'sold' || matchedUnit.status === 'damaged') {
        toast({
          title: t?.validationError ?? 'خطأ في التحقق',
          description: t?.trackedUnitUnavailable ?? 'هذه الوحدة غير متاحة للبيع.',
          variant: 'destructive',
        });
        setBarcodeInput('');
        requestAnimationFrame(() => barcodeRef.current?.focus());
        return;
      }

      const unitPrice = getUnitPriceForMaterial(material);
      const sourceLocation = resolveDefaultSourceForMaterial(material.id);
      addOrIncrementItem(material.id, unitPrice, 1, material.name, {
        itemUnitId: matchedUnit.id,
        serialNumber: matchedUnit.serialNumber,
        rfidCode: matchedUnit.rfidCode,
      }, sourceLocation);
      toast({
        title: t?.itemAdded ?? 'تمت إضافة الصنف',
        description: `${material.name}: ${getTrackedUnitLabel(matchedUnit)}`,
      });
      setBarcodeInput('');
      requestAnimationFrame(() => barcodeRef.current?.focus());
      return;
    }

    const resolved = resolveMaterialByBarcode(barcode);
    if (!resolved) {
      setNotFoundBarcode(barcode.trim());
      setShowAddBarcodeDialog(true);
      return;
    }

    if (isMaterialMeasured(resolved.material)) {
      if (openShapeDialogForMaterial(resolved.material, resolved.unitPrice, barcode.trim())) {
        setBarcodeInput('');
        return;
      }
      openMeasurementDialog(resolved.material, resolved.material.name, {
        unitType: resolved.unitType,
        matchedSecondaryKey: resolved.matchedSecondaryKey,
      });
      setBarcodeInput('');
      return;
    }

    if (openShapeDialogForMaterial(resolved.material, resolved.unitPrice, barcode.trim())) {
      setBarcodeInput('');
      return;
    }

    if (isTrackedMaterial(resolved.material)) {
      openTrackedUnitDialog(resolved.material, resolved.unitPrice, resolved.material.name, barcode.trim());
      setBarcodeInput('');
      return;
    }

    const resolvedSource = resolveDefaultSourceForMaterial(resolved.material.id);
    const updated = addOrIncrementItem(resolved.material.id, resolved.unitPrice, 1, resolved.material.name, undefined, resolvedSource);
    toast({
      title: t?.itemAdded ?? 'تمت إضافة الصنف',
      description: `${resolved.material.name}: ${updated}`,
    });
    setBarcodeInput('');
    requestAnimationFrame(() => barcodeRef.current?.focus());
  };

  const handleAddMaterial = (material: ProductionItem) => {
    const unitPrice = getUnitPriceForMaterial(material);

    if (openShapeDialogForMaterial(material, unitPrice)) {
      return;
    }

    if (isTrackedMaterial(material)) {
      openTrackedUnitDialog(material, unitPrice, material.name);
      return;
    }

    if (isMaterialMeasured(material)) {
      openMeasurementDialog(material, material.name, { unitType: 'primary' });
      return;
    }

    const defaultSource = resolveDefaultSourceForMaterial(material.id);
    const updated = addOrIncrementItem(material.id, unitPrice, 1, material.name, undefined, defaultSource);
    toast({
      title: t?.itemAdded ?? 'تمت إضافة الصنف',
      description: `${material.name}: ${updated}`,
    });
    requestAnimationFrame(() => barcodeRef.current?.focus());
  };

  const handleConfirmProductShape = (shapeId?: string) => {
    if (!pendingShapeMaterial) return;

    const activeShapes = getActiveProductShapes(pendingShapeMaterial);
    const selectedShape = activeShapes.find((shape) => String(shape.id) === String(shapeId || selectedShapeId)) || activeShapes[0];
    if (!selectedShape) {
      setShowShapeDialog(false);
      setPendingShapeMaterial(null);
      setPendingShapeBasePrice(0);
      setPendingShapeBarcode(undefined);
      setSelectedShapeId('');
      requestAnimationFrame(() => barcodeRef.current?.focus());
      return;
    }

    const shapePrice = Number(selectedShape.salePrice);
    const unitPrice = Number.isFinite(shapePrice) ? shapePrice : pendingShapeBasePrice;
    const shapeLabel = String(selectedShape.name || '').trim();
    const description = `${pendingShapeMaterial.name} - ${shapeLabel}`;

    if (isTrackedMaterial(pendingShapeMaterial)) {
      setShowShapeDialog(false);
      openTrackedUnitDialog(pendingShapeMaterial, unitPrice, description, pendingShapeBarcode || '');
      setPendingShapeMaterial(null);
      setPendingShapeBasePrice(0);
      setPendingShapeBarcode(undefined);
      setSelectedShapeId('');
      setBarcodeInput('');
      return;
    }

    if (isMaterialMeasured(pendingShapeMaterial)) {
      openMeasurementDialog(pendingShapeMaterial, description, { unitType: 'primary' });
      setShowShapeDialog(false);
      setPendingShapeMaterial(null);
      setPendingShapeBasePrice(0);
      setPendingShapeBarcode(undefined);
      setSelectedShapeId('');
      setBarcodeInput('');
      return;
    }

    const shapeSource = resolveDefaultSourceForMaterial(pendingShapeMaterial.id);
    const updated = addOrIncrementItem(pendingShapeMaterial.id, unitPrice, 1, description, undefined, shapeSource);
    toast({
      title: t?.itemAdded ?? 'تمت إضافة الصنف',
      description: `${description}: ${updated}`,
    });

    setShowShapeDialog(false);
    setPendingShapeMaterial(null);
   
    setSelectedShapeId('');
    setBarcodeInput('');
    requestAnimationFrame(() => barcodeRef.current?.focus());
  };

  const handleMaterialCreated = (material: ProductionItem) => {
    setExtraMaterials((prev) => {
      if (prev.find(m => m.id === material.id) || materials.find(m => m.id === material.id)) {
        return prev;
      }
      return [material, ...prev];
    });
    handleAddMaterial(material);
    setNotFoundBarcode('');
  };

  const activeGroupMaterials = useMemo(() => {
    if (!activeGroupId) return [];
    return allMaterials.filter(m => m.groupId === activeGroupId);
  }, [allMaterials, activeGroupId]);

  const itemsWithDetails = useMemo(() => {
    return watchAllItems.map((item, index) => {
      const material = allMaterials.find(m => m.id === item.materialId);
      if (!material) return null;

      const priceInfo = customerPricing?.prices.find(p => p.materialId === material.id);
      const primaryPrice = priceInfo?.price ?? material.salePrice ?? 0;
      const secondaryPrice = typeof material.secondaryUnitPrice === 'number'
        ? material.secondaryUnitPrice
        : material.secondaryUnitQuantity
          ? primaryPrice / material.secondaryUnitQuantity
          : undefined;
      const isSecondary = typeof secondaryPrice === 'number' && Math.abs((item.unitPrice || 0) - secondaryPrice) < 0.0001;
      const lineSubtotal = (item.quantity || 0) * (item.unitPrice || 0);
      const rawDiscount = Number(item.discount || 0);
      const campaignPreviewDiscount = Number(campaignPreview.discountByLineKey[String(index)] || 0);
      const lineDiscount = Math.min(Math.max(rawDiscount + campaignPreviewDiscount, 0), lineSubtotal);
      const description = (item.description || '').trim() || material.name;
      const warehouseId = isWarehouseEnabled ? String((item as any)?.warehouseId || '').trim() : '';
      const shelfId = isWarehouseEnabled ? String((item as any)?.shelfId || '').trim() : '';
      const warehouseName = warehouseNameById.get(warehouseId) || warehouseId;
      const shelfName = shelfNameById.get(shelfId) || shelfId;
      const allowDescriptionEdit = material.allowDescriptionEdit === true;
      let bonus = 0;
      const bonusRule = customerPricing?.bonus;
      if (!isReturn && bonusRule && bonusRule.materialId === item.materialId && bonusRule.buyQuantity > 0 && item.quantity > 0) {
        bonus = Math.floor(item.quantity / bonusRule.buyQuantity) * bonusRule.bonusQuantity;
      }

      return {
        name: material.name,
        description,
        allowDescriptionEdit,
        itemNumber: material.itemNumber || material.id,
        unitLabel: isSecondary ? (material.secondaryUnit || '-') : (material.primaryUnit || '-'),
        unitBarcode: isSecondary ? (material.secondaryBarcode || '-') : (material.barcode || '-'),
        warehouseId,
        shelfId,
        warehouseName,
        shelfName,
        bonus,
        lineSubtotal,
        lineDiscount,
        campaignPreviewDiscount,
        total: (lineSubtotal - lineDiscount) * (isReturn ? -1 : 1),
      };
    }).filter(Boolean);
  }, [watchAllItems, allMaterials, customerPricing, isReturn, isWarehouseEnabled, warehouseNameById, shelfNameById, campaignPreview]);

  const itemDiscountTotal = useMemo(() => (itemsWithDetails || []).reduce((sum, item) => sum + (item?.lineDiscount ?? 0), 0), [itemsWithDetails]);
  const campaignDiscountTotal = useMemo(() => Number(campaignPreview.totalCampaignDiscount || 0), [campaignPreview]);
  const itemsSubTotal = useMemo(() => (itemsWithDetails || []).reduce((sum, item) => sum + (item?.lineSubtotal ?? 0), 0), [itemsWithDetails]);
  const customerDiscount = useMemo(() => ((itemsSubTotal - itemDiscountTotal) * (selectedCustomer?.allowedDiscount || 0)) / 100, [itemsSubTotal, itemDiscountTotal, selectedCustomer]);
  const safeInvoiceDiscount = useMemo(() => {
    const base = Math.max((itemsSubTotal - itemDiscountTotal) - customerDiscount, 0);
    return Math.min(Math.max(Number(watchedDiscountAmount || 0), 0), base);
  }, [itemsSubTotal, itemDiscountTotal, customerDiscount, watchedDiscountAmount]);
  const totalAfterDiscount = useMemo(() => {
    const base = (itemsSubTotal - itemDiscountTotal) - customerDiscount - safeInvoiceDiscount;
    return isReturn ? -base : base;
  }, [itemsSubTotal, itemDiscountTotal, customerDiscount, safeInvoiceDiscount, isReturn]);
  
  // Calculate total paid from either single amountPaid or payments array
  const totalPaid = useMemo(() => {
    if (payments && payments.length > 0) {
      return payments.reduce((sum, p) => sum + (p.amount || 0), 0);
    }
    return watchedAmountPaid || 0;
  }, [payments, watchedAmountPaid]);
  
  const amountDue = useMemo(() => totalAfterDiscount - totalPaid, [totalAfterDiscount, totalPaid]);
  const applyPayments = (nextPayments: PosPaymentBreakdown) => {
    setPayments(nextPayments);
    form.setValue('payments', nextPayments);
    form.setValue('amountPaid', nextPayments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0));
  };

  const requestFinalizeInvoice = (action: 'save' | 'savePrint') => {
    if (isSaveInvoicePending || !isShiftOpen) return;
    shouldPrintAfterSaveRef.current = action === 'savePrint';
    setPendingFinalizeAction(action);
    setPaymentModalOpen(true);
  };

  const getPartialQtyForIndex = (idx: number) => {
    const maxQty = Math.max(1, Number(watchAllItems[idx]?.quantity ?? 1));
    if (idx === partialPayRowIndex) {
      return Math.max(1, Math.min(Number(partialPayRowQty || 1), maxQty));
    }
    return maxQty;
  };

  const partialPayTotal = useMemo(() => partialPaySelectedIndexes.reduce((sum, idx) => {
    const line = watchAllItems[idx];
    if (!line) return sum;
    const qty = getPartialQtyForIndex(idx);
    const fullQty = Math.max(1, Number(line.quantity || 1));
    const fullLineTotal = Math.abs(Number(itemsWithDetails[idx]?.total ?? (Number(line.unitPrice || 0) * fullQty)));
    const unitTotal = fullLineTotal / fullQty;
    return sum + (qty * unitTotal);
  }, 0), [partialPaySelectedIndexes, watchAllItems, itemsWithDetails, partialPayRowIndex, partialPayRowQty]);

  const handleSubmitPartialPayment = () => {
    if (!isShiftOpen) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.shiftRequiredBeforeSale ?? 'يجب افتتاح الوردية قبل حفظ أي فاتورة.',
        variant: 'destructive',
      });
      return;
    }

    const selectedEntries = Array.from(new Set(partialPaySelectedIndexes))
      .filter((idx) => idx >= 0 && idx < watchAllItems.length)
      .map((idx) => ({ idx, qty: getPartialQtyForIndex(idx) }))
      .filter((entry) => entry.qty > 0 && String(watchAllItems[entry.idx]?.materialId || '').trim().length > 0);

    if (selectedEntries.length === 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: 'لم يتم اختيار أصناف صالحة للدفع الجزئي.',
        variant: 'destructive',
      });
      return;
    }

    const currentValues = form.getValues();
    const normalizedCustomerId = String(currentValues.customerId || '').trim();
    const partialItems = selectedEntries.map(({ idx, qty }) => {
      const currentLine = currentValues.items?.[idx] as any;
      const material = allMaterials.find((entry) => entry.id === currentLine?.materialId);
      const originalQty = Math.max(0.001, Number(currentLine?.quantity || 1));
      const ratio = qty / originalQty;
      const proratedDiscount = Number(currentLine?.discount || 0) * ratio;

      return {
        ...currentLine,
        quantity: qty,
        description: String(currentLine?.description || '').trim(),
        discount: proratedDiscount,
        warehouseId: String(currentLine?.warehouseId || (allowOutOfStockSales ? defaultWarehouseId : '') || '').trim(),
        shelfId: String(currentLine?.shelfId || (allowOutOfStockSales ? defaultShelfId : '') || '').trim(),
        printSectionId: String((material as any)?.printSectionId || '').trim(),
        printLabel: String((material as any)?.printLabelOverride || '').trim(),
        excludeFromPrepTicket: (material as any)?.excludeFromPrepTicket === true,
      };
    });

    const partialAmount = Math.max(0, partialPayTotal);
    if (partialAmount <= 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: 'المبلغ الجزئي غير صالح.',
        variant: 'destructive',
      });
      return;
    }

    const payload = {
      ...currentValues,
      customerId: normalizedCustomerId,
      amountPaid: partialAmount,
      payments: [{ method: 'cash' as const, amount: partialAmount, customerName: undefined }],
      discountAmount: 0,
      items: partialItems,
      restaurantTableId: activeRestaurantTableId || undefined,
      restaurantAreaId: activeRestaurantAreaId || undefined,
      restaurantGuestCount: Math.max(1, Number(restaurantConfig?.defaultGuestCount || 2)),
      restaurantChannel: restaurantPosEnabled ? ('dine_in' as const) : undefined,
    };

    startInvoiceTransition(async () => {
      setIsPartialPaymentPending(true);
      try {
        const result = await handleCreateSaleInvoice(payload as any);
        if (result.success) {
          const soldUnitIds = new Set(
            (payload.items || [])
              .map((line) => String((line as any)?.itemUnitId || '').trim())
              .filter(Boolean)
          );

          if (soldUnitIds.size > 0) {
            const nextStatus: ItemUnit['status'] = isReturn ? 'available' : 'sold';
            setAllItemUnits((prev) => prev.map((unit) => (soldUnitIds.has(unit.id) ? { ...unit, status: nextStatus } : unit)));
          }

          const entryQtyMap = new Map(selectedEntries.map((entry) => [entry.idx, entry.qty]));
          const nextItems = (form.getValues('items') || [])
            .map((line: any, idx: number) => {
              const paidQty = Number(entryQtyMap.get(idx) || 0);
              if (paidQty <= 0) return line;

              const originalQty = Math.max(0.001, Number(line?.quantity || 0));
              const remainingQty = Number((originalQty - paidQty).toFixed(3));
              if (remainingQty <= 0) return null;

              const ratio = remainingQty / originalQty;
              return {
                ...line,
                quantity: remainingQty,
                discount: Number(line?.discount || 0) * ratio,
              };
            })
            .filter(Boolean) as any[];

          replace(nextItems as any);
          form.setValue('items', nextItems as any, {
            shouldDirty: true,
            shouldTouch: true,
            shouldValidate: true,
          });

          applyPayments([]);
          if (nextItems.length === 0) {
            form.setValue('discountAmount', 0, {
              shouldDirty: true,
              shouldTouch: true,
              shouldValidate: true,
            });
          }

          setShowPartialPayDialog(false);
          setPartialPaySelectedIndexes([]);
          setPartialPayRowIndex(null);
          setPartialPayRowQty('1');

          toast({ title: 'تم تنفيذ الدفع الجزئي بنجاح.', description: '' });
        } else {
          if (result.error === 'POS_SHIFT_REQUIRED') {
            await loadShiftStatus();
          }
          toast({
            title: t?.saveInvoiceError ?? 'فشل حفظ الفاتورة.',
            description: result.error,
            variant: 'destructive',
          });
        }
      } finally {
        setIsPartialPaymentPending(false);
      }
    });
  };

  const promptSelectCustomerForReceivables = () => {
    form.setError('customerId', {
      type: 'manual',
      message: t?.receivablesCustomerRequired ?? 'عند اختيار الذمم يجب تحديد الزبون أولاً.',
    });
    setShowCustomerPickerDialog(true);
  };

  const handleRemoveItem = (index: number) => {
    const currentItems = [...(form.getValues('items') || [])];
    if (index < 0 || index >= currentItems.length) return;

    currentItems.splice(index, 1);
    replace(currentItems as any);
    form.setValue('items', currentItems as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true,
    });

    if (currentItems.length === 0) {
      applyPayments([]);
      form.setValue('discountAmount', 0, {
        shouldDirty: true,
        shouldTouch: true,
        shouldValidate: true,
      });
    }
  };
  const totalQuantity = useMemo(() => (watchAllItems || []).reduce((sum, item) => sum + (Number(item.quantity) || 0), 0), [watchAllItems]);
  const bonusTotalQuantity = useMemo(() => (itemsWithDetails || []).reduce((sum, item) => sum + (item?.bonus ?? 0), 0), [itemsWithDetails]);
  const bonusValueTotal = useMemo(() => (itemsWithDetails || []).reduce((sum, item, index) => {
    const line = watchAllItems[index];
    if (!item || !line) return sum;
    return sum + (item.bonus ? item.bonus * (Number(line.unitPrice) || 0) : 0);
  }, 0), [itemsWithDetails, watchAllItems]);

  const summarySection = (
    <div className="rounded-xl border bg-card p-2.5 shadow-sm">
      <div className="grid grid-cols-2 gap-2 text-xs text-center md:grid-cols-4 xl:grid-cols-2 2xl:grid-cols-4">
        <div className="flex flex-col items-center gap-1">
          <span className="text-muted-foreground">{t?.itemsCountLabel ?? 'عدد الأصناف'}</span>
          <span className="font-mono">{watchAllItems.length}</span>
        </div>
        <div className="flex flex-col items-center gap-1">
          <span className="text-muted-foreground">{t?.totalQuantityLabel ?? 'مجموع الكميات'}</span>
          <span className="font-mono">{totalQuantity}</span>
        </div>
        <div className="flex flex-col items-center gap-1">
          <span className="text-muted-foreground">{t?.bonusQuantityLabel ?? 'مجموع البونص'}</span>
          <span className="font-mono">{bonusTotalQuantity}</span>
        </div>
        <div className="flex flex-col items-center gap-1">
          <span className="text-muted-foreground">{t?.itemsDiscountTotalLabel ?? 'خصم الأصناف'}</span>
          <span className="font-mono">-{formatCurrency(itemDiscountTotal, currencySymbol)}</span>
        </div>
      </div>

      <Separator className="my-2" />

      <div className="grid grid-cols-1 gap-2 md:grid-cols-3 xl:grid-cols-1 2xl:grid-cols-3">
        <div className="rounded-lg border-2 border-blue-200 bg-gradient-to-br from-blue-50 to-blue-100/50 p-3">
          <div className="mb-1 text-xs text-muted-foreground">{t?.subTotal ?? 'المجموع الفرعي'}</div>
          <div className="text-2xl font-bold text-blue-700">{formatCurrency(itemsSubTotal, currencySymbol)}</div>
          {(itemDiscountTotal > 0 || customerDiscount > 0 || safeInvoiceDiscount > 0 || bonusValueTotal > 0 || campaignDiscountTotal > 0) && (
            <div className="mt-2 space-y-1 border-t border-blue-200 pt-2 text-xs">
              {campaignDiscountTotal > 0 && (
                <div className="flex justify-between text-emerald-700">
                  <span>{t?.campaignDiscountPreviewLabel ?? 'خصم الحملات (معاينة)'}</span>
                  <span>-{formatCurrency(campaignDiscountTotal, currencySymbol)}</span>
                </div>
              )}
              {itemDiscountTotal > 0 && (
                <div className="flex justify-between text-green-600">
                  <span>{t?.itemsDiscountTotalLabel ?? 'خصم الأصناف'}</span>
                  <span>-{formatCurrency(itemDiscountTotal, currencySymbol)}</span>
                </div>
              )}
              {customerDiscount > 0 && (
                <div className="flex justify-between text-green-600">
                  <span>{t?.discount ?? 'الخصم'} ({selectedCustomer?.allowedDiscount || 0}%)</span>
                  <span>-{formatCurrency(customerDiscount, currencySymbol)}</span>
                </div>
              )}
              {safeInvoiceDiscount > 0 && (
                <div className="flex justify-between text-green-600">
                  <span>{t?.invoiceDiscountLabel ?? 'خصم الإجمالي'}</span>
                  <span>-{formatCurrency(safeInvoiceDiscount, currencySymbol)}</span>
                </div>
              )}
              {bonusValueTotal > 0 && (
                <div className="flex justify-between text-green-600">
                  <span>{t?.bonusValueLabel ?? 'قيمة البونص'}</span>
                  <span>-{formatCurrency(bonusValueTotal, currencySymbol)}</span>
                </div>
              )}
            </div>
          )}
        </div>

        <div className="rounded-lg border-2 border-amber-200 bg-gradient-to-br from-amber-50 to-amber-100/50 p-3">
          <div className="mb-1 text-xs text-muted-foreground">{t?.grandTotal ?? 'المجموع الإجمالي'}</div>
          <div className="text-2xl font-bold text-amber-700">{formatCurrency(totalAfterDiscount, currencySymbol)}</div>
          <div className="mt-2 border-t border-amber-200 pt-2 text-xs text-amber-600">
            {t?.afterAllDiscounts ?? 'بعد جميع الخصومات'}
          </div>
        </div>

        <div className={`rounded-lg border-2 p-3 ${
          amountDue > 0
            ? 'border-red-200 bg-gradient-to-br from-red-50 to-red-100/50'
            : 'border-green-200 bg-gradient-to-br from-green-50 to-green-100/50'
        }`}>
          <div className="mb-1 text-xs text-muted-foreground">{t?.amountDue ?? 'المبلغ المتبقي'}</div>
          <div className={`text-2xl font-bold ${amountDue > 0 ? 'text-red-700' : 'text-green-700'}`}>
            {formatCurrency(amountDue, currencySymbol)}
          </div>
          <div className={`mt-2 border-t pt-2 text-xs ${
            amountDue > 0 ? 'border-red-200 text-red-600' : 'border-green-200 text-green-600'
          }`}>
            {amountDue > 0 ? (t?.requiresPayment ?? 'يتطلب دفع') : (t?.fullyPaid ?? 'مدفوع بالكامل')}
          </div>
        </div>
      </div>

      <div className="mt-2 flex flex-col gap-2 md:flex-row md:items-stretch">
        <FormField
          control={form.control}
          name="discountAmount"
          render={({ field }) => (
            <FormItem className="flex-1 rounded-lg border-2 border-purple-200 bg-gradient-to-br from-purple-50 to-purple-100/50 p-3 flex flex-col justify-center">
              <FormLabel className="text-xs text-muted-foreground mb-1">{t?.invoiceDiscountLabel ?? 'خصم الإجمالي'}</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  step="0.01"
                  inputMode="decimal"
                  className="border-purple-300 text-center font-mono text-lg font-bold focus-visible:ring-purple-500"
                  {...field}
                  onFocus={(e) => e.target.select()}
                  onBlur={(e) => {
                    const raw = e.target.value;
                    const num = Number(raw);
                    field.onChange(Number.isFinite(num) ? num.toFixed(2) : '0.00');
                  }}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex-[2] flex flex-col justify-center space-y-2 rounded-lg border-2 border-sky-200 bg-gradient-to-br from-sky-50 to-sky-100/50 p-3">
          <FormLabel className="text-xs text-muted-foreground mb-1">{t?.PaymentMethods?.paymentMethods ?? 'طرق الدفع'}</FormLabel>
          <div className="rounded-xl border border-sky-300 bg-white/90 p-2.5 shadow-sm">
            <div className="mb-2 flex items-center justify-between text-xs text-muted-foreground">
              <span>{t?.PaymentMethods?.paymentBreakdown ?? 'تفاصيل الدفع'}</span>
              <span>{formatCurrency(totalPaid, currencySymbol)} / {formatCurrency(totalAfterDiscount, currencySymbol)}</span>
            </div>
            {payments.length > 0 ? (
              <div className="space-y-2">
                {payments.map((payment, idx) => (
                  <div
                    key={idx}
                    className="flex items-center justify-between rounded-xl border border-sky-200 bg-gradient-to-l from-sky-50 to-white p-3 text-sm"
                  >
                    <div className="flex items-center gap-2">
                      <span className="flex h-8 w-8 items-center justify-center rounded-full bg-white text-base shadow-sm">
                        {payment.method === 'cash' && '💵'}
                        {payment.method === 'visa' && '💳'}
                        {payment.method === 'receivables' && '📋'}
                        {payment.method === 'coupon' && '🎟️'}
                      </span>
                      <span className="font-semibold text-foreground">
                        {payment.method === 'cash' && (t?.PaymentMethods?.cash ?? 'نقدي')}
                        {payment.method === 'visa' && (t?.PaymentMethods?.visa ?? 'فيزا')}
                        {payment.method === 'receivables' && (t?.PaymentMethods?.receivables ?? 'ذمم')}
                        {payment.method === 'coupon' && (t?.PaymentMethods?.coupon ?? 'كوبون')}
                      </span>
                    </div>
                    <span className="rounded-lg bg-white px-2.5 py-1.5 font-mono font-bold text-sky-800 shadow-sm">
                      {formatCurrency(payment.amount, currencySymbol)}
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <div className="rounded-lg border border-dashed border-sky-300 bg-sky-50 px-3 py-2 text-xs text-sky-700">
                {t?.PaymentMethods?.selectOnSave ?? 'سيظهر نموذج اختيار طريقة الدفع عند الضغط على حفظ أو حفظ + طباعة.'}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );

  const handleResizeStart = (type: 'left' | 'summary', event: React.PointerEvent<HTMLDivElement>) => {
    event.preventDefault();
    const startX = event.clientX;
    const startWidth = type === 'left' ? leftPanelWidthRef.current : summaryPanelWidthRef.current;
    const minWidth = type === 'left' ? 260 : 280;
    const maxWidth = type === 'left' ? 640 : 520;

    const handleMove = (moveEvent: PointerEvent) => {
      const delta = moveEvent.clientX - startX;
      const next = Math.min(Math.max(startWidth + delta, minWidth), maxWidth);
      if (type === 'left') {
        setLeftPanelWidth(next);
      } else {
        setSummaryPanelWidth(next);
      }
    };

    const handleUp = () => {
      document.body.style.userSelect = '';
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
      if (type === 'left') {
        localStorage.setItem('posLayoutLeftPanelWidth', String(leftPanelWidthRef.current));
      } else {
        localStorage.setItem('posLayoutSummaryPanelWidth', String(summaryPanelWidthRef.current));
      }
    };

    document.body.style.userSelect = 'none';
    window.addEventListener('pointermove', handleMove);
    window.addEventListener('pointerup', handleUp);
  };

  const onSubmit = (values: z.infer<typeof posSchema>) => {
    if (!isShiftOpen) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.shiftRequiredBeforeSale ?? 'يجب افتتاح الوردية قبل حفظ أي فاتورة.',
        variant: 'destructive',
      });
      return;
    }

    const normalizedCustomerId = (values.customerId || '').trim();
    const activePayments: PosPaymentBreakdown =
      Array.isArray(values.payments) && values.payments.length > 0
        ? values.payments.map((payment) => ({
          ...payment,
          amount: Number(payment.amount || 0),
        }))
        : payments;
    const computedAmountPaid = activePayments.length > 0
      ? activePayments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0)
      : Number(values.amountPaid || 0);
    const computedAmountDue = totalAfterDiscount - computedAmountPaid;
    const hasReceivablesPayment = activePayments.some(
      (payment) => payment.method === 'receivables' && Number(payment.amount || 0) > 0
    );

    if (hasReceivablesPayment && normalizedCustomerId.length === 0) {
      promptSelectCustomerForReceivables();
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.receivablesCustomerRequired ?? 'عند اختيار الذمم يجب تحديد الزبون أولاً.',
        variant: 'destructive',
      });
      return;
    }

    const isCashCustomer = normalizedCustomerId.length === 0;
    if (isCashCustomer && Math.abs(computedAmountDue) > 0.0001) {
      form.setError('customerId', {
        type: 'manual',
        message: t?.cashCustomerRequiresPaid ?? 'الزبون النقدي يجب أن يكون المتبقي 0.00',
      });
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.cashCustomerRequiresPaid ?? 'الزبون النقدي يجب أن يكون المتبقي 0.00',
        variant: 'destructive',
      });
      return;
    }

    const normalizedItems = (values.items || []).map((item) => {
      const material = allMaterials.find((entry) => entry.id === item.materialId);
      return {
        ...item,
        description: (item.description || '').trim(),
        discount: Number(item.discount || 0),
        warehouseId: String((item as any)?.warehouseId || (allowOutOfStockSales ? defaultWarehouseId : '') || '').trim(),
        shelfId: String((item as any)?.shelfId || (allowOutOfStockSales ? defaultShelfId : '') || '').trim(),
        printSectionId: String((material as any)?.printSectionId || '').trim(),
        printLabel: String((material as any)?.printLabelOverride || '').trim(),
        excludeFromPrepTicket: (material as any)?.excludeFromPrepTicket === true,
      };
    });

    // Pre-validate tracked items locally so the cashier gets immediate actionable feedback.
    const trackedIssues: string[] = [];
    const selectedTrackedUnitIds = new Set(
      normalizedItems
        .map((line) => String((line as any)?.itemUnitId || '').trim())
        .filter(Boolean)
    );

    for (let index = 0; index < normalizedItems.length; index += 1) {
      const item = normalizedItems[index] as any;
      const material = allMaterials.find((entry) => entry.id === item.materialId);
      if (!material || !isTrackedMaterial(material)) continue;

      const itemName = material.name || item.materialId;
      const existingUnitId = String(item.itemUnitId || '').trim();

      if (!existingUnitId) {
        const availableUnits = (allItemUnits || []).filter((unit) => {
          if (unit.itemId !== item.materialId) return false;
          if (!isReturn && (unit.status === 'sold' || unit.status === 'damaged')) return false;
          if (selectedTrackedUnitIds.has(unit.id)) return false;
          return true;
        });

        if (availableUnits.length === 1) {
          const onlyUnit = availableUnits[0];
          item.itemUnitId = onlyUnit.id;
          item.serialNumber = String(onlyUnit.serialNumber || '').trim();
          item.rfidCode = String(onlyUnit.rfidCode || '').trim();
          selectedTrackedUnitIds.add(onlyUnit.id);
          form.setValue(`items.${index}.itemUnitId`, item.itemUnitId);
          form.setValue(`items.${index}.serialNumber`, item.serialNumber);
          form.setValue(`items.${index}.rfidCode`, item.rfidCode);
          continue;
        }

        trackedIssues.push(`${itemName}: ${t?.trackedUnitRequired ?? 'يجب اختيار وحدة متتبعة (Serial/RFID).'}`);
        openTrackedUnitDialog(material, Number(item.unitPrice || getUnitPriceForMaterial(material)), item.description || material.name || '');
        break;
      }

      const selectedUnit = (allItemUnits || []).find((unit) => unit.id === existingUnitId);
      if (!selectedUnit || selectedUnit.itemId !== item.materialId) {
        trackedIssues.push(`${itemName}: ${t?.trackedUnitInvalid ?? 'الوحدة المتتبعة غير صحيحة لهذا الصنف.'}`);
        openTrackedUnitDialog(material, Number(item.unitPrice || getUnitPriceForMaterial(material)), item.description || material.name || '');
        break;
      }

      if (!isReturn && (selectedUnit.status === 'sold' || selectedUnit.status === 'damaged')) {
        trackedIssues.push(`${itemName}: ${t?.trackedUnitUnavailable ?? 'الوحدة المتتبعة غير متاحة.'}`);
        openTrackedUnitDialog(material, Number(item.unitPrice || getUnitPriceForMaterial(material)), item.description || material.name || '');
        break;
      }
    }

    if (trackedIssues.length > 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: trackedIssues[0],
        variant: 'destructive',
      });
      return;
    }

    if (isWarehouseEnabled && !isReturn && !allowOutOfStockSales) {
      const sourceUsage = new Map<string, number>();
      const sourceErrors: string[] = [];

      normalizedItems.forEach((item, index) => {
        const material = allMaterials.find((entry) => entry.id === item.materialId);
        const materialName = material?.name || item.materialId;
        const availableLocations = availableLocationsByMaterial.get(item.materialId) || [];

        if (availableLocations.length === 0) {
          sourceErrors.push(`${materialName}: ${t?.noStockForItem ?? 'لا يوجد رصيد متاح لهذا الصنف على أي رف.'}`);
          return;
        }

        if ((!item.warehouseId || !item.shelfId) && availableLocations.length === 1) {
          item.warehouseId = availableLocations[0].warehouseId;
          item.shelfId = availableLocations[0].shelfId;
          form.setValue(`items.${index}.warehouseId`, item.warehouseId);
          form.setValue(`items.${index}.shelfId`, item.shelfId);
        }

        if (!item.warehouseId || !item.shelfId) {
          sourceErrors.push(`${materialName}: ${t?.selectShelfBeforeSave ?? 'يرجى اختيار الرف قبل الحفظ.'}`);
          return;
        }

        const selectedLocation = availableLocations.find(
          (location) => location.warehouseId === item.warehouseId && location.shelfId === item.shelfId
        );

        if (!selectedLocation) {
          sourceErrors.push(`${materialName}: ${t?.invalidShelfSelection ?? 'الرف المختار غير متاح للصنف.'}`);
          return;
        }

        const usageKey = `${item.materialId}||${item.warehouseId}||${item.shelfId}`;
        const nextUsage = (sourceUsage.get(usageKey) || 0) + Number(item.quantity || 0);
        sourceUsage.set(usageKey, nextUsage);

        if (nextUsage > Number(selectedLocation.quantity || 0)) {
          sourceErrors.push(
            `${materialName}: ${t?.insufficientShelfStock ?? 'الكمية المطلوبة أكبر من المتوفر في الرف المختار.'} (${selectedLocation.warehouseName} / ${selectedLocation.shelfName})`
          );
        }
      });

      if (sourceErrors.length > 0) {
        toast({
          title: t?.validationError ?? 'خطأ في التحقق',
          description: sourceErrors[0],
          variant: 'destructive',
        });
        return;
      }
    }

    const payload = {
      ...values,
      customerId: normalizedCustomerId,
      amountPaid: computedAmountPaid,
      payments: activePayments,
      discountAmount: Number(values.discountAmount || 0),
      items: normalizedItems,
      restaurantTableId: activeRestaurantTableId || '',
      restaurantAreaId: activeRestaurantAreaId || '',
      restaurantGuestCount: Math.max(1, Number(restaurantConfig?.defaultGuestCount || 2)),
      restaurantChannel: restaurantPosEnabled ? ('dine_in' as const) : ('takeaway' as const),
    };

    startInvoiceTransition(async () => {
      setIsSaveInvoicePending(true);
      try {
        const result = await handleCreateSaleInvoice(payload);
        if (result.success) {
          const soldUnitIds = new Set(
            (payload.items || [])
              .map((line) => String((line as any)?.itemUnitId || '').trim())
              .filter(Boolean)
          );
          if (soldUnitIds.size > 0) {
            const nextStatus: ItemUnit['status'] = isReturn ? 'available' : 'sold';
            setAllItemUnits((prev) => prev.map((unit) => (soldUnitIds.has(unit.id) ? { ...unit, status: nextStatus } : unit)));
          }
          const savedInvoiceId = String((result as any)?.invoiceId || '').trim();
          const savedInvoiceNumber = String((result as any)?.invoiceNumber || '').trim();
          if (printingSettings?.printerAutoPrintEnabled === true || shouldPrintAfterSaveRef.current) {
            handlePrint(true, { id: savedInvoiceId, number: savedInvoiceNumber });
          }
          toast({ title: t?.saveInvoiceSuccess ?? 'تم حفظ الفاتورة بنجاح.', description: '' });
          form.reset({ customerId: payload.customerId, amountPaid: 0, payments: [], discountAmount: 0, items: [], isReturn });
          setPayments([]);
          setSuspendedInvoices((prev) => {
            if (!activeRestaurantTableId) return prev;
            return prev.filter((entry) => String(entry.tableId || '') !== activeRestaurantTableId);
          });
          localStorage.removeItem(posDraftInvoiceStorageKey);
        } else {
          if (result.error === 'POS_SHIFT_REQUIRED') {
            await loadShiftStatus();
          }
          toast({ title: t?.saveInvoiceError ?? 'فشل حفظ الفاتورة.', description: result.error, variant: 'destructive' });
        }
      } finally {
        shouldPrintAfterSaveRef.current = false;
        setIsSaveInvoicePending(false);
      }
    });
  };

  const handleSuspend = () => {
    const currentItems = form.getValues('items');
    if (!currentItems || currentItems.length === 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.',
        variant: 'destructive',
      });
      return;
    }

    const normalizedItems = currentItems
      .map((item) => ({
        materialId: String(item.materialId || ''),
        quantity: Number(item.quantity || 0),
        unitPrice: Number(item.unitPrice || 0),
        description: (item.description || '').trim(),
        discount: Number(item.discount || 0),
        itemUnitId: String((item as any).itemUnitId || '').trim(),
        serialNumber: String((item as any).serialNumber || '').trim(),
        rfidCode: String((item as any).rfidCode || '').trim(),
        warehouseId: String((item as any).warehouseId || '').trim(),
        shelfId: String((item as any).shelfId || '').trim(),
      }))
      .filter((item) => item.materialId);

    if (normalizedItems.length === 0) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.',
        variant: 'destructive',
      });
      return;
    }

    const id = `susp-${Date.now()}`;
    const tableAreaName = activeRestaurantTable
      ? (restaurantAreas.find((area) => area.id === activeRestaurantTable.areaId)?.name || 'بدون منطقة')
      : '';
    setSuspendedInvoices((prev) => [
      {
        id,
        customerId: form.getValues('customerId'),
        amountPaid: form.getValues('amountPaid') || 0,
        payments: form.getValues('payments') || [],
        discountAmount: form.getValues('discountAmount') || 0,
        items: normalizedItems,
        createdAt: new Date().toISOString(),
        tableId: activeRestaurantTable?.id,
        tableName: activeRestaurantTable?.name,
        areaName: tableAreaName,
      },
      ...prev,
    ]);
    form.reset({ customerId: '', amountPaid: 0, payments: [], discountAmount: 0, items: [], isReturn });
    setPayments([]);
    localStorage.removeItem(posDraftInvoiceStorageKey);
    toast({ title: t?.invoiceSuspended ?? 'تم تعليق الفاتورة' });
    requestAnimationFrame(() => barcodeRef.current?.focus());
  };

  const handleResume = (suspId: string) => {
    const target = suspendedInvoices.find((inv) => inv.id === suspId);
    if (!target) return;
    form.reset({
      customerId: target.customerId,
      amountPaid: target.amountPaid,
      payments: (target as any).payments || [],
      discountAmount: target.discountAmount || 0,
      items: target.items,
      isReturn,
    });
    setPayments((target as any).payments || []);
    setActiveRestaurantTableId(String((target as any).tableId || '').trim());
    setSuspendedInvoices((prev) => prev.filter((inv) => inv.id !== suspId));
    setShowSuspended(false);
    localStorage.setItem(posDraftInvoiceStorageKey, JSON.stringify({
      customerId: target.customerId,
      amountPaid: target.amountPaid,
      payments: (target as any).payments || [],
      discountAmount: target.discountAmount || 0,
      items: target.items,
      isReturn,
      savedAt: new Date().toISOString(),
    }));
    requestAnimationFrame(() => barcodeRef.current?.focus());
  };

  const handleSelectRestaurantTable = (tableId: string) => {
    if (!restaurantPosEnabled) return;
    if (hasPendingInvoiceLines && activeRestaurantTableId !== tableId) {
      setPendingTableIdOnSwitch(tableId);
      setShowTableSwitchConfirmDialog(true);
      return;
    }

    setActiveRestaurantTableId(tableId);

    const suspendedForTable = suspendedInvoices.find((entry) => String(entry.tableId || '') === tableId);
    if (suspendedForTable) {
      handleResume(suspendedForTable.id);
      toast({
        title: 'تم تحميل طلب الطاولة',
        description: `تم استرجاع الطلب المعلق للطاولة ${suspendedForTable.tableName || ''}.`,
      });
    } else {
      // إذا لم توجد فاتورة معلقة للطاولة الجديدة، قم بتنظيف العميل والنموذج
      form.setValue('customerId', '');
    }
  };

  const handleConfirmTableSwitchWithSuspend = () => {
    if (pendingTableIdOnSwitch) {
      handleSuspend();
      setShowTableSwitchConfirmDialog(false);
      setTimeout(() => {
        setActiveRestaurantTableId(pendingTableIdOnSwitch);
        const suspendedForTable = suspendedInvoices.find((entry) => String(entry.tableId || '') === pendingTableIdOnSwitch);
        if (suspendedForTable) {
          handleResume(suspendedForTable.id);
          toast({
            title: 'تم تحميل طلب الطاولة',
            description: `تم استرجاع الطلب المعلق للطاولة ${suspendedForTable.tableName || ''}.`,
          });
        } else {
          // إذا لم توجد فاتورة معلقة للطاولة الجديدة، قم بتنظيف العميل
          form.setValue('customerId', '');
        }
        setPendingTableIdOnSwitch(null);
      }, 100);
    }
  };

  const handlePrint = (autoTriggered = false, invoiceMeta?: { id?: string; number?: string }) => {
    if (!itemsWithDetails.length) {
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.',
        variant: 'destructive',
      });
      return false;
    }

    const printableItems = itemsWithDetails.map((item, idx) => {
      const line = watchAllItems[idx];
      if (!item || !line) return '';
      return `<tr>
        <td>${escapePrintHtml(item.name)}</td>
        <td>${escapePrintHtml(item.itemNumber)}</td>
        <td>${escapePrintHtml(item.description || item.name)}</td>
        <td>${escapePrintHtml(item.unitLabel)}</td>
        <td>${escapePrintHtml(line.quantity)}</td>
        <td>${escapePrintHtml(line.unitPrice)}</td>
        <td>${escapePrintHtml(formatCurrency(item.total ?? 0, currencySymbol))}</td>
      </tr>`;
    }).join('');

    const modeLabel = isReturn ? (t?.returnMode ?? 'مردود مبيعات') : (t?.saleMode ?? 'مبيعات');
    const receiptTarget = defaultReceiptPrinterName ? ` - ${escapePrintHtml(defaultReceiptPrinterName)}` : '';
    const invoiceReferenceRaw = String(invoiceMeta?.number || invoiceMeta?.id || '').trim();
    const invoiceReference = invoiceReferenceRaw ? escapePrintHtml(invoiceReferenceRaw) : escapePrintHtml('DRAFT');
    const qrValue = invoiceReferenceRaw || 'DRAFT';
    const qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(qrValue)}`;
    const receiptHtml = `
      <html dir="rtl">
        <head>
          <title>${escapePrintHtml(t?.posTitle ?? 'نقطة البيع')}</title>
          <style>
            body{font-family:Arial, sans-serif; padding:20px;}
            h2{margin:0 0 10px 0;}
            table{width:100%; border-collapse:collapse;}
            th,td{border:1px solid #ddd; padding:6px; font-size:12px;}
            th{text-align:right; background:#f3f4f6;}
            .totals{margin-top:12px; font-weight:bold;}
            .meta{margin-bottom:10px; color:#4b5563; font-size:12px;}
            .qr-footer{margin-top:14px; display:flex; flex-direction:column; align-items:center; gap:6px; color:#374151; font-size:12px;}
            .qr-footer img{width:120px; height:120px; border:1px dashed #d1d5db; padding:4px; background:#fff;}
          </style>
        </head>
        <body>
          <h2>${escapePrintHtml(t?.posTitle ?? 'نقطة البيع')} - ${escapePrintHtml(modeLabel)}${receiptTarget}</h2>
          <div class="meta">${escapePrintHtml(t?.invoiceNumber ?? 'رقم الفاتورة')}: ${invoiceReference}</div>
          <div class="meta">${escapePrintHtml(t?.cashier ?? 'الكاشير')}: ${escapePrintHtml(cashierName ?? '')}</div>
          <table>
            <thead>
              <tr>
                <th>${escapePrintHtml(t?.item ?? 'الصنف')}</th>
                <th>${escapePrintHtml(t?.itemNumberLabel ?? 'رقم الصنف')}</th>
                <th>${escapePrintHtml(t?.descriptionLabel ?? 'الوصف')}</th>
                <th>${escapePrintHtml(t?.unitLabel ?? 'الوحدة')}</th>
                <th>${escapePrintHtml(t?.quantity ?? 'الكمية')}</th>
                <th>${escapePrintHtml(t?.price ?? 'السعر')}</th>
                <th>${escapePrintHtml(t?.total ?? 'الإجمالي')}</th>
              </tr>
            </thead>
            <tbody>${printableItems}</tbody>
          </table>
          <div class="totals">${escapePrintHtml(t?.grandTotal ?? 'المجموع الإجمالي')}: ${escapePrintHtml(formatCurrency(totalAfterDiscount, currencySymbol))}</div>
          <div class="qr-footer">
            <img src="${qrSrc}" alt="Invoice QR" />
            <div>${escapePrintHtml(t?.invoiceNumber ?? 'رقم الفاتورة')}: ${invoiceReference}</div>
          </div>
        </body>
      </html>
    `;

    if (printingSettings?.printTransportMode === 'native-bridge') {
      toast({
        title: t?.printerBridgeNoticeTitle ?? 'تنبيه الطباعة',
        description: t?.printerBridgeNoticeDescription ?? 'تم حفظ توزيع الطابعات. الإرسال الصامت للطابعات يحتاج ربطاً محلياً، لذا سيتم فتح معاينة المتصفح حالياً.',
        variant: 'destructive',
      });
    }

    let openedDocuments = 0;
    if (openPrintPreviewWindow(receiptHtml)) {
      openedDocuments += 1;
    }

    if (printingSettings?.customPrintersEnabled) {
      const groupedPrepTickets = new Map<string, { sectionName: string; printerName: string; copies: number; printPrices: boolean; rows: string[] }>();

      itemsWithDetails.forEach((item, idx) => {
        const line = watchAllItems[idx];
        if (!item || !line) return;

        const material = allMaterials.find((entry) => entry.id === line.materialId);
        if (!material || material.excludeFromPrepTicket === true) return;

        const sectionId = String((material as any).printSectionId || '').trim();
        if (!sectionId) return;

        const section = printSectionById.get(sectionId);
        if (!section) return;

        const bucket = groupedPrepTickets.get(sectionId) || {
          sectionName: String(section.name || sectionId),
          printerName: printerNameById.get(String(section.printerId || '')) || '',
          copies: Math.max(1, Number(section.copies || 1)),
          printPrices: section.printPrices === true,
          rows: [],
        };

        const prepLabel = String((material as any).printLabelOverride || item.description || item.name || '').trim() || item.name;
        const lineNotes = String((line.description || '')).trim();

        bucket.rows.push(`
          <tr>
            <td>
              <div style="font-weight:600">${escapePrintHtml(prepLabel)}</div>
              ${lineNotes && lineNotes !== item.name ? `<div style="font-size:11px;color:#6b7280">${escapePrintHtml(lineNotes)}</div>` : ''}
            </td>
            <td>${escapePrintHtml(item.unitLabel || '-')}</td>
            <td>${escapePrintHtml(line.quantity)}</td>
            ${bucket.printPrices ? `<td>${escapePrintHtml(formatCurrency(item.total ?? 0, currencySymbol))}</td>` : ''}
          </tr>
        `);

        groupedPrepTickets.set(sectionId, bucket);
      });

      groupedPrepTickets.forEach((group) => {
        const prepHtml = `
          <html dir="rtl">
            <head>
              <title>${escapePrintHtml(group.sectionName)}</title>
              <style>
                body{font-family:Arial, sans-serif; padding:16px;}
                h2{margin:0 0 6px 0;}
                table{width:100%; border-collapse:collapse; margin-top:10px;}
                th,td{border:1px solid #ddd; padding:6px; font-size:12px; vertical-align:top;}
                th{text-align:right; background:#f3f4f6;}
                .meta{font-size:12px; color:#4b5563; margin-bottom:8px;}
              </style>
            </head>
            <body>
              <h2>${escapePrintHtml(group.sectionName)}</h2>
              <div class="meta">${escapePrintHtml(t?.cashier ?? 'الكاشير')}: ${escapePrintHtml(cashierName ?? '')}</div>
              <div class="meta">${escapePrintHtml(t?.copiesLabel ?? 'عدد النسخ')}: ${escapePrintHtml(group.copies)}${group.printerName ? ` — ${escapePrintHtml(group.printerName)}` : ''}</div>
              <table>
                <thead>
                  <tr>
                    <th>${escapePrintHtml(t?.item ?? 'الصنف')}</th>
                    <th>${escapePrintHtml(t?.unitLabel ?? 'الوحدة')}</th>
                    <th>${escapePrintHtml(t?.quantity ?? 'الكمية')}</th>
                    ${group.printPrices ? `<th>${escapePrintHtml(t?.total ?? 'الإجمالي')}</th>` : ''}
                  </tr>
                </thead>
                <tbody>${group.rows.join('')}</tbody>
              </table>
            </body>
          </html>
        `;

        if (openPrintPreviewWindow(prepHtml)) {
          openedDocuments += 1;
        }
      });
    }

    if (autoTriggered && openedDocuments === 0) {
      toast({
        title: t?.printerPopupBlockedTitle ?? 'تعذر فتح الطباعة',
        description: t?.printerPopupBlockedDescription ?? 'قد يكون المتصفح قد حظر نوافذ الطباعة. استخدم زر الطباعة يدوياً إذا لزم الأمر.',
        variant: 'destructive',
      });
    }

    return openedDocuments > 0;
  };

  const handlePrintSavedInvoice = (invoice: SalesInvoice) => {
    const printableItems = (invoice.items || []).map((item) => `
      <tr>
        <td>${escapePrintHtml(item.name)}</td>
        <td>${escapePrintHtml(item.description || item.name)}</td>
        <td>${escapePrintHtml(item.quantity)}</td>
        <td>${escapePrintHtml(item.unitPrice)}</td>
        <td>${escapePrintHtml(formatCurrency(item.total || (Number(item.quantity || 0) * Number(item.unitPrice || 0)), currencySymbol))}</td>
      </tr>
    `).join('');

    const customer = customers.find((c) => c.id === invoice.customerId);
    const total = typeof invoice.grandTotal === 'number'
      ? invoice.grandTotal
      : (invoice.items || []).reduce((sum, item) => sum + Number(item.total || (item.quantity * item.unitPrice)), 0);
    const invoiceReferenceRaw = String(invoice.invoiceNumber || invoice.id || '').trim();
    const invoiceReference = escapePrintHtml(invoiceReferenceRaw);
    const qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(invoiceReferenceRaw)}`;

    const html = `
      <html dir="rtl">
        <head>
          <title>${escapePrintHtml(invoice.invoiceNumber || invoice.id)}</title>
          <style>
            body{font-family:Arial, sans-serif; padding:20px;}
            h2{margin:0 0 10px 0;}
            table{width:100%; border-collapse:collapse;}
            th,td{border:1px solid #ddd; padding:6px; font-size:12px;}
            th{text-align:right; background:#f3f4f6;}
            .meta{margin-bottom:10px; color:#4b5563; font-size:12px;}
            .totals{margin-top:12px; font-weight:bold;}
            .qr-footer{margin-top:14px; display:flex; flex-direction:column; align-items:center; gap:6px; color:#374151; font-size:12px;}
            .qr-footer img{width:120px; height:120px; border:1px dashed #d1d5db; padding:4px; background:#fff;}
          </style>
        </head>
        <body>
          <h2>${escapePrintHtml(t?.posTitle ?? 'نقطة البيع')}</h2>
          <div class="meta">${escapePrintHtml(t?.invoiceNumber ?? 'رقم الفاتورة')}: ${invoiceReference}</div>
          <div class="meta">${escapePrintHtml(t?.customer ?? 'الزبون')}: ${escapePrintHtml(getDisplayCustomerName((invoice as any)?.customerName, customer?.name))}</div>
          <div class="meta">${escapePrintHtml(t?.date ?? 'التاريخ')}: ${escapePrintHtml(formatDateTimeStable(invoice.date))}</div>
          <table>
            <thead>
              <tr>
                <th>${escapePrintHtml(t?.item ?? 'الصنف')}</th>
                <th>${escapePrintHtml(t?.descriptionLabel ?? 'الوصف')}</th>
                <th>${escapePrintHtml(t?.quantity ?? 'الكمية')}</th>
                <th>${escapePrintHtml(t?.price ?? 'السعر')}</th>
                <th>${escapePrintHtml(t?.total ?? 'الإجمالي')}</th>
              </tr>
            </thead>
            <tbody>${printableItems}</tbody>
          </table>
          <div class="totals">${escapePrintHtml(t?.grandTotal ?? 'المجموع الإجمالي')}: ${escapePrintHtml(formatCurrency(total, currencySymbol))}</div>
          <div class="qr-footer">
            <img src="${qrSrc}" alt="Invoice QR" />
            <div>${escapePrintHtml(t?.invoiceNumber ?? 'رقم الفاتورة')}: ${invoiceReference}</div>
          </div>
        </body>
      </html>
    `;

    const opened = openPrintPreviewWindow(html);
    if (!opened) {
      toast({
        title: t?.printerPopupBlockedTitle ?? 'تعذر فتح الطباعة',
        description: t?.printerPopupBlockedDescription ?? 'قد يكون المتصفح قد حظر نوافذ الطباعة. حاول السماح بالنوافذ المنبثقة.',
        variant: 'destructive',
      });
    }
  };

  const normalizeSearchText = (value: string) => {
    return value
      .toLowerCase()
      .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
      .replace(/[إأآٱ]/g, 'ا')
      .replace(/ى/g, 'ي')
      .replace(/ؤ/g, 'و')
      .replace(/ئ/g, 'ي')
      .replace(/ة/g, 'ه')
      .replace(/[^\p{L}\p{N}]+/gu, '');
  };

  const matchesItemSearch = (material: ProductionItem, query: string) => {
    const trimmed = query.trim();
    if (!trimmed) return true;

    const tokens = trimmed
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);
    const normalizedName = normalizeSearchText(material.name || '');
    const normalizedNumber = normalizeSearchText(String(material.itemNumber || material.id || ''));
    const normalizedBarcode = normalizeSearchText(material.barcode || '');
    const normalizedExtra = (material.additionalBarcodes || [])
      .map((code) => normalizeSearchText(code || ''))
      .join(' ');
    const normalizedAdditionalDetails = normalizeSearchText(material.additionalDetails || '');

    if (tokens.length === 0) return true;
    return tokens.every((token) =>
      normalizedName.includes(token) ||
      normalizedNumber.includes(token) ||
      normalizedBarcode.includes(token) ||
      normalizedExtra.includes(token) ||
      normalizedAdditionalDetails.includes(token)
    );
  };

  const hasAllCharactersUnordered = (haystack: string, token: string) => {
    if (!token) return true;
    if (!haystack) return false;

    const counts = new Map<string, number>();
    for (const ch of haystack) {
      counts.set(ch, (counts.get(ch) || 0) + 1);
    }

    for (const ch of token) {
      const available = counts.get(ch) || 0;
      if (available <= 0) return false;
      counts.set(ch, available - 1);
    }

    return true;
  };

  const customerSearchScore = (customer: Customer, query: string) => {
    const trimmed = String(query || '').trim();
    if (!trimmed) return 0;

    const tokens = trimmed
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);
    if (tokens.length === 0) return 0;

    const name = normalizeSearchText(customer.name || '');
    const idValue = normalizeSearchText(String(customer.id || ''));
    const phoneValue = normalizeSearchText(String((customer as any).phone || (customer as any).mobile || ''));
    const combined = `${name} ${idValue} ${phoneValue}`.trim();
    const compactCombined = combined.replace(/\s+/g, '');

    let score = 0;
    for (const token of tokens) {
      if (!token) continue;

      if (name === token || idValue === token || phoneValue === token) {
        score += 0;
        continue;
      }

      if (name.startsWith(token) || idValue.startsWith(token) || phoneValue.startsWith(token)) {
        score += 1;
        continue;
      }

      if (combined.includes(token) || compactCombined.includes(token)) {
        score += 3;
        continue;
      }

      if (hasAllCharactersUnordered(compactCombined, token)) {
        score += 8;
        continue;
      }

      return Number.POSITIVE_INFINITY;
    }

    return score;
  };

  const filteredCustomers = useMemo(() => {
    return customerList
      .map((customer) => ({ customer, score: customerSearchScore(customer, customerSearchQuery) }))
      .filter((entry) => Number.isFinite(entry.score))
      .sort((a, b) => {
        if (a.score !== b.score) return a.score - b.score;
        return String(a.customer.name || '').localeCompare(String(b.customer.name || ''), locale || 'ar');
      })
      .map((entry) => entry.customer);
  }, [customerList, customerSearchQuery, locale]);

  const filteredMaterials = useMemo(() => {
    if (!showItemPicker) return [];
    return allMaterials.filter((m) => matchesItemSearch(m, itemSearch));
  }, [allMaterials, itemSearch, showItemPicker]);

  const visibleItemPickerMaterials = useMemo(() => {
    if (!showItemPicker) return [];
    if (itemSearch.trim()) return filteredMaterials;
    return filteredMaterials.slice(0, 200);
  }, [filteredMaterials, itemSearch, showItemPicker]);

  const filteredGroupMaterials = useMemo(() => {
    const query = groupItemSearch.trim();
    if (!query) return activeGroupMaterials;
    return activeGroupMaterials.filter((material) => matchesItemSearch(material, query));
  }, [activeGroupMaterials, groupItemSearch]);

  const touchKeyboardLayouts: Record<'ar' | 'en', string[][]> = {
    ar: [
      ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
      ['ض', 'ص', 'ث', 'ق', 'ف', 'غ', 'ع', 'ه', 'خ', 'ح', 'ج', 'د'],
      ['ش', 'س', 'ي', 'ب', 'ل', 'ا', 'ت', 'ن', 'م', 'ك', 'ط'],
      ['ئ', 'ء', 'ؤ', 'ر', 'لا', 'ى', 'ة', 'و', 'ز', 'ظ'],
    ],
    en: [
      ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
      ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
      ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'],
      ['z', 'x', 'c', 'v', 'b', 'n', 'm'],
    ],
  };

  const supportedKeyboardLanguages: Array<{ code: 'ar' | 'en'; label: string }> = [
    { code: 'ar', label: 'العربية' },
    { code: 'en', label: 'English' },
  ];

  const touchKeyboardRows = touchKeyboardLayouts[groupKeyboardLanguage];

  const appendTouchKey = (key: string) => {
    setGroupItemSearch((prev) => `${prev}${key}`);
  };

  return (
    <div className={`flex min-h-[calc(100vh-4rem)] w-full flex-col ${isReturn ? 'bg-red-50' : ''}`}>
      <Card className="flex flex-1 min-h-0 min-w-0 flex-col overflow-hidden rounded-none border-0 shadow-none">
        <CardHeader className="space-y-3 border-b bg-card/80 pb-4 xl:hidden">
          <div className="flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between">
            <div>
              <CardTitle className="text-2xl font-semibold">{t?.posTitle ?? 'نقطة البيع'}</CardTitle>
              <p className="mt-1 text-sm text-muted-foreground">
                {t?.invoicePageDescription ?? 'إنشاء فاتورة جديدة لزبون. سيتم تطبيق الأسعار والبونص الخاص بالزبون تلقائياً.'}
              </p>
            </div>
            <div className="flex flex-wrap items-center gap-2 text-xs">
              <span className="rounded-full bg-primary/10 px-3 py-1 font-medium text-primary">
                {(t?.cashier ?? 'الكاشير')}: {cashierName || '—'}
              </span>
              <span className={`rounded-full px-3 py-1 font-medium ${isShiftOpen ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>
                {isShiftLoading
                  ? (t?.shiftLoading ?? 'تحميل حالة الوردية...')
                  : isShiftOpen
                    ? (t?.shiftOpenState ?? 'وردية نشطة')
                    : (t?.shiftClosedState ?? 'الوردية غير مفتوحة')}
              </span>
              <Button
                type="button"
                size="sm"
                variant={isShiftOpen ? 'destructive' : 'default'}
                onClick={() => {
                  if (isShiftOpen) {
                    void handleCloseShiftOpen();
                    return;
                  }
                  requestOpenShiftDialog();
                }}
                disabled={isShiftPending || isShiftLoading}
                className="h-7 rounded-full px-3 text-xs"
              >
                {isShiftOpen ? (t?.closeShift ?? 'إغلاق الوردية') : (t?.openShift ?? 'افتتاح الوردية')}
              </Button>
              <span className="rounded-full bg-muted px-3 py-1">
                {(t?.groupItemsTitle ?? 'مجموعات POS')}: {posGroups.length}
              </span>
              <span className="rounded-full bg-muted px-3 py-1">
                {(t?.weightDialogTitle ?? 'الأصناف الوزنية')}: {measuredItemsCount}
              </span>
              <span className="rounded-full bg-muted px-3 py-1">
                {(t?.trackedUnitTitle ?? 'الأصناف المتتبعة')}: {trackedItemsCount}
              </span>
              {restaurantPosEnabled && (
                <span className="rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-800">
                  Restaurant POS: ON ({restaurantAreasCount} مناطق / {restaurantTablesCount} طاولات)
                </span>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent className="flex-1 min-h-0 overflow-hidden p-2 sm:p-3">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="flex h-full min-h-0 flex-col gap-3">
              <div className="flex min-h-0 flex-1 flex-col gap-2 xl:flex-row-reverse xl:items-stretch">
                <aside className="space-y-2 self-stretch xl:sticky xl:top-0 xl:h-full xl:w-auto xl:min-w-[300px] xl:max-w-[620px] xl:shrink-0">
                  <div className="flex min-h-full w-full flex-col space-y-3 rounded-xl border bg-muted/20 p-3 shadow-sm xl:min-w-[320px] xl:resize-x xl:overflow-auto">
                    {/* ─── شريط المستخدم / الوقت / إغلاق الوردية ─── */}
                    <div className="flex items-center justify-between gap-2 rounded-xl border bg-background px-3 py-2 shadow-sm">
                      <div className="flex items-center gap-2 min-w-0">
                        <span className="text-base">👤</span>
                        <span className="truncate text-sm font-medium">{cashierName || '—'}</span>
                      </div>
                      <div className="shrink-0 flex items-center gap-2 font-mono text-sm tabular-nums text-muted-foreground" dir="ltr">
                        <span>{liveTime}</span>
                        {activeShift && (
                          <span className="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700" title="مدة الوردية منذ الافتتاح">
                            ⏱ {shiftElapsed}
                          </span>
                        )}
                      </div>
                      {activeShift ? (
                        <Button
                          type="button"
                          size="sm"
                          variant="destructive"
                          className="h-8 shrink-0"
                          onClick={handleCloseShiftOpen}
                          disabled={isShiftPending}
                        >
                          {isShiftPending ? <Loader2 className="h-4 w-4 animate-spin" /> : (t?.closeShift ?? 'إغلاق الوردية')}
                        </Button>
                      ) : (
                        <Button
                          type="button"
                          size="sm"
                          className="h-8 shrink-0"
                          onClick={() => {
                            void requestOpenShiftDialog();
                          }}
                          disabled={isShiftPending || isShiftLoading}
                        >
                          {isShiftLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : (t?.openShift ?? 'افتتاح الوردية')}
                        </Button>
                      )}
                    </div>

                    <div className="rounded-xl border border-sky-200/70 bg-sky-50/60 p-2">
                      <div className="flex gap-2">
                        <div className="relative flex-1">
                          <ScanLine className="pointer-events-none absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                          <Input
                            ref={barcodeRef}
                            value={barcodeInput}
                            onChange={(e) => setBarcodeInput(e.target.value)}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter' && barcodeInput.trim()) {
                                e.preventDefault();
                                handleBarcodeScanned(barcodeInput.trim());
                              }
                            }}
                            placeholder={t?.barcodePlaceholder ?? 'امسح الباركود أو أدخله هنا...'}
                            className="h-12 rounded-xl bg-background ps-10 text-base shadow-sm"
                          />
                        </div>
                        {restaurantPosEnabled && (
                          <Button
                            type="button"
                            variant="outline"
                            className="h-12 shrink-0 rounded-xl px-3"
                            title="الطاولات"
                            onClick={() => setShowRestaurantTablesDialog(true)}
                          >
                            <Table2 className="h-5 w-5" />
                          </Button>
                        )}
                        {posGroups.length > 0 && (
                          <Button
                            type="button"
                            variant="outline"
                            className="h-12 shrink-0 rounded-xl px-3"
                            title={t?.showGroups ?? 'المجموعات'}
                            onClick={() => {
                              setShowAllGroups(true);
                              setShowGroupsPicker(true);
                            }}
                          >
                            <LayoutGrid className="h-5 w-5" />
                          </Button>
                        )}
                      </div>
                    </div>

                    <div className="rounded-xl border bg-background p-2">
                      <div className="grid grid-cols-3 gap-2 sm:grid-cols-5">
                        <FormField
                          control={form.control}
                          name="customerId"
                          render={({ field }) => (
                            <FormItem className="col-span-1 min-w-0">
                              <FormControl>
                                <Button
                                  type="button"
                                  variant="outline"
                                  role="combobox"
                                  onClick={() => {
                                    setCustomerSearchQuery('');
                                    setShowCustomerPickerDialog(true);
                                  }}
                                  className={cn(
                                    'h-auto w-full flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground',
                                    !field.value && 'text-muted-foreground'
                                  )}
                                >
                                  <span className="text-xl">👤</span>
                                  <span className="text-xs font-medium">{t?.selectCustomer ?? 'اختر زبوناً'}</span>
                                  <span className="max-w-full truncate text-[10px] text-muted-foreground">
                                    {customerList.find((customer) => customer.id === field.value)?.name ?? (t?.noneLabel ?? 'بدون تحديد')}
                                  </span>
                                </Button>
                              </FormControl>
                              <FormMessage />

                              <Dialog
                                open={showCustomerPickerDialog}
                                onOpenChange={(open) => {
                                  setShowCustomerPickerDialog(open);
                                  if (!open) setCustomerSearchQuery('');
                                }}
                              >
                                <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-2xl">
                                  <DialogHeader>
                                    <DialogTitle>{t?.selectCustomer ?? 'اختر زبوناً'}</DialogTitle>
                                    <DialogDescription>{t?.searchCustomerPlaceholder ?? t?.searchPlaceholder ?? 'ابحث عن الزبون...'}</DialogDescription>
                                  </DialogHeader>

                                  <div className="space-y-3">
                                    <Input
                                      value={customerSearchQuery}
                                      onChange={(event) => setCustomerSearchQuery(event.target.value)}
                                      placeholder={t?.searchCustomerPlaceholder ?? t?.searchPlaceholder ?? 'ابحث عن الزبون...'}
                                      autoFocus
                                    />

                                    <div className="max-h-80 overflow-y-auto rounded-md border">
                                      {filteredCustomers.length > 0 ? (
                                        filteredCustomers.map((customer, customerIndex) => (
                                          <button
                                            key={`${String(customer.id)}-${customerIndex}`}
                                            onClick={() => {
                                              field.onChange(customer.id);
                                              form.clearErrors('customerId');
                                              setShowCustomerPickerDialog(false);
                                              setCustomerSearchQuery('');
                                            }}
                                            className={cn(
                                              'flex w-full items-center gap-2 px-3 py-2 text-start text-sm hover:bg-accent',
                                              customer.id === field.value && 'bg-accent'
                                            )}
                                          >
                                            <Check className={cn('h-4 w-4', customer.id === field.value ? 'opacity-100' : 'opacity-0')} />
                                            <span className="truncate">{customer.name}</span>
                                          </button>
                                        ))
                                      ) : (
                                        <div className="px-3 py-4 text-center text-sm text-muted-foreground">
                                          {t?.noResults ?? 'لا توجد نتائج'}
                                        </div>
                                      )}
                                    </div>
                                  </div>

                                  <DialogFooter className="gap-2">
                                    <Button
                                      type="button"
                                      variant="outline"
                                      onClick={() => {
                                        setShowCustomerPickerDialog(false);
                                        setShowAddCustomerDialog(true);
                                      }}
                                    >
                                      <Plus className="me-2 h-4 w-4" />
                                      {t?.addCustomerButton ?? 'إضافة زبون جديد'}
                                    </Button>
                                    <Button
                                      type="button"
                                      variant="ghost"
                                      onClick={() => setShowCustomerPickerDialog(false)}
                                    >
                                      {t?.cancel ?? 'إلغاء'}
                                    </Button>
                                  </DialogFooter>
                                </DialogContent>
                              </Dialog>
                            </FormItem>
                          )}
                        />

                        {showWeighedItemsButton && (
                          <Button
                            type="button"
                            variant="outline"
                            className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                            onClick={() => { setWeighedSearch(''); setWeighedGroupFilter('__all__'); setShowWeighedItemsDialog(true); }}
                          >
                            <span className="text-xl">⚖️</span>
                            <span className="text-xs font-medium">أصناف الميزان</span>
                          </Button>
                        )}

                        <Button
                          type="button"
                          variant="outline"
                          className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                          onClick={() => setShowItemPicker(true)}
                        >
                          <span className="text-xl">📦</span>
                          <span className="text-xs font-medium">{t?.addItem ?? 'إضافة صنف'}</span>
                        </Button>

                        <Button
                          type="button"
                          variant="outline"
                          className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                          onClick={() => setShowInvoices(true)}
                        >
                          <span className="text-xl">🧾</span>
                          <span className="text-xs font-medium">{t?.posInvoices ?? 'عرض الفواتير'}</span>
                        </Button>

                        <Button
                          type="button"
                          variant="outline"
                          className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                          onClick={() => {
                            setAccountingView('statement');
                            setShowAccounting(true);
                          }}
                        >
                          <span className="text-xl">🧮</span>
                          <span className="text-xs font-medium">{t?.accountingButton ?? 'محاسبة'}</span>
                        </Button>

                      </div>
                    </div>

                    {lastAutosaveAt && (
                      <div className="flex justify-end">
                        <span className="rounded-full bg-background px-3 py-1 text-xs text-muted-foreground">
                          {t?.autosaveLabel ?? 'حفظ تلقائي'}: {formatTimeStable(lastAutosaveAt)}
                        </span>
                      </div>
                    )}

                    {summarySection}

                    <div className={`rounded-md border p-4 space-y-3 ${isReturn ? 'border-red-300 bg-red-50' : 'bg-background'}`}>
                      <div className="flex items-center justify-between">
                        <div className="text-sm font-medium">{t?.actionsLabel ?? 'العمليات'}</div>
                        <div className="flex items-center gap-2">
                          <Button
                            type="button"
                            variant={!isReturn ? 'default' : 'outline'}
                            size="sm"
                            onClick={() => setIsReturn(false)}
                          >
                            {t?.saleMode ?? 'مبيعات'}
                          </Button>
                          <Button
                            type="button"
                            variant={isReturn ? 'destructive' : 'outline'}
                            size="sm"
                            onClick={() => setIsReturn(true)}
                          >
                            {t?.returnMode ?? 'مردود مبيعات'}
                          </Button>
                        </div>
                      </div>
                      <div className={`rounded-xl border bg-muted/20 p-2 transition-opacity ${!isShiftOpen ? 'opacity-40 pointer-events-none select-none' : ''}`}>
                        <div className="grid grid-cols-2 gap-2">
                          <Button
                            type="button"
                            disabled={isSaveInvoicePending || !isShiftOpen}
                            variant="outline"
                            className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                            onClick={() => requestFinalizeInvoice('save')}
                          >
                            <span className="text-xl">{isSaveInvoicePending ? <Loader2 className="h-5 w-5 animate-spin" /> : '💾'}</span>
                            <span className="text-xs font-medium">{t?.saveInvoice ?? 'حفظ الفاتورة'}</span>
                          </Button>
                          <Button
                            type="button"
                            disabled={isSaveInvoicePending || !isShiftOpen}
                            variant="outline"
                            className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                            onClick={() => requestFinalizeInvoice('savePrint')}
                          >
                            <span className="text-xl">🧾</span>
                            <span className="text-xs font-medium">{t?.saveAndPrintInvoice ?? 'حفظ + طباعة'}</span>
                          </Button>
                          <Button
                            type="button"
                            variant="outline"
                            disabled={!isShiftOpen}
                            className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                            onClick={handleSuspend}
                          >
                            <span className="text-xl">⏸️</span>
                            <span className="text-xs font-medium">{t?.suspendInvoice ?? 'تعليق الفاتورة'}</span>
                          </Button>
                          <Button
                            type="button"
                            variant="outline"
                            disabled={!isShiftOpen}
                            className="h-auto flex-col items-center justify-center gap-1 rounded-md border-2 border-gray-300 bg-gray-50 px-2 py-2 text-gray-700 transition-all hover:bg-gray-100 hover:text-accent-foreground"
                            onClick={() => setShowSuspended(true)}
                          >
                            <span className="text-xl">📋</span>
                            <span className="text-xs font-medium">{t?.resumeInvoice ?? 'الفواتير المعلقة'}</span>
                            {suspendedInvoices.length > 0 && (
                              <span className="rounded-full bg-primary px-2 py-0.5 text-[10px] text-primary-foreground">
                                {suspendedInvoices.length}
                              </span>
                            )}
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>

                </aside>

                  <div className="flex min-h-0 flex-1 flex-col gap-2 self-stretch">
                    <div className="flex-1 min-h-[560px] overflow-auto rounded-md border xl:min-h-0">
                      {/* معلومات الزبون والطاولة المفعلة */}
                      <div className="sticky top-0 z-20 bg-gradient-to-b from-blue-50 to-blue-100 border-b-2 border-blue-200 px-4 py-4 flex gap-6 items-center flex-wrap justify-center text-center">
                        {selectedCustomer && (
                          <div className="flex items-center gap-2">
                            <span className="text-base font-bold text-blue-900">👤 زبون:</span>
                            <span className="text-base font-semibold text-blue-700 bg-white rounded px-3 py-1.5 shadow-sm">{selectedCustomer.name}</span>
                          </div>
                        )}
                        {activeRestaurantTable && (
                          <div className="flex items-center gap-2">
                            <span className="text-base font-bold text-blue-900">🪑 طاولة:</span>
                            <span className="text-base font-semibold text-blue-700 bg-white rounded px-3 py-1.5 shadow-sm">
                              {activeRestaurantTable.tableCode ? `${activeRestaurantTable.tableCode} - ` : ''}{activeRestaurantTable.name}
                            </span>
                          </div>
                        )}
                        {!selectedCustomer && !activeRestaurantTable && (
                          <div className="text-base font-medium text-muted-foreground italic">
                            اختر زبوناً أو طاولة لبدء الفاتورة
                          </div>
                        )}
                        <div className="ms-auto flex items-center gap-2">
                          <span className="text-xs font-medium text-blue-900">عرض الأصناف:</span>
                          <div className="inline-flex overflow-hidden rounded-md border border-blue-300 bg-white shadow-sm">
                            <button
                              type="button"
                              onClick={() => setCompactRowLayout(true)}
                              className={`px-3 py-1 text-xs font-medium transition-colors ${compactRowLayout ? 'bg-blue-600 text-white' : 'text-blue-700 hover:bg-blue-50'}`}
                              title="سطر واحد"
                            >
                              سطر واحد
                            </button>
                            <button
                              type="button"
                              onClick={() => setCompactRowLayout(false)}
                              className={`px-3 py-1 text-xs font-medium transition-colors ${!compactRowLayout ? 'bg-blue-600 text-white' : 'text-blue-700 hover:bg-blue-50'}`}
                              title="سطرين"
                            >
                              سطرين
                            </button>
                          </div>
                        </div>
                      </div>

                      <Table className="min-w-[1180px]">
                        <TableHeader className="sticky top-0 z-10 bg-background">
                          <TableRow>
                            <TableHead className="text-center w-10">
                              <Checkbox
                                checked={
                                  fields.length > 0 && partialPaySelectedIndexes.length === fields.length
                                    ? true
                                    : partialPaySelectedIndexes.length > 0 && partialPaySelectedIndexes.length < fields.length
                                      ? 'indeterminate'
                                      : false
                                }
                                onCheckedChange={(checked) => {
                                  if (checked) {
                                    setPartialPaySelectedIndexes(fields.map((_, idx) => idx));
                                  } else {
                                    setPartialPaySelectedIndexes([]);
                                  }
                                }}
                                aria-label="تحديد الكل"
                              />
                            </TableHead>
                            <TableHead className="text-center">{t?.item ?? 'الصنف'}</TableHead>
                            {showItemNumberColumn && <TableHead className="text-center">{t?.itemNumberLabel ?? 'رقم الصنف'}</TableHead>}
                            {showUnitColumn && <TableHead className="text-center">{t?.unitLabel ?? 'الوحدة'}</TableHead>}
                            {isWarehouseEnabled && <TableHead className="text-center">{t?.warehouseLabel ?? 'المستودع/الرف'}</TableHead>}
                            {showDescriptionColumn && <TableHead className="text-center">{t?.descriptionLabel ?? 'الوصف'}</TableHead>}
                            {showBarcodeColumn && <TableHead className="text-center">{t?.barcodeLabel ?? 'الباركود'}</TableHead>}
                            {showQuantityColumn && <TableHead className="text-center">{t?.quantity ?? 'الكمية'}</TableHead>}
                            {showPriceColumn && <TableHead className="text-center">{t?.price ?? 'السعر'}</TableHead>}
                            {showItemDiscountColumn && <TableHead className="text-center">{t?.itemDiscountLabel ?? 'خصم الصنف'}</TableHead>}
                            {showBonusColumn && <TableHead className="text-center">{t?.bonus ?? 'بونص'}</TableHead>}
                            {showTotalColumn && <TableHead className="text-right">{t?.total ?? 'الإجمالي'}</TableHead>}
                            {showActionsColumn && <TableHead className="text-center">
                              <div className="flex flex-col items-center gap-1">
                                {t?.actionsLabel ?? 'العمليات'}
                                {isAnyPartialPaySelected && (
                                  <Button
                                    type="button"
                                    size="sm"
                                    variant="secondary"
                                    className="mt-1 px-2 py-1 text-xs"
                                    onClick={() => setShowPartialPayDialog(true)}
                                  >
                                    💵 دفع جزئي
                                  </Button>
                                )}
                              </div>
                            </TableHead>}
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                        {fields.map((field, index) => {
                          const checkboxCell = (
                            <Checkbox
                              checked={partialPaySelectedIndexes.includes(index)}
                              onCheckedChange={(checked) => {
                                setPartialPaySelectedIndexes((prev) =>
                                  checked
                                    ? [...prev, index].filter((v, i, arr) => arr.indexOf(v) === i)
                                    : prev.filter((v) => v !== index)
                                );
                              }}
                              aria-label={`تحديد الصنف ${index + 1}`}
                            />
                          );
                          const itemSelectCell = (
                            <FormField
                              control={form.control}
                              name={`items.${index}.materialId`}
                              render={({ field }) => (
                                <FormItem>
                                  <Select
                                    onValueChange={(value) => {
                                      field.onChange(value);
                                      const material = allMaterials.find(m => m.id === value);
                                      const priceInfo = customerPricing?.prices.find(p => p.materialId === value);
                                      form.setValue(`items.${index}.unitPrice`, priceInfo?.price ?? material?.salePrice ?? 0);
                                      const currentDescription = form.getValues(`items.${index}.description`);
                                      if (!currentDescription && material?.name) {
                                        form.setValue(`items.${index}.description`, material.name);
                                      }
                                    }}
                                    defaultValue={field.value}
                                  >
                                    <FormControl>
                                      <SelectTrigger className="h-12 text-base font-semibold bg-green-50 [&>span]:mx-auto [&>span]:text-center">
                                        <SelectValue placeholder={t?.item ?? 'الصنف'} />
                                      </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                      {allMaterials.map((m, materialOptionIndex) => (
                                        <SelectItem key={`${String(m.id)}-${materialOptionIndex}`} value={m.id}>
                                          {getMaterialDisplayLabel(m)}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </FormItem>
                              )}
                            />
                          );
                          const itemNumberCellContent = itemsWithDetails[index]?.itemNumber ?? '-';
                          const unitCellContent = itemsWithDetails[index]?.unitLabel ?? '-';
                          const warehouseCellContent = (() => {
                            const materialId = String((watchAllItems[index] as any)?.materialId || '').trim();
                            const availableLocations = availableLocationsByMaterial.get(materialId) || [];
                            const currentWarehouseId = String((watchAllItems[index] as any)?.warehouseId || '').trim();
                            const currentShelfId = String((watchAllItems[index] as any)?.shelfId || '').trim();
                            const currentValue = currentWarehouseId && currentShelfId
                              ? `${currentWarehouseId}||${currentShelfId}`
                              : '';

                            if (availableLocations.length === 0) {
                              return (
                                <span className={`text-xs ${allowOutOfStockSales ? 'text-amber-600' : 'text-destructive'}`}>
                                  {allowOutOfStockSales
                                    ? (t?.noStockButSaleAllowed ?? 'لا يوجد رصيد متاح (البيع مسموح حسب الإعدادات)')
                                    : (t?.noStockForItem ?? 'لا يوجد رصيد متاح')}
                                </span>
                              );
                            }

                            if (availableLocations.length === 1) {
                              const location = availableLocations[0];
                              return (
                                <div className="text-xs">
                                  <div className="font-medium">{location.warehouseName} / {location.shelfName}</div>
                                  <div className="text-muted-foreground">{t?.availableQtyLabel ?? 'متاح'}: {location.quantity}</div>
                                </div>
                              );
                            }

                            return (
                              <Select
                                value={currentValue}
                                onValueChange={(value) => {
                                  const [warehouseId, shelfId] = value.split('||');
                                  form.setValue(`items.${index}.warehouseId`, warehouseId || '');
                                  form.setValue(`items.${index}.shelfId`, shelfId || '');
                                }}
                              >
                                <SelectTrigger className="min-w-[230px]">
                                  <SelectValue placeholder={t?.selectShelfBeforeSave ?? 'اختر الرف'} />
                                </SelectTrigger>
                                <SelectContent>
                                  {availableLocations.map((location, locationIndex) => (
                                    <SelectItem
                                      key={`${location.materialId}-${location.warehouseId}-${location.shelfId}-${locationIndex}`}
                                      value={`${location.warehouseId}||${location.shelfId}`}
                                    >
                                      {location.warehouseName} / {location.shelfName} ({location.quantity})
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            );
                          })();
                          const descriptionCellContent = (
                            <>
                              {itemsWithDetails[index]?.allowDescriptionEdit ? (
                                <FormField
                                  control={form.control}
                                  name={`items.${index}.description`}
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input
                                          {...field}
                                          className="min-w-[140px] text-center"
                                          placeholder={t?.descriptionLabel ?? 'الوصف'}
                                          onFocus={(e) => e.target.select()}
                                        />
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              ) : (
                                <span className="text-sm text-muted-foreground">
                                  {itemsWithDetails[index]?.description ?? itemsWithDetails[index]?.name ?? '-'}
                                </span>
                              )}
                              {(() => {
                                const currentLine = watchAllItems[index] as any;
                                const materialId = String(currentLine?.materialId || '').trim();
                                const material = allMaterials.find((entry) => entry.id === materialId);
                                if (!material || !isTrackedMaterial(material)) return null;

                                const trackedUnit = getTrackedUnitForLine(currentLine);
                                if (trackedUnit) {
                                  return (
                                    <div className="mt-2 inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] text-emerald-700">
                                      <span className="font-medium">{t?.trackedUnitTitle ?? 'الوحدة المتتبعة'}:</span>
                                      <span className="font-mono">{getTrackedUnitLabel(trackedUnit)}</span>
                                    </div>
                                  );
                                }

                                if (!isTrackedLineMissingUnit(currentLine)) return null;

                                return (
                                  <div className="mt-2 flex flex-wrap items-center justify-center gap-2">
                                    <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2.5 py-1 text-[11px] text-red-700">
                                      <AlertTriangle className="h-3.5 w-3.5" />
                                      {t?.trackedUnitRequired ?? 'يتطلب اختيار وحدة متتبعة'}
                                    </span>
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="sm"
                                      className="h-7 rounded-full border-red-200 px-3 text-[11px] text-red-700 hover:bg-red-50"
                                      onClick={() => openTrackedUnitDialog(
                                        material,
                                        Number(currentLine?.unitPrice || getUnitPriceForMaterial(material)),
                                        String(currentLine?.description || material.name || '').trim() || material.name
                                      )}
                                    >
                                      {t?.selectTrackedUnit ?? 'اختيار وحدة'}
                                    </Button>
                                  </div>
                                );
                              })()}
                            </>
                          );
                          const barcodeCellContent = itemsWithDetails[index]?.unitBarcode ?? '-';
                          const quantityCellContent = (
                            <FormField
                              control={form.control}
                              name={`items.${index}.quantity`}
                              render={({ field }) => (
                                <FormItem>
                                  <div className="flex items-center gap-2">
                                    <FormControl>
                                      <Input type="number" {...field} onFocus={(e) => e.target.select()} className="min-w-[90px] text-center" />
                                    </FormControl>
                                    <span className="text-xs text-muted-foreground">{t?.quantity ?? 'الكمية'}</span>
                                    <Button
                                      type="button"
                                      size="icon"
                                      variant="outline"
                                      className="h-9 w-9"
                                      onClick={() => {
                                        const current = form.getValues(`items.${index}.quantity`) || 0;
                                        form.setValue(`items.${index}.quantity`, Number(current) + 1);
                                      }}
                                    >
                                      <PlusCircle className="h-4 w-4" />
                                    </Button>
                                  </div>
                                </FormItem>
                              )}
                            />
                          );
                          const priceCellContent = (
                            <FormField
                              control={form.control}
                              name={`items.${index}.unitPrice`}
                              render={({ field }) => (
                                <FormItem>
                                  <FormControl>
                                    <div className="flex items-center gap-2">
                                      <Input
                                        type="number"
                                        step="0.01"
                                        {...field}
                                        className="font-mono min-w-[100px] text-center"
                                        onFocus={(e) => e.target.select()}
                                      />
                                      <span className="text-xs text-muted-foreground">{t?.price ?? 'السعر'}</span>
                                    </div>
                                  </FormControl>
                                </FormItem>
                              )}
                            />
                          );
                          const discountCellContent = (
                            <>
                              <FormField
                                control={form.control}
                                name={`items.${index}.discount`}
                                render={({ field }) => (
                                  <FormItem>
                                    <FormControl>
                                      <div className="flex items-center gap-2">
                                        <Input
                                          type="number"
                                          step="0.01"
                                          {...field}
                                          className="font-mono min-w-[100px] text-center"
                                          onFocus={(e) => e.target.select()}
                                        />
                                        <span className="text-xs text-muted-foreground">{t?.itemDiscountLabel ?? 'خصم الصنف'}</span>
                                      </div>
                                    </FormControl>
                                  </FormItem>
                                )}
                              />
                              {Number(itemsWithDetails[index]?.campaignPreviewDiscount || 0) > 0 && (
                                <p className="mt-1 text-xs text-emerald-700">
                                  {t?.campaignDiscountPreviewLabel ?? 'خصم الحملات (معاينة)'}: -{formatCurrency(Number(itemsWithDetails[index]?.campaignPreviewDiscount || 0), currencySymbol)}
                                </p>
                              )}
                            </>
                          );
                          const bonusCellContent = (
                            <>
                              {itemsWithDetails[index]?.bonus ?? 0}
                              <span className="ms-1 text-xs text-muted-foreground">{t?.bonus ?? 'بونص'}</span>
                            </>
                          );
                          const totalCellContent = formatCurrency(itemsWithDetails[index]?.total ?? 0, currencySymbol);
                          const actionsCellContent = (
                            <div className="flex items-center justify-center gap-1.5">
                              <button
                                type="button"
                                title="دفع جزئي"
                                disabled={!isShiftOpen || fields.length === 0}
                                onClick={() => handleOpenPartialPayRow(index)}
                                className="inline-flex flex-col items-center justify-center gap-0.5 rounded-lg border border-emerald-200 bg-emerald-50 px-2 py-1 text-emerald-700 shadow-sm transition-colors hover:bg-emerald-100 hover:border-emerald-300 disabled:pointer-events-none disabled:opacity-40 min-w-[46px]"
                              >
                                <span className="text-sm leading-none">💵</span>
                                <span className="text-[9px] font-medium leading-none">دفع جزئي</span>
                              </button>
                              <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveItem(index)}>
                                <Trash2 className="h-4 w-4 text-destructive" />
                              </Button>
                            </div>
                          );

                          if (compactRowLayout) {
                            return (
                              <TableRow key={field.id}>
                                <TableCell className="text-center w-10">{checkboxCell}</TableCell>
                                <TableCell className="py-2 min-w-[220px]">{itemSelectCell}</TableCell>
                                {showItemNumberColumn && <TableCell className="font-mono text-sm whitespace-nowrap text-center">{itemNumberCellContent}</TableCell>}
                                {showUnitColumn && <TableCell className="whitespace-nowrap text-center">{unitCellContent}</TableCell>}
                                {isWarehouseEnabled && <TableCell>{warehouseCellContent}</TableCell>}
                                {showDescriptionColumn && <TableCell className="text-center">{descriptionCellContent}</TableCell>}
                                {showBarcodeColumn && <TableCell className="font-mono text-sm whitespace-nowrap text-center">{barcodeCellContent}</TableCell>}
                                {showQuantityColumn && <TableCell>{quantityCellContent}</TableCell>}
                                {showPriceColumn && <TableCell>{priceCellContent}</TableCell>}
                                {showItemDiscountColumn && <TableCell>{discountCellContent}</TableCell>}
                                {showBonusColumn && <TableCell className="text-center font-mono">{bonusCellContent}</TableCell>}
                                {showTotalColumn && <TableCell className="text-right font-mono">{totalCellContent}</TableCell>}
                                {showActionsColumn && <TableCell>{actionsCellContent}</TableCell>}
                              </TableRow>
                            );
                          }

                          return (
                          <Fragment key={field.id}>
                            <TableRow>
                              <TableCell className="text-center w-10">
                                <Checkbox
                                  checked={partialPaySelectedIndexes.includes(index)}
                                  onCheckedChange={(checked) => {
                                    setPartialPaySelectedIndexes((prev) =>
                                      checked
                                        ? [...prev, index].filter((v, i, arr) => arr.indexOf(v) === i)
                                        : prev.filter((v) => v !== index)
                                    );
                                  }}
                                  aria-label={`تحديد الصنف ${index + 1}`}
                                />
                              </TableCell>
                            </TableRow>
                            <TableRow>
                              <TableCell colSpan={5} className="py-3">
                                <FormField
                                  control={form.control}
                                  name={`items.${index}.materialId`}
                                  render={({ field }) => (
                                    <FormItem>
                                      <Select
                                        onValueChange={(value) => {
                                          field.onChange(value);
                                          const material = allMaterials.find(m => m.id === value);
                                          const priceInfo = customerPricing?.prices.find(p => p.materialId === value);
                                          form.setValue(`items.${index}.unitPrice`, priceInfo?.price ?? material?.salePrice ?? 0);
                                          const currentDescription = form.getValues(`items.${index}.description`);
                                          if (!currentDescription && material?.name) {
                                            form.setValue(`items.${index}.description`, material.name);
                                          }
                                        }}
                                        defaultValue={field.value}
                                      >
                                        <FormControl>
                                          <SelectTrigger className="h-12 text-base font-semibold bg-green-50 [&>span]:mx-auto [&>span]:text-center">
                                            <SelectValue placeholder={t?.item ?? 'الصنف'} />
                                          </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                          {allMaterials.map((m, materialOptionIndex) => (
                                            <SelectItem key={`${String(m.id)}-${materialOptionIndex}`} value={m.id}>
                                              {getMaterialDisplayLabel(m)}
                                            </SelectItem>
                                          ))}
                                        </SelectContent>
                                      </Select>
                                    </FormItem>
                                  )}
                                />
                              </TableCell>
                              {showItemNumberColumn && <TableCell className="font-mono text-sm whitespace-nowrap text-center">{itemsWithDetails[index]?.itemNumber ?? '-'}</TableCell>}
                              {showUnitColumn && <TableCell className="whitespace-nowrap text-center">{itemsWithDetails[index]?.unitLabel ?? '-'}</TableCell>}
                              {isWarehouseEnabled && (
                                <TableCell>
                                  {(() => {
                                    const materialId = String((watchAllItems[index] as any)?.materialId || '').trim();
                                    const availableLocations = availableLocationsByMaterial.get(materialId) || [];
                                    const currentWarehouseId = String((watchAllItems[index] as any)?.warehouseId || '').trim();
                                    const currentShelfId = String((watchAllItems[index] as any)?.shelfId || '').trim();
                                    const currentValue = currentWarehouseId && currentShelfId
                                      ? `${currentWarehouseId}||${currentShelfId}`
                                      : '';

                                    if (availableLocations.length === 0) {
                                      return (
                                        <span className={`text-xs ${allowOutOfStockSales ? 'text-amber-600' : 'text-destructive'}`}>
                                          {allowOutOfStockSales
                                            ? (t?.noStockButSaleAllowed ?? 'لا يوجد رصيد متاح (البيع مسموح حسب الإعدادات)')
                                            : (t?.noStockForItem ?? 'لا يوجد رصيد متاح')}
                                        </span>
                                      );
                                    }

                                    if (availableLocations.length === 1) {
                                      const location = availableLocations[0];
                                      return (
                                        <div className="text-xs">
                                          <div className="font-medium">{location.warehouseName} / {location.shelfName}</div>
                                          <div className="text-muted-foreground">{t?.availableQtyLabel ?? 'متاح'}: {location.quantity}</div>
                                        </div>
                                      );
                                    }

                                    return (
                                      <Select
                                        value={currentValue}
                                        onValueChange={(value) => {
                                          const [warehouseId, shelfId] = value.split('||');
                                          form.setValue(`items.${index}.warehouseId`, warehouseId || '');
                                          form.setValue(`items.${index}.shelfId`, shelfId || '');
                                        }}
                                      >
                                        <SelectTrigger className="min-w-[230px]">
                                          <SelectValue placeholder={t?.selectShelfBeforeSave ?? 'اختر الرف'} />
                                        </SelectTrigger>
                                        <SelectContent>
                                          {availableLocations.map((location, locationIndex) => (
                                            <SelectItem
                                              key={`${location.materialId}-${location.warehouseId}-${location.shelfId}-${locationIndex}`}
                                              value={`${location.warehouseId}||${location.shelfId}`}
                                            >
                                              {location.warehouseName} / {location.shelfName} ({location.quantity})
                                            </SelectItem>
                                          ))}
                                        </SelectContent>
                                      </Select>
                                    );
                                  })()}
                                </TableCell>
                              )}
                              <TableCell colSpan={isWarehouseEnabled ? 2 : 3}></TableCell>
                            </TableRow>
                            <TableRow>
                              {showDescriptionColumn && <TableCell className="text-center">
                                {itemsWithDetails[index]?.allowDescriptionEdit ? (
                                  <FormField
                                    control={form.control}
                                    name={`items.${index}.description`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <FormControl>
                                          <Input
                                            {...field}
                                            className="min-w-[140px] text-center"
                                            placeholder={t?.descriptionLabel ?? 'الوصف'}
                                            onFocus={(e) => e.target.select()}
                                          />
                                        </FormControl>
                                      </FormItem>
                                    )}
                                  />
                                ) : (
                                  <span className="text-sm text-muted-foreground">
                                    {itemsWithDetails[index]?.description ?? itemsWithDetails[index]?.name ?? '-'}
                                  </span>
                                )}
                                {(() => {
                                  const currentLine = watchAllItems[index] as any;
                                  const materialId = String(currentLine?.materialId || '').trim();
                                  const material = allMaterials.find((entry) => entry.id === materialId);
                                  if (!material || !isTrackedMaterial(material)) return null;

                                  const trackedUnit = getTrackedUnitForLine(currentLine);
                                  if (trackedUnit) {
                                    return (
                                      <div className="mt-2 inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] text-emerald-700">
                                        <span className="font-medium">{t?.trackedUnitTitle ?? 'الوحدة المتتبعة'}:</span>
                                        <span className="font-mono">{getTrackedUnitLabel(trackedUnit)}</span>
                                      </div>
                                    );
                                  }

                                  if (!isTrackedLineMissingUnit(currentLine)) return null;

                                  return (
                                    <div className="mt-2 flex flex-wrap items-center justify-center gap-2">
                                      <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2.5 py-1 text-[11px] text-red-700">
                                        <AlertTriangle className="h-3.5 w-3.5" />
                                        {t?.trackedUnitRequired ?? 'يتطلب اختيار وحدة متتبعة'}
                                      </span>
                                      <Button
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        className="h-7 rounded-full border-red-200 px-3 text-[11px] text-red-700 hover:bg-red-50"
                                        onClick={() => openTrackedUnitDialog(
                                          material,
                                          Number(currentLine?.unitPrice || getUnitPriceForMaterial(material)),
                                          String(currentLine?.description || material.name || '').trim() || material.name
                                        )}
                                      >
                                        {t?.selectTrackedUnit ?? 'اختيار وحدة'}
                                      </Button>
                                    </div>
                                  );
                                })()}
                              </TableCell>}
                              {showBarcodeColumn && <TableCell className="font-mono text-sm whitespace-nowrap text-center">{itemsWithDetails[index]?.unitBarcode ?? '-'}</TableCell>}
                              {showQuantityColumn && <TableCell>
                                <FormField
                                  control={form.control}
                                  name={`items.${index}.quantity`}
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex items-center gap-2">
                                        <FormControl>
                                          <Input type="number" {...field} onFocus={(e) => e.target.select()} className="min-w-[90px] text-center" />
                                        </FormControl>
                                        <span className="text-xs text-muted-foreground">{t?.quantity ?? 'الكمية'}</span>
                                        <Button
                                          type="button"
                                          size="icon"
                                          variant="outline"
                                          className="h-9 w-9"
                                          onClick={() => {
                                            const current = form.getValues(`items.${index}.quantity`) || 0;
                                            form.setValue(`items.${index}.quantity`, Number(current) + 1);
                                          }}
                                        >
                                          <PlusCircle className="h-4 w-4" />
                                        </Button>
                                      </div>
                                    </FormItem>
                                  )}
                                />
                              </TableCell>}
                              {showPriceColumn && <TableCell>
                                <FormField
                                  control={form.control}
                                  name={`items.${index}.unitPrice`}
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <div className="flex items-center gap-2">
                                          <Input
                                            type="number"
                                            step="0.01"
                                            {...field}
                                            className="font-mono min-w-[100px] text-center"
                                            onFocus={(e) => e.target.select()}
                                          />
                                          <span className="text-xs text-muted-foreground">{t?.price ?? 'السعر'}</span>
                                        </div>
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              </TableCell>}
                              {showItemDiscountColumn && <TableCell>
                                <FormField
                                  control={form.control}
                                  name={`items.${index}.discount`}
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <div className="flex items-center gap-2">
                                          <Input
                                            type="number"
                                            step="0.01"
                                            {...field}
                                            className="font-mono min-w-[100px] text-center"
                                            onFocus={(e) => e.target.select()}
                                          />
                                          <span className="text-xs text-muted-foreground">{t?.itemDiscountLabel ?? 'خصم الصنف'}</span>
                                        </div>
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                                {Number(itemsWithDetails[index]?.campaignPreviewDiscount || 0) > 0 && (
                                  <p className="mt-1 text-xs text-emerald-700">
                                    {t?.campaignDiscountPreviewLabel ?? 'خصم الحملات (معاينة)'}: -{formatCurrency(Number(itemsWithDetails[index]?.campaignPreviewDiscount || 0), currencySymbol)}
                                  </p>
                                )}
                              </TableCell>}
                              {showBonusColumn && <TableCell className="text-center font-mono">
                                {itemsWithDetails[index]?.bonus ?? 0}
                                <span className="ms-1 text-xs text-muted-foreground">{t?.bonus ?? 'بونص'}</span>
                              </TableCell>}
                              {showTotalColumn && <TableCell className="text-right font-mono">{formatCurrency(itemsWithDetails[index]?.total ?? 0, currencySymbol)}</TableCell>}
                              {showActionsColumn && <TableCell>
                                <div className="flex items-center justify-center gap-1.5">
                                  <button
                                    type="button"
                                    title="دفع جزئي"
                                    disabled={!isShiftOpen || fields.length === 0}
                                    onClick={() => handleOpenPartialPayRow(index)}
                                    className="inline-flex flex-col items-center justify-center gap-0.5 rounded-lg border border-emerald-200 bg-emerald-50 px-2 py-1 text-emerald-700 shadow-sm transition-colors hover:bg-emerald-100 hover:border-emerald-300 disabled:pointer-events-none disabled:opacity-40 min-w-[46px]"
                                  >
                                    <span className="text-sm leading-none">💵</span>
                                    <span className="text-[9px] font-medium leading-none">دفع جزئي</span>
                                  </button>
                                  <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveItem(index)}>
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </div>
                              </TableCell>}
                            </TableRow>
                          </Fragment>
                          );
                        })}
                        {fields.length === 0 && (
                          <TableRow>
                            <TableCell colSpan={visibleColumnCount} className="text-center text-muted-foreground h-24">
                              {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                            </TableCell>
                          </TableRow>
                        )}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              </div>
          </form>
          </Form>
        </CardContent>
      </Card>

      {/* حوار سؤال الكمية للدفع الجزئي */}
      <Dialog open={showPartialPayRowQtyDialog} onOpenChange={(open) => { if (!open) setShowPartialPayRowQtyDialog(false); }}>
        <DialogContent className="w-[95vw] max-w-md rounded-2xl p-4 sm:p-6">
          <DialogHeader>
            <DialogTitle>كمية الدفع الجزئي</DialogTitle>
            <DialogDescription>
              {partialPayRowIndex !== null && (
                <>
                  الصنف: <span className="font-semibold">{itemsWithDetails[partialPayRowIndex]?.name ?? `صنف ${(partialPayRowIndex ?? 0) + 1}`}</span>
                  {' '}— الكمية الإجمالية: <span className="font-semibold font-mono">{Number(watchAllItems[partialPayRowIndex ?? 0]?.quantity ?? 1)}</span>
                </>
              )}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <label className="text-base font-semibold">الكمية المراد تسديدها</label>
            <div className="grid grid-cols-[56px_1fr_56px] items-center gap-2">
              <Button
                type="button"
                variant="outline"
                className="h-14 rounded-xl text-2xl"
                onClick={() => {
                  const nextQty = Math.max(1, Number(partialPayRowQty || 1) - 1);
                  setPartialPayRowQty(String(nextQty));
                }}
                aria-label="تقليل الكمية"
              >
                -
              </Button>
              <Input
                type="number"
                inputMode="numeric"
                min={1}
                max={partialPayRowIndex !== null ? Number(watchAllItems[partialPayRowIndex]?.quantity ?? 1) : 1}
                step={1}
                value={partialPayRowQty}
                onChange={(e) => setPartialPayRowQty(e.target.value)}
                onFocus={(e) => e.target.select()}
                autoFocus
                className="h-14 rounded-xl text-center text-xl font-semibold"
              />
              <Button
                type="button"
                variant="outline"
                className="h-14 rounded-xl text-2xl"
                onClick={() => {
                  const maxQty = partialPayRowIndex !== null ? Number(watchAllItems[partialPayRowIndex]?.quantity ?? 1) : 1;
                  const nextQty = Math.min(maxQty, Number(partialPayRowQty || 1) + 1);
                  setPartialPayRowQty(String(nextQty));
                }}
                aria-label="زيادة الكمية"
              >
                +
              </Button>
            </div>
            {partialPayRowIndex !== null && (() => {
              const qty = Math.max(1, Math.min(Number(partialPayRowQty || 1), Number(watchAllItems[partialPayRowIndex]?.quantity ?? 1)));
              const unitPrice = Number(watchAllItems[partialPayRowIndex]?.unitPrice ?? 0);
              return (
                <p className="rounded-lg bg-muted px-3 py-2 text-sm text-muted-foreground">
                  المبلغ المتوقع: <span className="font-mono font-semibold">{formatCurrency(qty * unitPrice, currencySymbol)}</span>
                </p>
              );
            })()}
          </div>
          <DialogFooter className="flex-col gap-2 sm:flex-row sm:gap-2">
            <Button type="button" variant="outline" className="h-12 w-full rounded-xl text-base sm:w-auto" onClick={() => setShowPartialPayRowQtyDialog(false)}>إلغاء</Button>
            <Button
              type="button"
              className="h-12 w-full rounded-xl text-base sm:w-auto"
              onClick={handleConfirmPartialPayRowQty}
              disabled={!partialPayRowQty || Number(partialPayRowQty) < 1}
            >
              متابعة الدفع الجزئي
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* حوار الدفع الجزئي النهائي */}
      <Dialog open={showPartialPayDialog} onOpenChange={setShowPartialPayDialog}>
        <DialogContent className="w-[95vw] max-w-xl rounded-2xl p-4 sm:p-6">
          <DialogHeader>
            <DialogTitle className="text-xl">دفع جزئي للأصناف المحددة</DialogTitle>
            <DialogDescription className="text-base">راجع الأصناف ثم أكمل عملية الدفع الجزئي.</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            {partialPaySelectedIndexes.map((idx) => {
              const qty = getPartialQtyForIndex(idx);
              const unitPrice = Number(watchAllItems[idx]?.unitPrice ?? 0);
              return (
                <div key={idx} className="flex items-center justify-between rounded-xl border bg-muted/30 px-4 py-3">
                  <div>
                    <div className="text-base font-semibold">{itemsWithDetails[idx]?.name ?? `صنف ${idx + 1}`}</div>
                    <div className="text-sm text-muted-foreground">الكمية: {qty} × {formatCurrency(unitPrice, currencySymbol)}</div>
                  </div>
                  <span className="font-mono text-lg font-semibold">{formatCurrency(qty * unitPrice, currencySymbol)}</span>
                </div>
              );
            })}
            {partialPaySelectedIndexes.length > 0 && (
              <div className="flex items-center justify-between rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-lg font-semibold text-emerald-900">
                <span>الإجمالي</span>
                <span className="font-mono">{formatCurrency(partialPayTotal, currencySymbol)}</span>
              </div>
            )}
          </div>
          <DialogFooter className="flex-col gap-2 sm:flex-row sm:gap-2">
            <Button
              type="button"
              variant="outline"
              className="h-12 w-full rounded-xl text-base sm:w-auto"
              onClick={() => {
                setShowPartialPayDialog(false);
                setPartialPaySelectedIndexes([]);
                setPartialPayRowIndex(null);
                setPartialPayRowQty('1');
              }}
            >
              إلغاء
            </Button>
            <Button
              type="button"
              variant="default"
              className="h-12 w-full rounded-xl text-base sm:w-auto"
              onClick={handleSubmitPartialPayment}
              disabled={isPartialPaymentPending || partialPaySelectedIndexes.length === 0 || partialPayTotal <= 0}
            >
              {isPartialPaymentPending ? <Loader2 className="h-5 w-5 animate-spin" /> : 'متابعة الدفع الجزئي'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showOpenShiftDialog} onOpenChange={setShowOpenShiftDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t?.openShift ?? 'افتتاح الوردية'}</DialogTitle>
            <DialogDescription>{t?.openShiftDesc ?? 'أدخل الأرصدة الافتتاحية قبل البدء بالبيع.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div className="space-y-1">
              <label className="text-sm font-medium">{t?.openingCash ?? 'الرصيد الافتتاحي النقدي'}</label>
              <Input type="number" step="0.01" inputMode="decimal" value={openShiftCash} onChange={(e) => setOpenShiftCash(e.target.value)} onFocus={(e) => e.target.select()} />
            </div>
            <div className="space-y-1">
              <label className="text-sm font-medium">{t?.openingVisa ?? 'الرصيد الافتتاحي للبطاقة'}</label>
              <Input type="number" step="0.01" inputMode="decimal" value={openShiftVisa} onChange={(e) => setOpenShiftVisa(e.target.value)} onFocus={(e) => e.target.select()} />
            </div>
            <div className="space-y-1">
              <label className="text-sm font-medium">{t?.notes ?? 'ملاحظات'}</label>
              <Input value={openShiftNotes} onChange={(e) => setOpenShiftNotes(e.target.value)} placeholder={t?.optionalNotes ?? 'ملاحظات اختيارية'} />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowOpenShiftDialog(false)}>{t?.cancel ?? 'إلغاء'}</Button>
            <Button type="button" onClick={handleOpenShiftSubmit} disabled={isShiftPending}>{t?.openShift ?? 'افتتاح الوردية'}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showCloseShiftDialog} onOpenChange={setShowCloseShiftDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t?.closeShift ?? 'إغلاق الوردية'}</DialogTitle>
            <DialogDescription>{t?.closeShiftDesc ?? 'ملخص الوردية الحالية — أدخل الجرد الفعلي ثم أغلق الوردية.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            {/* ─── ملخص الوردية ─── */}
            {activeShift && (
              <div className="rounded-md border bg-muted/20 p-3 text-xs space-y-1.5">
                <p className="mb-1 text-sm font-semibold">{t?.shiftSummaryTitle ?? 'ملخص الوردية'}</p>
                <div className="flex justify-between"><span className="text-muted-foreground">{t?.cashierLabel ?? 'الكاشير'}</span><span className="font-medium">{cashierName || '—'}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">{t?.shiftStartedAt ?? 'بداية الوردية'}</span><span className="font-mono">{formatDateTimeStable(activeShift.startedAt)}</span></div>
                <div className="my-1 border-t" />
                <div className="flex justify-between"><span>{t?.openingCash ?? 'نقدي افتتاحي'}</span><span className="font-mono">{formatCurrency(activeShift.openingCash || 0, currencySymbol)}</span></div>
                <div className="flex justify-between"><span>{t?.openingVisa ?? 'بطاقة افتتاحية'}</span><span className="font-mono">{formatCurrency(activeShift.openingVisa || 0, currencySymbol)}</span></div>
                <div className="my-1 border-t" />
                <div className="flex justify-between"><span>{t?.cashSales ?? 'مبيعات نقدية'}</span><span className="font-mono">{formatCurrency(activeShift.cashSalesAmount || 0, currencySymbol)}</span></div>
                <div className="flex justify-between"><span>{t?.visaSales ?? 'مبيعات بطاقة'}</span><span className="font-mono">{formatCurrency(activeShift.visaSalesAmount || 0, currencySymbol)}</span></div>
                <div className="flex justify-between"><span>{t?.totalSalesAmount ?? 'إجمالي المبيعات'}</span><span className="font-mono font-semibold">{formatCurrency((activeShift.cashSalesAmount || 0) + (activeShift.visaSalesAmount || 0) + (activeShift.receivablesAmount || 0) + (activeShift.couponAmount || 0), currencySymbol)}</span></div>
                <div className="my-1 border-t" />
                <div className="flex justify-between"><span className="font-medium">{t?.expectedCashAtClose ?? 'نقدي متوقع عند الإغلاق'}</span><span className="font-mono font-semibold">{formatCurrency(activeShift.expectedCashAtClose || 0, currencySymbol)}</span></div>
                <div className="flex justify-between"><span className="font-medium">{t?.expectedVisaAtClose ?? 'بطاقة متوقعة عند الإغلاق'}</span><span className="font-mono font-semibold">{formatCurrency(activeShift.expectedVisaAtClose || 0, currencySymbol)}</span></div>
              </div>
            )}
            <div className="space-y-1">
              <label className="text-sm font-medium">{t?.countedCashAtClose ?? 'الجرد الفعلي النقدي'}</label>
              <Input type="number" step="0.01" inputMode="decimal" value={closeShiftCash} onChange={(e) => setCloseShiftCash(e.target.value)} onFocus={(e) => e.target.select()} />
            </div>
            <div className="space-y-1">
              <label className="text-sm font-medium">{t?.countedVisaAtClose ?? 'الجرد الفعلي للبطاقة'}</label>
              <Input type="number" step="0.01" inputMode="decimal" value={closeShiftVisa} onChange={(e) => setCloseShiftVisa(e.target.value)} onFocus={(e) => e.target.select()} />
            </div>
            <div className="space-y-1">
              <label className="text-sm font-medium">{t?.notes ?? 'ملاحظات'}</label>
              <Input value={closeShiftNotes} onChange={(e) => setCloseShiftNotes(e.target.value)} placeholder={t?.optionalNotes ?? 'ملاحظات اختيارية'} />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowCloseShiftDialog(false)}>{t?.cancel ?? 'إلغاء'}</Button>
            <Button type="button" variant="outline" onClick={printShiftSummary} disabled={!activeShift}>
              <Printer className="me-1.5 h-4 w-4" />{t?.printShiftSummary ?? 'طباعة'}
            </Button>
            <Button type="button" variant="destructive" onClick={handleCloseShiftSubmit} disabled={isShiftPending}>{t?.closeShift ?? 'إغلاق الوردية'}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showPendingInvoiceBeforeCloseDialog} onOpenChange={setShowPendingInvoiceBeforeCloseDialog}>
        <DialogContent className="w-[95vw] max-w-md overflow-x-hidden">
          <DialogHeader>
            <DialogTitle>{t?.closeShiftPendingInvoiceTitle ?? 'يوجد فاتورة غير منتهية'}</DialogTitle>
            <DialogDescription>
              {t?.closeShiftPendingInvoiceDesc ?? 'يجب أن يكون جدول الفاتورة فارغاً قبل إغلاق الوردية. اختر الإجراء المناسب للفاتورة الحالية.'}
            </DialogDescription>
          </DialogHeader>
          <div className="rounded-md border bg-muted/20 p-3 text-sm">
            {(t?.closeShiftPendingInvoiceCountLabel ?? 'عدد الأصناف الحالية')}: <span className="font-semibold">{pendingInvoiceLineCount}</span>
          </div>
          <DialogFooter className="flex-col gap-2 sm:flex-col">
            <Button
              type="button"
              variant="outline"
              className="h-auto min-h-10 w-full whitespace-normal break-words text-center leading-relaxed"
              onClick={() => setShowPendingInvoiceBeforeCloseDialog(false)}
            >
              {t?.returnToInvoice ?? 'العودة للفاتورة'}
            </Button>
            <Button
              type="button"
              variant="secondary"
              className="h-auto min-h-10 w-full whitespace-normal break-words text-center leading-relaxed"
              onClick={handleSuspendPendingInvoiceAndContinueClose}
            >
              {t?.suspendThenCloseShift ?? 'تعليق الفاتورة ثم متابعة الإغلاق'}
            </Button>
            <Button
              type="button"
              variant="destructive"
              className="h-auto min-h-10 w-full whitespace-normal break-words text-center leading-relaxed"
              onClick={handleDiscardPendingInvoiceAndContinueClose}
            >
              {t?.discardThenCloseShift ?? 'إلغاء الفاتورة وتفريغ الجدول'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showShiftConflictDialog} onOpenChange={setShowShiftConflictDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t?.shiftAlreadyOpenTitle ?? 'يوجد وردية مفتوحة'}</DialogTitle>
            <DialogDescription>
              {t?.shiftAlreadyOpenDecision ?? `لديك وردية نشطة غير مغلقة باسم: ${String(cashierName || activeShift?.userName || 'المستخدم الحالي')}. هل تريد الاستمرار بها أم إغلاقها وبدء وردية جديدة؟`}
            </DialogDescription>
          </DialogHeader>
          {activeShift && (
            <div className="rounded-md border bg-muted/20 p-3 text-xs space-y-1.5">
              <div className="flex justify-between"><span className="text-muted-foreground">{t?.cashierLabel ?? 'الكاشير'}</span><span className="font-medium">{cashierName || '—'}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">{t?.shiftStartedAt ?? 'بداية الوردية'}</span><span className="font-mono">{formatDateTimeStable(activeShift.startedAt)}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">{t?.expectedCashAtClose ?? 'نقدي متوقع عند الإغلاق'}</span><span className="font-mono">{formatCurrency(activeShift.expectedCashAtClose || 0, currencySymbol)}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">{t?.expectedVisaAtClose ?? 'بطاقة متوقعة عند الإغلاق'}</span><span className="font-mono">{formatCurrency(activeShift.expectedVisaAtClose || 0, currencySymbol)}</span></div>
            </div>
          )}
          <DialogFooter>
            <Button type="button" variant="outline" onClick={handleContinueExistingShift} disabled={isShiftPending}>
              {t?.continueCurrentShift ?? 'الاستمرار بالوردية الحالية'}
            </Button>
            <Button type="button" variant="destructive" onClick={handleClosePreviousAndOpenNewShift} disabled={isShiftPending}>
              {t?.closePreviousOpenNewShift ?? 'إغلاق السابقة وفتح جديدة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showTableSwitchConfirmDialog} onOpenChange={setShowTableSwitchConfirmDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>تبديل الطاولة</DialogTitle>
            <DialogDescription>
              لديك أصناف غير محفوظة في الطاولة الحالية. ماذا تريد أن تفعل؟
            </DialogDescription>
          </DialogHeader>
          <div className="rounded-md border bg-amber-50 border-amber-200 p-3 text-sm">
            <div className="font-medium text-amber-900 mb-2">الأصناف المعلقة:</div>
            <div className="text-amber-800 font-mono text-xs space-y-1">
              {pendingInvoiceLineCount} أصناف بانتظار الحفظ
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowTableSwitchConfirmDialog(false)}>
              العودة
            </Button>
            <Button type="button" variant="secondary" onClick={handleConfirmTableSwitchWithSuspend}>
              تعليق الفاتورة والانتقال للطاولة الأخرى
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showPartialCheckoutInfoDialog} onOpenChange={setShowPartialCheckoutInfoDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>محاسبة الطاولة (كاملة أو جزئية)</DialogTitle>
            <DialogDescription>
              شرح كيفية محاسبة حساب الطاولة
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 text-sm">
            <div>
              <h4 className="font-semibold mb-2">الطريقة 1: محاسبة الفاتورة الكاملة</h4>
              <ol className="list-decimal list-inside space-y-1 text-muted-foreground">
                <li>اختر الطاولة المراد محاسبتها</li>
                <li>تأكد من وجود جميع الأصناف المطلوبة في الفاتورة</li>
                <li>انقر على زر "إتمام الفاتورة" أو "حفظ الفاتورة"</li>
                <li>اختر طريقة الدفع (نقدي، بطاقة، إلخ)</li>
                <li>تم إقفال الحساب كاملاً والطاولة متاحة للعملاء الجدد</li>
              </ol>
            </div>
            <div>
              <h4 className="font-semibold mb-2">الطريقة 2: محاسبة جزئية (تقسيم الحساب)</h4>
              <ol className="list-decimal list-inside space-y-1 text-muted-foreground">
                <li>اختر الأصناف المراد محاسبتها من الفاتورة</li>
                <li>انقر على "دفع جزئي" أو استخدم زر الدفع المخصص</li>
                <li>أدخل المبلغ أو اختر الأصناف المحددة</li>
                <li>أكمل عملية الدفع</li>
                <li>ستبقى الأصناف المتبقية في حساب الطاولة معلقة</li>
                <li>يمكن الانتقال لطاولة أخرى والعودة لاحقاً لإكمال الحساب</li>
              </ol>
            </div>
            <div className="rounded-md bg-blue-50 border border-blue-200 p-3 text-blue-900">
              <div className="font-semibold mb-1">ملاحظة مهمة:</div>
              <p>إذا كنت تريد محاسبة جزء من الحساب فقط، اختر الأصناف المحددة قبل الضغط على "دفع" أو "محاسبة".</p>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" onClick={() => setShowPartialCheckoutInfoDialog(false)}>
              حسناً، فهمت
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showAccounting} onOpenChange={setShowAccounting} modal={false}>
        <DialogContent
          className="max-h-[90vh] max-w-6xl overflow-y-auto"
          onInteractOutside={(event) => {
            const target = event.target as HTMLElement | null;
            if (target?.closest('[data-radix-popper-content-wrapper]')) {
              event.preventDefault();
            }
          }}
        >
          <DialogHeader>
            <DialogTitle>{t?.accountingButton ?? 'محاسبة'}</DialogTitle>
            <DialogDescription>{t?.accountingDesc ?? 'كشف حساب الزبون وسند القبض.'}</DialogDescription>
          </DialogHeader>
          <div className="flex flex-wrap gap-2">
            <Button
              type="button"
              variant={accountingView === 'statement' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setAccountingView('statement')}
            >
              {t?.accountStatementTab ?? 'كشف حساب'}
            </Button>
            <Button
              type="button"
              variant={accountingView === 'payment' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setAccountingView('payment')}
            >
              {t?.paymentVoucherTab ?? 'سند قبض'}
            </Button>
          </div>
          <div className="mt-4">
            {accountingView === 'statement' ? (
              <PartyStatement
                customers={customers}
                suppliers={suppliers}
                invoices={invoices}
                orders={orders}
                customerPayments={customerPayments}
                supplierPayments={supplierPayments}
                initialPartyId={selectedCustomerId ? `customer:${selectedCustomerId}` : undefined}
                t={tStatement}
                tGlobal={tGlobal}
                locale={locale}
                currencySymbol={currencySymbol}
              />
            ) : (
              <PaymentVoucherForm
                customers={customers}
                suppliers={suppliers}
                banks={banks}
                currencies={currencies}
                defaultCurrency={defaultCurrency}
                initialCustomerId={selectedCustomerId || ''}
                t={t}
                tGlobal={tGlobal}
                currencySymbol={currencySymbol}
              />
            )}
          </div>
        </DialogContent>
      </Dialog>

      <AddCustomerDialog
        open={showAddCustomerDialog}
        onOpenChange={setShowAddCustomerDialog}
        t={t}
        salesReps={salesReps}
        onCustomerAdded={(customer) => {
          setCustomerList((prev) => [...prev, customer]);
          form.setValue('customerId', customer.id);
        }}
      />

      <Dialog
        open={showShapeDialog}
        onOpenChange={(open) => {
          setShowShapeDialog(open);
          if (!open) {
            setPendingShapeMaterial(null);
            setPendingShapeBasePrice(0);
            setPendingShapeBarcode(undefined);
            setSelectedShapeId('');
            requestAnimationFrame(() => barcodeRef.current?.focus());
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t?.selectProductShapeTitle ?? 'اختيار شكل المنتج'}</DialogTitle>
            <DialogDescription>{t?.selectProductShapeDesc ?? 'اختر الشكل المطلوب قبل إضافة الصنف للفاتورة.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">{t?.itemName ?? 'اسم الصنف'}</label>
              <Input value={pendingShapeMaterial?.name || ''} readOnly disabled className="bg-muted" />
            </div>
            <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
              {getActiveProductShapes(pendingShapeMaterial as ProductionItem).map((shape, shapeIndex) => (
                <button
                  key={`${String(shape.id)}-${shapeIndex}`}
                  type="button"
                  className="rounded-md border p-3 text-right transition-colors hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  onClick={() => {
                    setSelectedShapeId(shape.id);
                    handleConfirmProductShape(shape.id);
                  }}
                >
                  <div className="text-sm font-semibold">{shape.name}</div>
                  <div className="mt-2 space-y-1 text-xs text-muted-foreground">
                    <div className="flex items-center justify-between gap-2">
                      <span>{t?.salePriceLabel ?? 'سعر البيع'}</span>
                      <span className="font-mono text-foreground">{formatCurrency(shape.salePrice || 0, currencySymbol)}</span>
                    </div>
                    <div className="flex items-center justify-between gap-2">
                      <span>{t?.productShapeCostLabel ?? 'سعر التكلفة'}</span>
                      <span className="font-mono text-foreground">{formatCurrency(shape.costPrice || 0, currencySymbol)}</span>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowShapeDialog(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showWeightDialog} onOpenChange={setShowWeightDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{isManualVolumeDialog ? (t?.volumeDialogTitle ?? 'إدخال الحجم') : (t?.weightDialogTitle ?? 'قراءة الوزن')}</DialogTitle>
            <DialogDescription>{isManualVolumeDialog ? (t?.volumeDialogDesc ?? 'أدخل حجم المنتج ليتم إضافته للفاتورة.') : (t?.weightDialogDesc ?? 'أدخل وزن المنتج ليتم إضافته للفاتورة.')}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">{t?.itemName ?? 'اسم الصنف'}</label>
              <Input value={pendingWeightDescription || pendingWeightMaterial?.name || ''} readOnly disabled className="bg-muted" />
            </div>
            {pendingMeasurementMode === 'volume' && pendingVolumeOptions.length > 0 && (
              <div className="space-y-2">
                <label className="text-sm font-medium">{t?.secondaryUnitLabel ?? 'الوحدة الفرعية'}</label>
                <Select
                  value={selectedVolumeOptionKey}
                  onValueChange={(value) => {
                    setSelectedVolumeOptionKey(value);
                    const selected = pendingVolumeOptions.find((option) => option.key === value);
                    const material = pendingWeightMaterial;
                    if (!selected || !material) return;
                    setPendingWeightUnitPrice(Number(selected.price || 0));
                    setPendingWeightDescription(`${material.name} - ${selected.label}`);
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t?.secondaryUnitPlaceholder ?? 'اختر الوحدة الفرعية'} />
                  </SelectTrigger>
                  <SelectContent>
                    {pendingVolumeOptions.map((option) => (
                      <SelectItem key={option.key} value={option.key}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            <div className="space-y-2">
              <label className="text-sm font-medium">{isManualVolumeDialog ? (t?.volumeLabel ?? 'الحجم') : (t?.weightLabel ?? 'الوزن (كغم)')}</label>
              <Input
                type="number"
                step="0.001"
                value={weightInput}
                onChange={(e) => setWeightInput(e.target.value)}
                placeholder={isManualVolumeDialog ? (t?.volumePlaceholder ?? 'أدخل الحجم...') : (t?.weightPlaceholder ?? 'أدخل الوزن...')}
                ref={weightInputRef}
              />
            </div>
            {!isManualVolumeDialog && effectiveScaleMode === 'hid' && (
              <p className="text-xs text-muted-foreground">{t?.scaleHidHint ?? 'وضع HID: انتظر قراءة الميزان أو أدخل الوزن يدويًا.'}</p>
            )}
            {!isManualVolumeDialog && effectiveScaleMode === 'serial' && (
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  {!isSerialConnected ? (
                    <Button type="button" variant="outline" size="sm" onClick={() => connectSerialPort(false)} disabled={isSerialConnecting || !isSerialSupported}>
                      {isSerialConnecting ? (t?.connectingScale ?? 'جاري الاتصال...') : (t?.connectScale ?? 'اتصال الميزان')}
                    </Button>
                  ) : (
                    <Button type="button" variant="outline" size="sm" onClick={() => closeSerialReader()}>
                      {t?.disconnectScale ?? 'فصل الميزان'}
                    </Button>
                  )}
                  <span className="text-xs text-muted-foreground">
                    {isSerialConnected ? (t?.scaleConnected ?? 'متصل') : (t?.scaleDisconnected ?? 'غير متصل')}
                  </span>
                </div>
                {!isSerialSupported && (
                  <p className="text-xs text-destructive">{t?.webSerialNotSupported ?? 'المتصفح الحالي لا يدعم Web Serial. استخدم Chrome/Edge.'}</p>
                )}
              </div>
            )}
            <div className="text-xs text-muted-foreground">
              {(t?.unitPriceLabel ?? 'سعر الوحدة')}: {formatCurrency(pendingWeightUnitPrice || 0, currencySymbol)}
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowWeightDialog(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              variant="secondary"
              onClick={() => {
                if (!pendingWeightMaterial) return;

                const primaryDescription = pendingMeasurementMode === 'volume'
                  ? pendingWeightMaterial.name
                  : (pendingWeightDescription || pendingWeightMaterial.name);

                const updated = addOrIncrementItem(
                  pendingWeightMaterial.id,
                  pendingWeightPrimaryPrice || pendingWeightUnitPrice,
                  1,
                  primaryDescription,
                  undefined,
                  resolveDefaultSourceForMaterial(pendingWeightMaterial.id),
                );
                toast({
                  title: t?.itemAdded ?? 'تمت إضافة الصنف',
                  description: `${primaryDescription}: ${updated}`,
                });

                setShowWeightDialog(false);
                setPendingWeightMaterial(null);
                setPendingWeightUnitPrice(0);
                setPendingWeightPrimaryPrice(0);
                setPendingWeightDescription('');
                setPendingMeasurementMode('weight');
                setPendingVolumeOptions([]);
                setSelectedVolumeOptionKey('');
                setWeightInput('');
                requestAnimationFrame(() => barcodeRef.current?.focus());
              }}
            >
              {pendingMeasurementMode === 'volume'
                ? (t?.addPrimaryUnit ?? 'إضافة بالوحدة الرئيسية')
                : (t?.addFullPackage ?? 'إضافة كامل العبوة')}
            </Button>
            <Button
              type="button"
              onClick={() => {
                const weightValue = parseFloat(weightInput);
                if (!pendingWeightMaterial || isNaN(weightValue) || weightValue <= 0) {
                  toast({
                    title: t?.validationError ?? 'خطأ في التحقق',
                    description: isManualVolumeDialog
                      ? (t?.volumeInvalid ?? 'الرجاء إدخال حجم صحيح.')
                      : (t?.weightInvalid ?? 'الرجاء إدخال وزن صحيح.'),
                    variant: 'destructive',
                  });
                  return;
                }

                const updated = addOrIncrementItem(
                  pendingWeightMaterial.id,
                  pendingWeightUnitPrice,
                  weightValue,
                  pendingWeightDescription || pendingWeightMaterial.name,
                  undefined,
                  resolveDefaultSourceForMaterial(pendingWeightMaterial.id),
                );
                toast({
                  title: t?.itemAdded ?? 'تمت إضافة الصنف',
                  description: `${pendingWeightDescription || pendingWeightMaterial.name}: ${updated}`,
                });

                setShowWeightDialog(false);
                setPendingWeightMaterial(null);
                setPendingWeightUnitPrice(0);
                setPendingWeightPrimaryPrice(0);
                setPendingWeightDescription('');
                setPendingMeasurementMode('weight');
                setPendingVolumeOptions([]);
                setSelectedVolumeOptionKey('');
                setWeightInput('');
                requestAnimationFrame(() => barcodeRef.current?.focus());
              }}
            >
              {t?.addItem ?? 'إضافة الصنف'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={showTrackedUnitDialog}
        onOpenChange={(open) => {
          setShowTrackedUnitDialog(open);
          if (!open) {
            closeTrackedUnitDialog();
          }
        }}
      >
        <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-4xl">
          <DialogHeader>
            <DialogTitle>{t?.trackedUnitTitle ?? 'اختيار الرقم التسلسلي / RFID'}</DialogTitle>
            <DialogDescription>{t?.trackedUnitDesc ?? 'اختر الوحدة قبل إضافة الصنف للفاتورة.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <div className="space-y-1">
                <label className="text-sm font-medium">{t?.itemName ?? 'اسم الصنف'}</label>
                <Input value={pendingTrackedDescription || pendingTrackedMaterial?.name || ''} readOnly disabled className="bg-muted" />
              </div>
              <div className="space-y-1">
                <label className="text-sm font-medium">{t?.search ?? 'بحث'}</label>
                <Input
                  value={trackedUnitSearch}
                  onChange={(e) => setTrackedUnitSearch(e.target.value)}
                  placeholder={t?.trackedUnitSearchPlaceholder ?? 'ابحث بالرقم التسلسلي أو RFID...'}
                  autoFocus
                />
              </div>
            </div>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t?.serialNumberLabel ?? 'الرقم التسلسلي'}</TableHead>
                    <TableHead>{t?.rfidCodeLabel ?? 'RFID'}</TableHead>
                    <TableHead>{t?.location ?? 'الموقع'}</TableHead>
                    <TableHead>{t?.status ?? 'الحالة'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredTrackedUnits.map((unit, unitIndex) => (
                    <TableRow
                      key={`${String(unit.id)}-${unitIndex}`}
                      className="cursor-pointer"
                      onClick={() => handleSelectTrackedUnit(unit)}
                    >
                      <TableCell className="font-mono text-xs">{(unit.serialNumber || '').trim() || '-'}</TableCell>
                      <TableCell className="font-mono text-xs">{(unit.rfidCode || '').trim() || '-'}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">{(unit.location || '').trim() || '-'}</TableCell>
                      <TableCell className="text-xs">{unit.status}</TableCell>
                    </TableRow>
                  ))}
                  {filteredTrackedUnits.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={4} className="text-center text-muted-foreground h-20">
                        {t?.noAvailableTrackedUnits ?? 'لا توجد وحدات متاحة.'}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={closeTrackedUnitDialog}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={showAddMaterialDialog}
        onOpenChange={(open) => {
          setShowAddMaterialDialog(open);
          if (!open) {
            setAddMaterialInitialValues(undefined);
            setNotFoundBarcode('');
            requestAnimationFrame(() => barcodeRef.current?.focus());
          }
        }}
      >
        <MaterialItemDialog
          items={allMaterials}
          t={t}
          tGlobal={tGlobal}
          itemGroups={itemGroups}
          initialValues={addMaterialInitialValues}
          onFinished={() => {
            setShowAddMaterialDialog(false);
            setAddMaterialInitialValues(undefined);
            setNotFoundBarcode('');
            requestAnimationFrame(() => barcodeRef.current?.focus());
          }}
          onCreated={(item) => handleMaterialCreated(item as ProductionItem)}
        />
      </Dialog>

      <Dialog
        open={showRestaurantTablesDialog}
        onOpenChange={(open) => {
          setShowRestaurantTablesDialog(open);
          if (!open) {
            requestAnimationFrame(() => barcodeRef.current?.focus());
          }
        }}
      >
        <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-md">
          <DialogHeader>
            <DialogTitle>إدارة الطاولات</DialogTitle>
            <DialogDescription>اختر طاولة نشطة أو صفّ الطاولات حسب المنطقة.</DialogDescription>
          </DialogHeader>

          <div className="space-y-2 rounded-xl border bg-background p-3">
            <div className="flex items-center justify-between">
              {activeRestaurantTable ? (
                <span className="rounded-full bg-emerald-100 px-2.5 py-1 text-xs font-medium text-emerald-700">
                  الطاولة النشطة: {activeRestaurantTable.name}
                </span>
              ) : (
                <span className="rounded-full bg-amber-100 px-2.5 py-1 text-xs font-medium text-amber-700">
                  بدون طاولة نشطة
                </span>
              )}
            </div>

            <div className="grid grid-cols-1 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center">
              <Select value={selectedAreaFilter} onValueChange={setSelectedAreaFilter}>
                <SelectTrigger className="h-9">
                  <SelectValue placeholder="تصفية حسب المنطقة" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="__all__">كل المناطق</SelectItem>
                  {restaurantAreas.map((area) => (
                    <SelectItem key={area.id} value={area.id}>{area.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {activeRestaurantTable && (
                <span className="text-xs text-muted-foreground">
                  {activeRestaurantAreaName} • {activeRestaurantTable.seats} مقاعد
                </span>
              )}
            </div>

            {filteredRestaurantTables.length === 0 ? (
              <div className="rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">
                لا توجد طاولات في هذا القسم.
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-2">
                {filteredRestaurantTables.map((table) => {
                  const isActive = activeRestaurantTableId === table.id;
                  const isOccupied = occupiedTableIds.has(table.id);
                  return (
                    <button
                      key={table.id}
                      type="button"
                      onClick={() => {
                        handleSelectRestaurantTable(table.id);
                        setShowRestaurantTablesDialog(false);
                      }}
                      className={cn(
                        'rounded-lg border px-2 py-2 text-start transition',
                        isActive
                          ? 'border-primary bg-primary/10'
                          : isOccupied
                            ? 'border-amber-300 bg-amber-50 hover:bg-amber-100'
                            : 'hover:bg-muted/50'
                      )}
                    >
                      <div className="text-sm font-medium">{table.name}</div>
                      <div className="mt-1 text-[11px] text-muted-foreground">
                        {table.seats} مقاعد • {isOccupied ? 'مشغولة' : 'متاحة'}
                      </div>
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowRestaurantTablesDialog(false)}>
              إغلاق
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={showGroupsPicker}
        onOpenChange={(open) => {
          setShowGroupsPicker(open);
          if (!open) {
            setGroupItemSearch('');
            setGroupKeyboardVisible(true);
            requestAnimationFrame(() => barcodeRef.current?.focus());
          }
        }}
      >
        <DialogContent className="h-[90vh] w-[98vw] max-w-7xl overflow-hidden p-0">
          <DialogHeader className="sr-only">
            <DialogTitle>{t?.itemGroupsTitle ?? 'مجموعات الأصناف'}</DialogTitle>
            <DialogDescription>{t?.selectItemDesc ?? 'اختر مجموعة وابحث عن الصنف ثم اضغط لإضافته للفاتورة.'}</DialogDescription>
          </DialogHeader>
          <div className="grid h-full min-h-0 grid-cols-1 md:grid-cols-[260px_1fr]">
            <aside className="border-b p-3 md:border-b-0 md:border-e">
              <div className="mb-2 text-sm font-semibold">{t?.itemGroupsTitle ?? 'مجموعات الأصناف'}</div>
              <div className="overflow-auto md:max-h-[calc(90vh-6rem)]">
                <div className="flex flex-col gap-2">
                  {posGroups.map((group, groupIndex) => (
                    <Button
                      key={`${String(group.id)}-${groupIndex}`}
                      type="button"
                      variant={activeGroupId === group.id ? 'default' : 'outline'}
                      className="w-full justify-start"
                      onClick={() => setActiveGroupId(group.id)}
                    >
                      {group.name}
                    </Button>
                  ))}
                </div>
              </div>
            </aside>

            <section className="flex min-h-0 flex-col">
              <div className="border-b p-3">
                <div className="mb-2 text-sm font-semibold">{t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}</div>
                <Input
                  value={groupItemSearch}
                  onChange={(e) => setGroupItemSearch(e.target.value)}
                  placeholder={t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}
                  lang={groupKeyboardLanguage}
                  dir={groupKeyboardLanguage === 'en' ? 'ltr' : 'rtl'}
                  autoFocus
                  className="h-11"
                />

                <div className="mt-2 space-y-2">
                  <div className="flex flex-wrap items-center gap-2">
                    {supportedKeyboardLanguages.map((language) => (
                      <Button
                        key={language.code}
                        type="button"
                        variant={groupKeyboardLanguage === language.code ? 'default' : 'outline'}
                        className="h-9 rounded-full px-4"
                        onClick={() => setGroupKeyboardLanguage(language.code)}
                      >
                        {language.label}
                      </Button>
                    ))}
                    <Button
                      type="button"
                      variant="outline"
                      className="h-9 rounded-full px-4"
                      onClick={() => setGroupKeyboardVisible((prev) => !prev)}
                    >
                      {groupKeyboardVisible ? (t?.hideKeyboard ?? 'إخفاء لوحة المفاتيح') : (t?.showKeyboard ?? 'إظهار لوحة المفاتيح')}
                    </Button>
                  </div>

                  {groupKeyboardVisible && (
                    <div className="space-y-1.5 rounded-lg border bg-muted/20 p-2">
                      {touchKeyboardRows.map((row, rowIndex) => (
                        <div
                          key={`touch-row-${rowIndex}`}
                          className="grid gap-0"
                          style={{ gridTemplateColumns: `repeat(${row.length}, minmax(0, 1fr))` }}
                          dir="ltr"
                        >
                          {row.map((key, keyIndex) => (
                            <Button
                              key={`touch-key-${rowIndex}-${key}`}
                              type="button"
                              variant="outline"
                              className={`h-10 min-w-0 rounded-none px-1 text-sm ${
                                keyIndex === 0 ? 'rounded-s-md' : ''
                              } ${keyIndex === row.length - 1 ? 'rounded-e-md' : 'border-e-0'}`}
                              onClick={() => appendTouchKey(key)}
                            >
                              {key}
                            </Button>
                          ))}
                        </div>
                      ))}
                      <div className="grid grid-cols-[1fr_1.4fr_1fr] gap-0" dir="ltr">
                        <Button
                          type="button"
                          variant="outline"
                          className="h-10 rounded-none rounded-s-md border-e-0"
                          onClick={() => setGroupItemSearch((prev) => prev.slice(0, -1))}
                        >
                          {t?.backspace ?? 'حذف'}
                        </Button>
                        <Button
                          type="button"
                          variant="outline"
                          className="h-10 rounded-none border-e-0"
                          onClick={() => appendTouchKey(' ')}
                        >
                          {t?.space ?? 'مسافة'}
                        </Button>
                        <Button
                          type="button"
                          variant="outline"
                          className="h-10 rounded-none rounded-e-md"
                          onClick={() => setGroupItemSearch('')}
                        >
                          {t?.clear ?? 'مسح'}
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div className="min-h-0 flex-1 overflow-auto p-3">
                <div className="mb-2 text-sm font-semibold">{t?.groupItemsTitle ?? 'أصناف المجموعة'}</div>
                {filteredGroupMaterials.length === 0 ? (
                  <div className="rounded-md border py-10 text-center text-sm text-muted-foreground">
                    {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-4">
                    {filteredGroupMaterials.map((material, materialIndex) => {
                      const pricing = getMaterialUnitPricing(material);
                      const availableStock = (availableLocationsByMaterial.get(material.id) || []).reduce(
                        (sum, location) => sum + Number(location.quantity || 0),
                        0
                      );
                      const infoBadges = [
                        pricing.primaryUnitLabel && pricing.primaryUnitLabel !== '-' ? pricing.primaryUnitLabel : '',
                        pricing.secondaryUnitLabel && pricing.secondaryUnitLabel !== pricing.primaryUnitLabel && pricing.secondaryUnitLabel !== '-'
                          ? pricing.secondaryUnitLabel
                          : '',
                        isMaterialWeighed(material) ? (t?.weightLabel ?? 'وزني') : '',
                        isMaterialSized(material) ? (t?.volumeLabel ?? 'حجمي') : '',
                        isTrackedMaterial(material) ? 'Serial/RFID' : '',
                      ].filter(Boolean);

                      return (
                        <button
                          key={`${String(material.id)}-${materialIndex}`}
                          type="button"
                          className="min-h-[200px] rounded-md border p-3 text-start transition hover:bg-muted/50"
                          onClick={() => {
                            handleAddMaterial(material);
                            setShowGroupsPicker(false);
                            setGroupItemSearch('');
                          }}
                        >
                          <div className="mb-2 aspect-square w-full overflow-hidden rounded-md bg-muted">
                            {material.imageUrl ? (
                              <img src={material.imageUrl} alt={material.name} className="h-full w-full object-cover" loading="lazy" />
                            ) : (
                              <div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
                                {material.name?.slice(0, 2) || '--'}
                              </div>
                            )}
                          </div>
                          <div className="space-y-1">
                            <div className="line-clamp-2 text-sm font-semibold">{material.name}</div>
                            <div className="font-mono text-[11px] text-muted-foreground">{material.itemNumber || material.id}</div>
                          </div>
                          <div className="mt-3 flex flex-wrap gap-1">
                            {infoBadges.slice(0, 3).map((badge) => (
                              <span key={`${String(material.id)}-${badge}`} className="rounded-full bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">
                                {badge}
                              </span>
                            ))}
                            {availableStock > 0 && (
                              <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] text-emerald-700">
                                {(t?.stockLabel ?? 'المخزون')}: {Number.isInteger(availableStock) ? availableStock : availableStock.toFixed(2)}
                              </span>
                            )}
                          </div>
                          <div className="mt-3 text-sm font-bold">
                            {formatCurrency(pricing.primaryPrice, currencySymbol)}
                          </div>
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
            </section>
          </div>
        </DialogContent>
      </Dialog>

      {/* ─── نافذة أصناف الميزان ─── */}
      <Dialog open={showWeighedItemsDialog} onOpenChange={(open) => { setShowWeighedItemsDialog(open); if (!open) { setWeighedSearch(''); setWeighedGroupFilter('__all__'); } }}>
        <DialogContent className="max-h-[90vh] flex flex-col w-[96vw] max-w-5xl">
          <DialogHeader>
            <DialogTitle>أصناف الميزان</DialogTitle>
            <DialogDescription>الأصناف التي تُباع بالوزن — اضغط على الصنف لإضافته للفاتورة.</DialogDescription>
          </DialogHeader>
          <div className="flex flex-wrap items-center gap-2 pb-2">
            <Input
              placeholder="ابحث عن الصنف..."
              value={weighedSearch}
              onChange={(e) => setWeighedSearch(e.target.value)}
              className="h-9 max-w-xs"
              autoFocus
            />
            <Select value={weighedGroupFilter} onValueChange={setWeighedGroupFilter}>
              <SelectTrigger className="h-9 w-44">
                <SelectValue placeholder="كل المجموعات" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__all__">كل المجموعات</SelectItem>
                {itemGroups.map((g) => (
                  <SelectItem key={g.id} value={g.id}>{g.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex-1 overflow-y-auto">
            {(() => {
              const q = weighedSearch.trim().toLowerCase();
              const filtered = allMaterials.filter((m) => {
                if (!m.isWeighed) return false;
                if (weighedGroupFilter !== '__all__' && m.groupId !== weighedGroupFilter) return false;
                if (q && !m.name?.toLowerCase().includes(q) && !m.barcode?.toLowerCase().includes(q) && !m.itemNumber?.toLowerCase().includes(q)) return false;
                return true;
              });
              if (filtered.length === 0) return (
                <div className="flex h-32 items-center justify-center text-muted-foreground text-sm">لا توجد أصناف مطابقة</div>
              );
              return (
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
                  {filtered.map((material) => {
                    const unitPrice = customerPriceByMaterialId.get(material.id) ?? material.salePrice ?? 0;
                    return (
                      <button
                        key={material.id}
                        type="button"
                        className="flex flex-col rounded-lg border bg-card p-2 text-start shadow-sm transition hover:border-primary hover:bg-muted/40 active:scale-95"
                        onClick={() => {
                          handleAddMaterial(material);
                          setShowWeighedItemsDialog(false);
                          setWeighedSearch('');
                          setWeighedGroupFilter('__all__');
                          requestAnimationFrame(() => barcodeRef.current?.focus());
                        }}
                      >
                        <div className="mb-2 aspect-square w-full overflow-hidden rounded-md bg-muted">
                          {material.imageUrl ? (
                            <img src={material.imageUrl} alt={material.name} className="h-full w-full object-cover" loading="lazy" />
                          ) : (
                            <div className="flex h-full w-full items-center justify-center text-base text-muted-foreground font-semibold">
                              {material.name?.slice(0, 2) || '--'}
                            </div>
                          )}
                        </div>
                        <div className="line-clamp-2 text-xs font-semibold leading-tight">{material.name}</div>
                        <div className="mt-1 font-mono text-xs font-bold text-primary">{formatCurrency(unitPrice, currencySymbol)}</div>
                      </button>
                    );
                  })}
                </div>
              );
            })()}
          </div>
          <DialogFooter className="pt-2">
            <Button type="button" variant="outline" onClick={() => setShowWeighedItemsDialog(false)}>
              إغلاق
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Button
        type="button"
        variant={isFullscreenMode ? 'default' : 'outline'}
        size="sm"
        className="fixed bottom-4 start-4 z-[70] h-10 rounded-full px-3 shadow-lg"
        onClick={toggleFullscreenMode}
        title={isFullscreenMode ? 'خروج من ملء الشاشة' : 'تفعيل ملء الشاشة'}
      >
        {isFullscreenMode ? <Minimize2 className="me-1 h-4 w-4" /> : <Maximize2 className="me-1 h-4 w-4" />}
        {isFullscreenMode ? 'خروج' : 'ملء الشاشة'}
      </Button>

      <Dialog
        open={showItemPicker}
        onOpenChange={(open) => {
          setShowItemPicker(open);
          if (!open) {
            setItemSearch('');
            setItemSearchDraft('');
          }
        }}
      >
        <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-7xl">
          <DialogHeader>
            <DialogTitle>{t?.selectItemTitle ?? 'اختيار صنف'}</DialogTitle>
            <DialogDescription>{t?.selectItemDesc ?? 'ابحث عن الصنف ثم اضغط لإضافته للفاتورة.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="rounded-md border border-orange-200 bg-orange-100 p-2">
              <div className="flex items-center gap-2">
                <Input
                  placeholder={t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}
                  value={itemSearchDraft}
                  onChange={(e) => setItemSearchDraft(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      setItemSearch(itemSearchDraft.trim());
                    }
                  }}
                  autoFocus
                  className="bg-background"
                />
                <Button
                  type="button"
                  onClick={() => setItemSearch(itemSearchDraft.trim())}
                  className="shrink-0"
                >
                  {t?.search ?? 'بحث'}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    setItemSearchDraft('');
                    setItemSearch('');
                  }}
                  className="shrink-0"
                >
                  {t?.clearSearch ?? 'مسح البحث'}
                </Button>
              </div>
            </div>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t?.item ?? 'الصنف'}</TableHead>
                    <TableHead>{t?.itemNumberLabel ?? 'رقم الصنف'}</TableHead>
                    <TableHead>{t?.itemSymbolNameLabel ?? 'اسم رمز الصنف'}</TableHead>
                    <TableHead>{t?.barcodeLabel ?? 'الباركود'}</TableHead>
                    <TableHead>{t?.additionalDetailsLabel ?? 'تفاصيل اضافيه'}</TableHead>
                    <TableHead className="text-right">{t?.price ?? 'السعر'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                    {visibleItemPickerMaterials.map((m, filteredMaterialIndex) => {
                      const unitPrice = customerPriceByMaterialId.get(m.id) ?? m.salePrice ?? 0;
                      return (
                        <TableRow key={`${String(m.id)}-${filteredMaterialIndex}`} className="cursor-pointer" onClick={() => {
                          handleAddMaterial(m);
                          setShowItemPicker(false);
                          setItemSearch('');
                          setItemSearchDraft('');
                          requestAnimationFrame(() => barcodeRef.current?.focus());
                        }}>
                          <TableCell className="font-medium">{m.name}</TableCell>
                          <TableCell className="font-mono text-xs">{m.itemNumber || m.id}</TableCell>
                          <TableCell className="text-xs text-muted-foreground max-w-[180px] truncate">{(m.itemSymbolName || '').trim() || '-'}</TableCell>
                          <TableCell className="font-mono text-xs">{m.barcode || '-'}</TableCell>
                          <TableCell className="text-xs text-muted-foreground max-w-[320px] truncate">{(m.additionalDetails || '').trim() || '-'}</TableCell>
                          <TableCell className="text-right font-mono">{formatCurrency(unitPrice, currencySymbol)}</TableCell>
                        </TableRow>
                      );
                    })}
                  {filteredMaterials.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={6} className="text-center text-muted-foreground h-24">
                        {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
              {!itemSearch.trim() && filteredMaterials.length > visibleItemPickerMaterials.length && (
                <div className="border-t bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
                  {`تم عرض أول ${visibleItemPickerMaterials.length} صنف من أصل ${filteredMaterials.length}. اكتب في البحث لعرض النتائج المطلوبة بسرعة.`}
                </div>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setShowItemPicker(false);
                setItemSearch('');
                setItemSearchDraft('');
              }}
            >
              {t?.cancel ?? 'إلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showSuspended} onOpenChange={setShowSuspended}>
        <DialogContent className="max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{t?.suspendedInvoicesTitle ?? 'الفواتير المعلقة'}</DialogTitle>
            <DialogDescription>{t?.suspendedInvoicesDesc ?? 'اختر فاتورة لاستعادتها.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            {suspendedInvoices.length === 0 && (
              <div className="text-center text-muted-foreground py-8">
                {t?.noSuspendedInvoices ?? 'لا توجد فواتير معلقة.'}
              </div>
            )}
            {suspendedInvoices.map((inv, suspendedIndex) => {
              const customer = customers.find((c) => c.id === inv.customerId);
              return (
                <div key={`${String(inv.id)}-${suspendedIndex}`} className="rounded-md border p-3 flex items-center justify-between">
                  <div>
                    <div className="font-medium">{getDisplayCustomerName((inv as any)?.customerName, customer?.name)}</div>
                    {(inv as any)?.tableName && (
                      <div className="mt-1 inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-[11px] text-amber-800">
                        {(inv as any)?.areaName ? `${(inv as any).areaName} • ` : ''}{(inv as any).tableName}
                      </div>
                    )}
                    <div className="text-xs text-muted-foreground">{formatDateTimeStable(inv.createdAt)}</div>
                  </div>
                  <div className="flex gap-2">
                    <Button type="button" size="sm" onClick={() => handleResume(inv.id)}>
                      {t?.resume ?? 'استرجاع'}
                    </Button>
                    <Button type="button" size="sm" variant="outline" onClick={() => setSuspendedInvoices(prev => prev.filter(x => x.id !== inv.id))}>
                      {t?.delete ?? 'حذف'}
                    </Button>
                  </div>
                </div>
              );
            })}
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowSuspended(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showInvoices} onOpenChange={setShowInvoices}>
        <DialogContent className="h-[92vh] w-[96vw] max-w-6xl overflow-y-auto p-4 sm:p-6">
          <DialogHeader>
            <DialogTitle>{t?.posInvoices ?? 'فواتير نقطة البيع'}</DialogTitle>
            <DialogDescription>{t?.posInvoicesDesc ?? 'عرض آخر الفواتير المحفوظة من نقطة البيع.'}</DialogDescription>
          </DialogHeader>
          <div className="flex items-center gap-2 mb-3">
            <label className="text-sm text-muted-foreground">{t?.dateFilterLabel ?? 'التاريخ'}</label>
            <Input
              type="date"
              value={invoiceDateFilter}
              onChange={(e) => setInvoiceDateFilter(e.target.value)}
              className="h-9 w-[180px]"
            />
          </div>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.invoiceNumber ?? 'رقم الفاتورة'}</TableHead>
                  <TableHead>{t?.customer ?? 'الزبون'}</TableHead>
                  <TableHead>{t?.date ?? 'التاريخ'}</TableHead>
                  <TableHead>{t?.status ?? 'الحالة'}</TableHead>
                  <TableHead className="text-right">{t?.total ?? 'الإجمالي'}</TableHead>
                  <TableHead className="text-center">{t?.actionsLabel ?? 'العمليات'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {invoices.filter((inv) => toLocalDateKey(inv.date) === invoiceDateFilter).length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center text-muted-foreground h-24">
                      {t?.noInvoices ?? 'لا توجد فواتير.'}
                    </TableCell>
                  </TableRow>
                ) : (
                  invoices
                    .filter((inv) => toLocalDateKey(inv.date) === invoiceDateFilter)
                    .map((inv, invoiceIndex) => {
                    const customer = customers.find(c => c.id === inv.customerId);
                    const total = typeof inv.grandTotal === 'number'
                      ? inv.grandTotal
                      : (inv.items || []).reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);
                    return (
                      <TableRow key={`${String(inv.id)}-${invoiceIndex}`}>
                        <TableCell className="font-mono">{inv.invoiceNumber || inv.id}</TableCell>
                        <TableCell>{getDisplayCustomerName((inv as any)?.customerName, customer?.name)}</TableCell>
                        <TableCell>{formatDateTimeStable(inv.date)}</TableCell>
                        <TableCell>{inv.status ?? t?.activeStatus ?? 'نشطة'}</TableCell>
                        <TableCell className="text-right font-mono">{formatCurrency(total, currencySymbol)}</TableCell>
                        <TableCell className="text-center">
                          <Button
                            type="button"
                            size="sm"
                            variant="outline"
                            onClick={() => handlePrintSavedInvoice(inv)}
                          >
                            <Printer className="me-1 h-4 w-4" />
                            {t?.printInvoice ?? 'طباعة'}
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowInvoices(false)}>
              {t?.close ?? tGlobal?.cancel ?? 'إغلاق'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showAddBarcodeDialog} onOpenChange={setShowAddBarcodeDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t?.barcodeNotFound ?? 'باركود غير موجود'}</DialogTitle>
            <DialogDescription>{t?.barcodeAddPrompt ?? 'لم يتم العثور على الصنف. هل تريد إضافته؟'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">{t?.barcodeLabel ?? 'الباركود'}</label>
              <Input value={notFoundBarcode} readOnly className="bg-muted" />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowAddBarcodeDialog(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              onClick={async () => {
                const barcodeValue = notFoundBarcode.trim();
                setAddMaterialInitialValues(barcodeValue ? { barcode: barcodeValue } : undefined);
                setShowAddBarcodeDialog(false);
                setShowAddMaterialDialog(true);
              }}
            >
              {t?.addItem ?? 'إضافة الصنف'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Payment Method Modal */}
      <PaymentMethodModal
        isOpen={paymentModalOpen}
        onOpenChange={(open) => {
          setPaymentModalOpen(open);
          if (!open) {
            setPendingFinalizeAction(null);
            shouldPrintAfterSaveRef.current = false;
          }
        }}
        invoiceTotal={totalAfterDiscount}
        customers={customers}
        banks={banks}
        defaultVisaBankAccountId={String(posPaymentMethods?.defaultVisaBankAccountId || '').trim()}
        currencySymbol={currencySymbol}
        onConfirm={(paymentBreakdown) => {
          const normalizedPaymentBreakdown: PosPaymentBreakdown = paymentBreakdown
            .filter(
              (payment): payment is PaymentBreakdown & { method: 'cash' | 'visa' | 'receivables' | 'coupon' } =>
                payment.method === 'cash' || payment.method === 'visa' || payment.method === 'receivables' || payment.method === 'coupon'
            )
            .map((payment) => ({
              method: payment.method,
              amount: Number(payment.amount || 0),
              customerName: payment.customerName,
              bankAccountId: payment.bankAccountId,
              couponCode: payment.couponCode,
            }));

          const normalizedCustomerId = String(form.getValues('customerId') || '').trim();
          const breakdownTotalPaid = normalizedPaymentBreakdown.reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
          const breakdownAmountDue = totalAfterDiscount - breakdownTotalPaid;
          const hasReceivablesPayment = normalizedPaymentBreakdown.some(
            (payment) => payment.method === 'receivables' && Number(payment.amount || 0) > 0
          );

          if (hasReceivablesPayment && normalizedCustomerId.length === 0) {
            promptSelectCustomerForReceivables();
            toast({
              title: t?.validationError ?? 'خطأ في التحقق',
              description: t?.receivablesCustomerRequired ?? 'عند اختيار الذمم يجب تحديد الزبون أولاً.',
              variant: 'destructive',
            });
            return false;
          }

          const isCashCustomer = normalizedCustomerId.length === 0;
          if (isCashCustomer && Math.abs(breakdownAmountDue) > 0.0001) {
            form.setError('customerId', {
              type: 'manual',
              message: t?.cashCustomerRequiresPaid ?? 'الزبون النقدي يجب أن يكون المتبقي 0.00',
            });
            toast({
              title: t?.validationError ?? 'خطأ في التحقق',
              description: t?.cashCustomerRequiresPaid ?? 'الزبون النقدي يجب أن يكون المتبقي 0.00',
              variant: 'destructive',
            });
            return false;
          }

          applyPayments(normalizedPaymentBreakdown);

          const action = pendingFinalizeAction;
          if (action) {
            shouldPrintAfterSaveRef.current = action === 'savePrint';
            setPendingFinalizeAction(null);
            setPaymentModalOpen(false);
            setTimeout(() => {
              form.handleSubmit(onSubmit)();
            }, 0);
          }

          return true;
        }}
        translations={{
          selectPaymentMethod: t?.PaymentMethods?.selectPaymentMethod ?? 'اختر طريقة الدفع',
          paymentMethods: t?.PaymentMethods?.paymentMethods ?? 'طرق الدفع',
          cash: t?.PaymentMethods?.cash ?? 'نقدي',
          visa: t?.PaymentMethods?.visa ?? 'فيزا',
          receivables: t?.PaymentMethods?.receivables ?? 'ذمم',
          coupon: t?.PaymentMethods?.coupon ?? 'كوبون',
          couponCode: t?.PaymentMethods?.couponCode ?? 'كود الكوبون',
          totalAmount: t?.PaymentMethods?.totalAmount ?? 'إجمالي الفاتورة',
          paymentBreakdown: t?.PaymentMethods?.paymentBreakdown ?? 'تفاصيل الدفع',
          remainingBalance: t?.PaymentMethods?.remainingBalance ?? 'الرصيد المتبقي',
          addPaymentMethod: t?.PaymentMethods?.addPaymentMethod ?? 'إضافة طريقة دفع',
          confirm: t?.PaymentMethods?.confirm ?? 'تأكيد',
          cancel: t?.PaymentMethods?.cancel ?? 'إلغاء',
          amount: t?.PaymentMethods?.amount ?? 'المبلغ',
          remove: t?.PaymentMethods?.remove ?? 'حذف',
          errorExceeds: t?.PaymentMethods?.errorExceeds ?? 'إجمالي الدفع لا يمكن أن يتجاوز المبلغ الإجمالي',
          errorMinimum: t?.PaymentMethods?.errorMinimum ?? 'يجب إضافة طريقة دفع واحدة على الأقل',
          errorVisaBankRequired: t?.PaymentMethods?.errorVisaBankRequired ?? 'يجب اختيار بنك لمدفوعات البطاقة',
        }}
      />
    </div>
  );
}