'use client';

import { useState, useTransition, useMemo, useEffect, useRef, useId, type MouseEvent as ReactMouseEvent } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { PlusCircle, Loader2, MoreHorizontal, Pencil, Trash2, MapPin, ArrowLeftRight, Eye, RotateCcw, Upload, ChevronUp, ChevronDown, ChevronsUpDown, Filter } from "lucide-react";
import { type ProductionItem, type Customer, type CustomerCategory, type ItemGroup, type RealEstateProject, type SalesRep, type Supplier, type Warehouse, type StockLocationBalance, type ManagedUnit, type PrintingSettings, type ChartOfAccount, type InternalTransferDocument, type InventoryMovement } from "@/lib/types";
import AccountCodeSelector, { type AccountCodeOption } from "@/components/admin/account-code-selector";
import { handleAddListItem, handleUpdateListItem, handleDeleteListItem, handleCreateInternalTransfer, handleAcquireTransferLock, handleReleaseTransferLock, handleEnsureManagedUnit, handleGetManagedUnits, handleGetProductShapeDefinitions, handleGetPrinterConfiguration, handleQuickAddPrintSection, handleQuickAddPrinterConfig, handleSuggestMaterialAlternatives, handleToggleMaterialStoreEnabled } from "@/lib/actions";
import { handleBulkAddProductShapes } from "@/lib/actions";
import { handleAddItemGroup } from "@/lib/actions";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { formatCurrency } from "@/lib/currency-formatter";
import EmployeeAddDialog from "@/components/admin/employee-add-dialog";
import CustomerCategoryDialog from "@/components/admin/customer-category-dialog";
import MaterialImportDialog from "@/components/admin/material-import-dialog";

const listItemSchema = z.object({
    name: z.string().min(2, "Name must be at least 2 characters."),
});

const expenseItemSchema = z.object({
    name: z.string().min(2, "Name must be at least 2 characters."),
    realEstateProjectId: z.string().optional().default(''),
    realEstateUnitId: z.string().optional().default(''),
    realEstateCostType: z.enum(['general', 'direct-unit', 'shared-project']).optional().default('general'),
    realEstateAllocationMethod: z.enum(['area', 'sale-value', 'manual-share']).optional().default('area'),
});

const materialItemSchema = z.object({
    itemNumber: z.string().optional(),
    name: z.string().min(2, "Name must be at least 2 characters."),
    itemCategory: z.enum(['inventory', 'service', 'non_stock', 'bundle']).optional().default('inventory'),
    reorderMinimumQty: z.preprocess(
        (val) => (val === '' || val === null || val === undefined ? undefined : val),
        z.coerce.number().min(0).optional()
    ),
    reorderUnit: z.string().optional(),
    itemSymbolName: z.string().optional(),
    globalReferenceNumber: z.string().optional(),
    barcode: z.string().optional(),
    secondaryBarcode: z.string().optional(),
    additionalBarcodes: z.array(z.string().min(1)).optional(),
    groupId: z.string().optional(),
    additionalDetails: z.string().optional(),
    imageUrl: z.string().optional(),
    primaryUnit: z.string().optional(),
    primaryUnitQuantity: z.coerce.number().min(0).optional(),
    secondaryUnit: z.string().optional(),
    secondaryUnitQuantity: z.coerce.number().min(0).optional(),
    secondaryUnitPrice: z.coerce.number().min(0).optional(),
    secondaryUnits: z.array(z.object({
        unit: z.string().optional(),
        barcode: z.string().optional(),
        quantity: z.preprocess(
            (val) => (val === '' || val === null || val === undefined ? undefined : val),
            z.coerce.number().optional().refine(val => val === undefined || val === null || val > 1, { message: 'يجب أن تكون كمية الوحدة الفرعية أكبر من 1' })
        ),
        price: z.coerce.number().min(0).optional(),
    })).optional(),
    isManufactured: z.coerce.boolean().optional(),
    productionOutputQuantity: z.coerce.number().min(0.0001).optional(),
    productionFormula: z.array(z.object({
        materialId: z.string().min(1),
        quantity: z.coerce.number().min(0.0001),
        unit: z.string().optional(),
        notes: z.string().optional(),
        wastePercent: z.coerce.number().min(0).max(100).optional(),
    })).optional(),
    isDisassemblable: z.coerce.boolean().optional().default(false),
    disassemblyTemplate: z.array(z.object({
        partItemId: z.string().optional(),
        quantity: z.coerce.number().min(0.0001).optional(),
        expectedSalePrice: z.coerce.number().min(0).optional(),
        notes: z.string().optional(),
    })).optional(),
    shelfLifeYears: z.coerce.number().min(0).optional(),
    shelfLifeMonths: z.coerce.number().min(0).optional(),
    shelfLifeDays: z.coerce.number().min(0).optional(),
    storeSectionId: z.string().optional(),
    storeBranchId: z.string().optional(),
    storeEnabled: z.boolean().optional(),
    printSectionId: z.string().optional(),
    excludeFromPrepTicket: z.coerce.boolean().optional().default(false),
    printLabelOverride: z.string().optional(),
    realEstateProjectId: z.string().optional().default(''),
    realEstateUnitId: z.string().optional().default(''),
    realEstateCostType: z.enum(['general', 'direct-unit', 'shared-project']).optional().default('general'),
    realEstateAllocationMethod: z.enum(['area', 'sale-value', 'manual-share']).optional().default('area'),
    alternativeItemIds: z.array(z.string()).optional(),
    isWeighed: z.coerce.boolean().optional(),
    isSized: z.coerce.boolean().optional(),
    purchasePrice: z.coerce.number().min(0).optional(),
    salePrice: z.preprocess(
        (value) => {
            if (value === '' || value === null || value === undefined) return undefined;
            const parsed = Number(value);
            return Number.isFinite(parsed) ? parsed : undefined;
        },
        z.number().min(0).optional(),
    ),
    allowDescriptionEdit: z.coerce.boolean().optional(),
    hasSerialNumber: z.coerce.boolean().optional().default(false),
    hasRfid: z.coerce.boolean().optional().default(false),
    enableCustomTax: z.coerce.boolean().optional().default(false),
    customTaxValue: z.coerce.number().min(0).max(100).optional(),
    enableProfitMargin: z.coerce.boolean().optional().default(false),
    profitMargin: z.coerce.number().min(0).max(1000).optional(),
    usesDefaultTax: z.coerce.boolean().optional().default(true),
    taxRate: z.coerce.number().min(0).max(100).optional(),
    usesProductShapes: z.coerce.boolean().optional().default(false),
    productShapeType: z.string().optional(),
    productShapes: z.array(z.object({
        id: z.string().optional(),
        name: z.string().optional(),
        salePrice: z.coerce.number().min(0),
        costPrice: z.coerce.number().min(0).optional(),
        type: z.string().optional(),
        isActive: z.coerce.boolean().optional(),
    })).optional(),
    revenueAccountCode: z.string().optional(),
    inventoryAccountCode: z.string().optional(),
    cogsAccountCode: z.string().optional(),
    purchaseAccountCode: z.string().optional(),
}).refine((data) => {
    const primaryQty = Number.isFinite(data.primaryUnitQuantity as number) ? (data.primaryUnitQuantity as number) : undefined;
    const candidateSecondaryUnits = (Array.isArray(data.secondaryUnits) && data.secondaryUnits.length > 0)
        ? data.secondaryUnits
        : [{ unit: data.secondaryUnit, quantity: data.secondaryUnitQuantity }];

    for (const entry of candidateSecondaryUnits) {
        const unit = String(entry?.unit || '').trim();
        if (!unit) continue;
        if (data.primaryUnit && unit === data.primaryUnit) return false;

        const secondaryQty = Number.isFinite(entry?.quantity as number) ? (entry?.quantity as number) : undefined;
        if (typeof primaryQty === 'number' && primaryQty > 0 && typeof secondaryQty === 'number' && secondaryQty > 0) {
            if (secondaryQty <= primaryQty) return false;
        }
    }

    return true;
}, { message: 'Invalid unit quantities or duplicate units.' }).superRefine((data, ctx) => {
    const salePrice = typeof data.salePrice === 'number' && Number.isFinite(data.salePrice)
        ? data.salePrice
        : undefined;
    const purchasePrice = typeof data.purchasePrice === 'number' && Number.isFinite(data.purchasePrice)
        ? data.purchasePrice
        : undefined;
    const canAutoCompute = !!data.enableProfitMargin;

    const normalizeCode = (value: unknown) => String(value || '').trim();
    const seenCodes = new Set<string>();
    const addLocalCode = (code: string, path: (string | number)[]) => {
        if (!code) return;
        if (seenCodes.has(code)) {
            ctx.addIssue({
                code: z.ZodIssueCode.custom,
                message: 'الباركود مكرر داخل نفس الصنف. يجب أن يكون كل باركود فريدًا.',
                path,
            });
            return;
        }
        seenCodes.add(code);
    };

    addLocalCode(normalizeCode(data.barcode), ['barcode']);
    addLocalCode(normalizeCode(data.secondaryBarcode), ['secondaryBarcode']);

    (Array.isArray(data.additionalBarcodes) ? data.additionalBarcodes : []).forEach((code, index) => {
        addLocalCode(normalizeCode(code), ['additionalBarcodes', index]);
    });

    (Array.isArray(data.secondaryUnits) ? data.secondaryUnits : []).forEach((entry, index) => {
        addLocalCode(normalizeCode(entry?.barcode), ['secondaryUnits', index, 'barcode']);
    });
});

const customerItemSchema = z.object({
    customerNumber: z.string().min(1, "Customer number is required."),
    name: z.string().min(2, "Name must be at least 2 characters."),
    category: z.string().min(1, "Category is required."),
    phone: z.string().optional(),
    creditLimit: z.coerce.number().min(0).optional(),
    address: z.string().optional(),
    allowedDiscount: z.coerce.number().min(0).max(100).optional(),
    salesRepId: z.string().optional(),
});

const supplierItemSchema = z.object({
    supplierNumber: z.string().min(1, "Supplier number is required.").optional(),
    name: z.string().min(2, "Name must be at least 2 characters."),
    phone: z.string().optional(),
    address: z.string().optional(),
    paymentTerms: z.coerce.number().min(0).optional(),
    taxNumber: z.string().optional(),
});

const salesRepItemSchema = z.object({
    name: z.string().min(2, "Name must be at least 2 characters."),
    phone: z.string().optional(),
    region: z.string().optional(),
    commissionRate: z.coerce.number().min(0).max(100).optional(),
});

const unitItemSchema = z.object({
    unitNumber: z.string().optional(),
    description: z.string().min(1, 'Unit description is required.'),
    unitType: z.enum(['primary', 'secondary']).optional().default('primary'),
    shortCode: z.string().optional(),
    notes: z.string().optional(),
});

type ListManagedUnit = ManagedUnit & { name: string };
type Item = ProductionItem | (Customer & { id: string }) | Supplier | SalesRep | ListManagedUnit | { id: string; name: string };
type ItemType = 'material' | 'expense' | 'product-shape' | 'customer' | 'supplier' | 'sales-rep' | 'unit';
type MaterialFilterMatchMode = 'contains' | 'startsWith' | 'endsWith';

interface ListManagerProps {
  items: Item[];
  title: string;
  description: string;
  itemType: ItemType;
  categories?: CustomerCategory[];
    itemGroups?: ItemGroup[];
    salesReps?: SalesRep[];
  t: any;
  tGlobal: any;
  currencySymbol?: string;
    warehouses?: Warehouse[];
    warehousesEnabled?: boolean;
    storeModuleEnabled?: boolean;
    stockLocationsByMaterial?: Record<string, StockLocationBalance[]>;
    internalTransferDocuments?: InternalTransferDocument[];
    inventoryMovements?: InventoryMovement[];
    unitDefinitions?: ManagedUnit[];
    productShapeDefinitions?: Array<{ id: string; name: string }>;
    realEstateProjects?: RealEstateProject[];
    chartOfAccounts?: ChartOfAccount[];
    serverPagination?: {
        enabled: boolean;
        page: number;
        pageSize: number;
        totalItems: number;
        totalPages: number;
        search?: string;
        hasAlternativesOnly?: boolean;
        availableOnly?: boolean;
        materialFilters?: Partial<Record<'itemNumber' | 'name' | 'itemSymbolName' | 'globalReferenceNumber' | 'barcode' | 'secondaryBarcode' | 'additionalDetails' | 'salePrice' | 'location', string>>;
        materialFilterModes?: Partial<Record<'itemNumber' | 'name' | 'itemSymbolName' | 'globalReferenceNumber' | 'barcode' | 'secondaryBarcode' | 'additionalDetails' | 'salePrice' | 'location', MaterialFilterMatchMode>>;
        sortKey?: string;
        sortDir?: 'asc' | 'desc';
        withBarcodeCount?: number;
        totalSaleValue?: number;
    };
}

function OverflowTooltipText({ value, className }: { value: string; className?: string }) {
    const textRef = useRef<HTMLSpanElement | null>(null);
    const [isOverflowed, setIsOverflowed] = useState(false);

    useEffect(() => {
        const element = textRef.current;
        if (!element) return;

        const checkOverflow = () => {
            const hasOverflow = element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight;
            setIsOverflowed(hasOverflow);
        };

        checkOverflow();

        if (typeof ResizeObserver !== 'undefined') {
            const observer = new ResizeObserver(checkOverflow);
            observer.observe(element);
            return () => observer.disconnect();
        }

        if (typeof window !== 'undefined') {
            window.addEventListener('resize', checkOverflow);
            return () => window.removeEventListener('resize', checkOverflow);
        }
    }, [value]);

    return (
        <span
            ref={textRef}
            className={className}
            title={isOverflowed ? value : undefined}
        >
            {value}
        </span>
    );
}

export function ItemDialog({ item, itemType, t, tGlobal, items, categories, itemGroups, salesReps, unitDefinitions, warehouses = [], productShapeDefinitions = [], realEstateProjects = [], chartOfAccounts = [], initialValues, onFinished, onCreated, focusSalePrice, currencySymbol = '$', asPage = false, active = true }: { item?: Item, itemType: ItemType, t: any, tGlobal: any, items: Item[], categories?: CustomerCategory[], itemGroups?: ItemGroup[], salesReps?: SalesRep[], unitDefinitions?: ManagedUnit[], warehouses?: Warehouse[], productShapeDefinitions?: Array<{ id: string; name: string }>, realEstateProjects?: RealEstateProject[], chartOfAccounts?: ChartOfAccount[], initialValues?: Partial<ProductionItem>, onFinished: () => void, onCreated?: (item: Item) => void, focusSalePrice?: boolean, currencySymbol?: string, asPage?: boolean, active?: boolean }) {
    const [isPending, startTransition] = useTransition();
    const dialogA11yId = useId().replace(/[:]/g, '');
    const dialogTitleId = `item-dialog-title-${dialogA11yId}`;
    const dialogDescriptionId = `item-dialog-description-${dialogA11yId}`;

    // Build chart of accounts options for selectors
    const allAccountOptions: AccountCodeOption[] = useMemo(
        () => (chartOfAccounts || [])
            .filter((acc) => acc.type === 'account')
            .map((acc) => ({ code: acc.code, label: `${acc.code} - ${acc.nameAr}` })),
        [chartOfAccounts]
    );
    const revenueAccountOptions = useMemo(
        () => allAccountOptions.filter((opt) => opt.code.startsWith('4')),
        [allAccountOptions]
    );
    const inventoryAccountOptions = useMemo(
        () => allAccountOptions.filter((opt) => opt.code.startsWith('1')),
        [allAccountOptions]
    );
    const cogsAccountOptions = useMemo(
        () => allAccountOptions.filter((opt) => opt.code.startsWith('5')),
        [allAccountOptions]
    );

    const formatManagedUnitLabel = (unit: ManagedUnit) => {
        const number = String(unit.unitNumber || '').trim();
        const description = String(unit.description || '').trim();
        const shortCode = String(unit.shortCode || '').trim();
        const baseLabel = number ? `${number} - ${description}` : description;
        return shortCode ? `${baseLabel} (${shortCode})` : baseLabel;
    };

    const sortManagedUnits = (units: ManagedUnit[]) => {
        return [...units].sort((a, b) => formatManagedUnitLabel(a).localeCompare(formatManagedUnitLabel(b)));
    };

    const [managedUnitOptions, setManagedUnitOptions] = useState<ManagedUnit[]>(sortManagedUnits(unitDefinitions || []));
    const primaryManagedUnitOptions = useMemo(
        () => managedUnitOptions.filter((unit) => String((unit as any).unitType || 'primary') !== 'secondary'),
        [managedUnitOptions],
    );

    const secondaryManagedUnitOptions = useMemo(
        () => managedUnitOptions.filter((unit) => String((unit as any).unitType || 'primary') === 'secondary'),
        [managedUnitOptions],
    );
    const [smartAlternativeSuggestions, setSmartAlternativeSuggestions] = useState<Array<{
        id: string;
        name: string;
        itemNumber?: string;
        itemSymbolName?: string;
        globalReferenceNumber?: string;
        additionalDetails?: string;
        score: number;
        reason: string;
    }>>([]);
    const [materialActiveTab, setMaterialActiveTab] = useState('general');
    const [suggestionPreviewItem, setSuggestionPreviewItem] = useState<ProductionItem | null>(null);
    const [smartSuggestionTried, setSmartSuggestionTried] = useState(false);
    const [manualAlternativeToAdd, setManualAlternativeToAdd] = useState('none');
    const [manualAlternativeQuery, setManualAlternativeQuery] = useState('');
    const [lowPriceWarningOpen, setLowPriceWarningOpen] = useState(false);
    const [pendingNormalizedValues, setPendingNormalizedValues] = useState<any | null>(null);
    const [lowPriceComparison, setLowPriceComparison] = useState<{
        salePrice: number;
        purchasePrice: number;
        isSecondary?: boolean;
        unitLabel?: string;
    } | null>(null);
    const { toast } = useToast();
    const isEditMode = !!item;
    const dialogTitleText = isEditMode ? (t.editDialogTitle || 'تعديل العنصر') : (t.addDialogTitle || 'إضافة عنصر جديد');
    const dialogDescriptionText = isEditMode ? (t.editDialogDescription || 'قم بتحديث اسم العنصر أدناه.') : (t.addDialogDescription || 'أدخل تفاصيل العنصر الجديد أدناه.');
    const addUnitOptionValue = '__add_new_managed_unit__';
    const managedUnitResolverRef = useRef<((value: string | null) => void) | null>(null);
    const managedUnitSubmitInFlightRef = useRef(false);
    const [managedUnitDialogOpen, setManagedUnitDialogOpen] = useState(false);
    const [managedUnitDescriptionDraft, setManagedUnitDescriptionDraft] = useState('');
    const [managedUnitTypeDraft, setManagedUnitTypeDraft] = useState<'primary' | 'secondary'>('primary');
    const [isManagedUnitSaving, setIsManagedUnitSaving] = useState(false);
    const [productShapeQuickAddOpen, setProductShapeQuickAddOpen] = useState(false);
    const [productShapeQuickAddName, setProductShapeQuickAddName] = useState('');
    const [isProductShapeQuickSaving, setIsProductShapeQuickSaving] = useState(false);
    const productShapeQuickInputRef = useRef<HTMLInputElement | null>(null);
    const addCategoryOptionValue = '__add_new_category__';
    const [categoryQuickAddOpen, setCategoryQuickAddOpen] = useState(false);
    const sortCategoryOptions = (entries: CustomerCategory[]) => {
        return [...entries].sort((left, right) => String(left.name || '').localeCompare(String(right.name || '')));
    };
    const [runtimeCategoryOptions, setRuntimeCategoryOptions] = useState<CustomerCategory[]>(sortCategoryOptions(categories || []));
    const addSalesRepOptionValue = '__add_new_sales_rep__';
    const [salesRepQuickAddOpen, setSalesRepQuickAddOpen] = useState(false);
    const sortSalesRepOptions = (entries: SalesRep[]) => {
        return [...entries].sort((left, right) => String(left.name || '').localeCompare(String(right.name || '')));
    };
    const [runtimeSalesRepOptions, setRuntimeSalesRepOptions] = useState<SalesRep[]>(sortSalesRepOptions(salesReps || []));
    const sortItemGroupOptions = (entries: ItemGroup[]) => {
        return [...entries].sort((a, b) => String(a.name || '').localeCompare(String(b.name || '')));
    };
    const [runtimeItemGroupOptions, setRuntimeItemGroupOptions] = useState<ItemGroup[]>(sortItemGroupOptions(itemGroups || []));
    const [storeSectionQuickName, setStoreSectionQuickName] = useState('');
    const [isStoreSectionSaving, setIsStoreSectionSaving] = useState(false);
    const shapeDefinitionOptions = useMemo(
        () => (Array.isArray(productShapeDefinitions)
            ? productShapeDefinitions
                .map((entry) => ({ id: String(entry.id || ''), name: String(entry.name || '').trim() }))
                .filter((entry) => entry.id && entry.name)
            : []),
        [productShapeDefinitions],
    );
    const [runtimeShapeDefinitionOptions, setRuntimeShapeDefinitionOptions] = useState<Array<{ id: string; name: string }>>(shapeDefinitionOptions);
    const [printingSettings, setPrintingSettings] = useState<PrintingSettings>({
        customPrintersEnabled: false,
        printerConfigs: [],
        printSections: [],
    });
    const [quickPrintDialogOpen, setQuickPrintDialogOpen] = useState(false);
    const [quickPrinterDialogOpen, setQuickPrinterDialogOpen] = useState(false);
    const [quickSectionName, setQuickSectionName] = useState('');
    const [quickSectionPrinterId, setQuickSectionPrinterId] = useState('none');
    const [quickSectionCopies, setQuickSectionCopies] = useState(1);
    const [quickSectionPrintPrices, setQuickSectionPrintPrices] = useState(false);
    const [quickSectionEnabled, setQuickSectionEnabled] = useState(true);
    const [quickPrinterName, setQuickPrinterName] = useState('');
    const [quickPrinterConnectionType, setQuickPrinterConnectionType] = useState<'network' | 'windows' | 'usb'>('network');
    const [quickPrinterIpAddress, setQuickPrinterIpAddress] = useState('');
    const [quickPrinterPort, setQuickPrinterPort] = useState('9100');
    const [quickPrinterShareName, setQuickPrinterShareName] = useState('');
    const [quickPrinterPaperWidth, setQuickPrinterPaperWidth] = useState<'58mm' | '80mm' | 'a4'>('80mm');
    const [quickPrinterRole, setQuickPrinterRole] = useState<'receipt' | 'prep' | 'both'>('prep');
    const [quickPrinterEnabled, setQuickPrinterEnabled] = useState(true);
    const [isQuickSectionSaving, setIsQuickSectionSaving] = useState(false);
    const [isQuickPrinterSaving, setIsQuickPrinterSaving] = useState(false);
    const realEstateProjectOptions = useMemo(
        () => [...(realEstateProjects || [])].sort((left, right) => String(left.name || '').localeCompare(String(right.name || ''))),
        [realEstateProjects],
    );

    const nextItemNumber = useMemo(() => {
        if (itemType !== 'material' || items.length === 0) return '1';
        const materialItems = items as ProductionItem[];
        const maxNum = materialItems.reduce((max, itm) => {
            const numeric = parseInt(String(itm.itemNumber || itm.id || '').replace(/\D+/g, ''), 10);
            return isNaN(numeric) ? max : Math.max(max, numeric);
        }, 0);
        return String(maxNum + 1);
    }, [items, itemType]);

    const nextCustomerNumber = useMemo(() => {
        if (itemType !== 'customer' || items.length === 0) return '1';
        const customerItems = items as (Customer & { id: string })[];
        const maxNum = customerItems.reduce((max, itm) => {
            const numeric = parseInt(String(itm.customerNumber || itm.id || '').replace(/\D+/g, ''), 10);
            return isNaN(numeric) ? max : Math.max(max, numeric);
        }, 0);
        return String(maxNum + 1);
    }, [items, itemType]);

    const nextSupplierNumber = useMemo(() => {
        if (itemType !== 'supplier' || items.length === 0) return '1';
        const supplierItems = items as Supplier[];
        const maxNum = supplierItems.reduce((max, itm) => {
            const numeric = parseInt(String(itm.supplierNumber || itm.id || '').replace(/\D+/g, ''), 10);
            return isNaN(numeric) ? max : Math.max(max, numeric);
        }, 0);
        return String(maxNum + 1);
    }, [items, itemType]);

    const nextUnitNumber = useMemo(() => {
        if (itemType !== 'unit') return '';
        return '';
    }, [itemType]);

    const supplierDefaults = (supplier?: Supplier) => ({
        supplierNumber: supplier?.supplierNumber || nextSupplierNumber || '1',
        name: supplier?.name || '',
        phone: supplier?.phone || '',
        address: supplier?.address || '',
        paymentTerms: supplier?.paymentTerms ?? '',
        taxNumber: supplier?.taxNumber || '',
    });

    const expenseDefaults = (expense?: ProductionItem) => ({
        name: expense?.name || '',
        realEstateProjectId: (expense as any)?.realEstateProjectId || '',
        realEstateUnitId: (expense as any)?.realEstateUnitId || '',
        realEstateCostType: (expense as any)?.realEstateCostType || 'general',
        realEstateAllocationMethod: (expense as any)?.realEstateAllocationMethod || 'area',
    });

    const salePriceRef = useRef<HTMLInputElement | null>(null);
    const materialNameRef = useRef<HTMLInputElement | null>(null);
    const materialAlternativeOptions = useMemo(() => {
        if (itemType !== 'material') return [] as ProductionItem[];
        const currentMaterialId = String((item as ProductionItem | undefined)?.id || initialValues?.itemNumber || '').trim();
        const materialItems = (items as ProductionItem[])
            .filter((entry) => String(entry?.id || '').trim() !== currentMaterialId)
            .sort((a, b) => String(a.name || '').localeCompare(String(b.name || '')));
        return materialItems;
    }, [itemType, item, initialValues, items]);
    const materialAlternativeById = useMemo(() => {
        const mapped = new Map<string, ProductionItem>();
        materialAlternativeOptions.forEach((entry) => {
            const id = String(entry?.id || '').trim();
            if (!id) return;
            mapped.set(id, entry);
        });
        return mapped;
    }, [materialAlternativeOptions]);

    const collectMaterialAvailableUnits = (material: ProductionItem | undefined): string[] => {
        if (!material) return [];

        const units: string[] = [];
        const pushUnique = (value: string) => {
            const unit = String(value || '').trim();
            if (!unit) return;
            if (!units.some((entry) => entry.toLowerCase() === unit.toLowerCase())) {
                units.push(unit);
            }
        };

        pushUnique(String(material.primaryUnit || ''));
        if (Array.isArray((material as any).secondaryUnits) && (material as any).secondaryUnits.length > 0) {
            (material as any).secondaryUnits.forEach((entry: any) => pushUnique(String(entry?.unit || '')));
        } else {
            pushUnique(String(material.secondaryUnit || ''));
        }

        return units;
    };

    const normalizeSimilarityText = (value: string) => String(value || '')
        .toLowerCase()
        .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
        .replace(/[إأآٱ]/g, 'ا')
        .replace(/ى/g, 'ي')
        .replace(/ؤ/g, 'و')
        .replace(/ئ/g, 'ي')
        .replace(/ة/g, 'ه')
        .replace(/\s+/g, '')
        .replace(/[^\p{L}\p{N}]+/gu, '');

    const sortCharsForAdvancedMatch = (value: string) => normalizeSimilarityText(value).split('').sort().join('');

    const matchesAdvancedAlternativeSearch = (candidate: ProductionItem, rawQuery: string) => {
        const query = String(rawQuery || '').trim();
        if (!query) return true;

        const tokens = query
            .split(/\s+/)
            .map((part) => ({
                normalized: normalizeSimilarityText(part),
                sorted: sortCharsForAdvancedMatch(part),
            }))
            .filter((part) => part.normalized.length > 0);

        if (tokens.length === 0) return true;

        const fields = [
            candidate.itemNumber,
            candidate.id,
            candidate.name,
            candidate.itemSymbolName || '',
            (candidate as any).globalReferenceNumber || '',
            candidate.barcode || '',
            candidate.secondaryBarcode || '',
            (candidate.additionalBarcodes || []).join(' '),
            Array.isArray((candidate as any).secondaryUnits)
                ? (candidate as any).secondaryUnits.map((entry: any) => `${entry?.unit || ''} ${entry?.barcode || ''} ${entry?.quantity || ''} ${entry?.price || ''}`).join(' ')
                : '',
            String(candidate.salePrice ?? ''),
            String(candidate.purchasePrice ?? ''),
            candidate.additionalDetails || '',
        ];

        const normalizedFields = fields.map((field) => normalizeSimilarityText(String(field || ''))).filter(Boolean);
        const sortedFields = normalizedFields.map((field) => field.split('').sort().join(''));

        return tokens.every((token) =>
            normalizedFields.some((field) => field.includes(token.normalized))
            || sortedFields.some((field) => token.sorted && field.includes(token.sorted))
        );
    };

    const toBigrams = (value: string) => {
        const source = normalizeSimilarityText(value).replace(/\s+/g, '');
        if (source.length < 2) return new Set<string>(source ? [source] : []);
        const grams = new Set<string>();
        for (let index = 0; index < source.length - 1; index += 1) {
            grams.add(source.slice(index, index + 2));
        }
        return grams;
    };

    const calcSimilarity = (left: string, right: string) => {
        const a = normalizeSimilarityText(left);
        const b = normalizeSimilarityText(right);
        if (!a || !b) return 0;
        if (a === b) return 1;

        const shorter = a.length <= b.length ? a : b;
        const longer = a.length > b.length ? a : b;
        if (longer.includes(shorter) && shorter.length >= 3) {
            const ratio = shorter.length / longer.length;
            return ratio >= 0.7 ? ratio : 0;
        }

        const gramsA = toBigrams(a);
        const gramsB = toBigrams(b);
        if (gramsA.size === 0 || gramsB.size === 0) return 0;

        let intersection = 0;
        gramsA.forEach((gram) => {
            if (gramsB.has(gram)) intersection += 1;
        });
        const union = gramsA.size + gramsB.size - intersection;
        return union > 0 ? (intersection / union) : 0;
    };

    const hasDetailsPartMatch = (sourceText: string, targetText: string) => {
        const source = normalizeSimilarityText(sourceText);
        const target = normalizeSimilarityText(targetText);
        if (!source || !target) return false;
        const tokens = source.split(/\s+/).map((token) => token.trim()).filter((token) => token.length >= 4);
        return tokens.some((token) => target.includes(token));
    };

    const runSmartAlternativeSuggestion = () => {
        setMaterialActiveTab('alternatives');
        const currentName = String(form.getValues('name') || '').trim();
        const currentSymbol = String(form.getValues('itemSymbolName') || '').trim();
        const currentGlobalReference = String((form.getValues as any)('globalReferenceNumber') || '').trim();
        const currentDetails = String(form.getValues('additionalDetails') || '').trim();

        void (async () => {
            try {
                const response = await handleSuggestMaterialAlternatives({
                    currentItemId: String((item as ProductionItem | undefined)?.id || '').trim(),
                    name: currentName,
                    itemSymbolName: currentSymbol,
                    globalReferenceNumber: currentGlobalReference,
                    additionalDetails: currentDetails,
                    limit: 40,
                });
                const mapped = (response?.suggestions || []).map((entry) => ({
                    ...entry,
                    reason: entry.reason === 'تطابق في اسم الصنف'
                        ? (t?.smartAltReasonName || entry.reason)
                        : entry.reason === 'تطابق في اسم الرمز'
                            ? (t?.smartAltReasonSymbol || entry.reason)
                            : entry.reason === 'تطابق في الرقم المرجعي العالمي'
                                ? (t?.smartAltReasonGlobalReference || entry.reason)
                                : (t?.smartAltReasonDetails || entry.reason),
                }));
                setSmartAlternativeSuggestions(mapped);
                setSmartSuggestionTried(true);
            } catch {
                // Fallback to local candidate list if server suggestion fails.
                const suggestions = materialAlternativeOptions.map((candidate) => {
                    const candidateName = String(candidate.name || '').trim();
                    const candidateSymbol = String(candidate.itemSymbolName || '').trim();
                    const candidateGlobalReference = String((candidate as any).globalReferenceNumber || '').trim();
                    const candidateDetails = String(candidate.additionalDetails || '').trim();

                    const nameScore = calcSimilarity(currentName, candidateName);
                    const symbolScore = calcSimilarity(currentSymbol, candidateSymbol);
                    const globalReferenceScore = calcSimilarity(currentGlobalReference, candidateGlobalReference);
                    let detailsScore = calcSimilarity(currentDetails, candidateDetails);
                    if (!detailsScore && (
                        hasDetailsPartMatch(`${currentName} ${currentSymbol} ${currentGlobalReference} ${currentDetails}`, candidateDetails)
                        || hasDetailsPartMatch(candidateDetails, `${currentName} ${currentSymbol} ${currentGlobalReference} ${currentDetails}`)
                    )) {
                        detailsScore = 0.7;
                    }

                    const maxScore = Math.max(nameScore, symbolScore, globalReferenceScore, detailsScore);
                    if (maxScore < 0.7) return null;

                    const reason = nameScore >= symbolScore && nameScore >= globalReferenceScore && nameScore >= detailsScore
                        ? (t?.smartAltReasonName || 'تطابق في اسم الصنف')
                        : (symbolScore >= globalReferenceScore && symbolScore >= detailsScore
                            ? (t?.smartAltReasonSymbol || 'تطابق في اسم الرمز')
                            : (globalReferenceScore >= detailsScore
                                ? (t?.smartAltReasonGlobalReference || 'تطابق في الرقم المرجعي العالمي')
                                : (t?.smartAltReasonDetails || 'تطابق في التفاصيل')));

                    return {
                        id: String(candidate.id || ''),
                        name: candidateName,
                        itemNumber: String(candidate.itemNumber || ''),
                        itemSymbolName: candidateSymbol,
                        globalReferenceNumber: candidateGlobalReference,
                        additionalDetails: candidateDetails,
                        score: maxScore,
                        reason,
                    };
                }).filter((entry): entry is {
                    id: string;
                    name: string;
                    itemNumber: string;
                    itemSymbolName: string;
                    globalReferenceNumber: string;
                    additionalDetails: string;
                    score: number;
                    reason: string;
                } => !!entry)
                    .sort((a, b) => b.score - a.score);

                setSmartAlternativeSuggestions(suggestions);
                setSmartSuggestionTried(true);
            }
        })();
    };

    const materialDefaults = (material?: ProductionItem) => ({
        secondaryUnits: Array.isArray((material as any)?.secondaryUnits) && (material as any).secondaryUnits.length > 0
            ? (material as any).secondaryUnits.map((entry: any) => ({
                unit: entry?.unit || '',
                barcode: entry?.barcode || '',
                quantity: entry?.quantity ?? '',
                price: entry?.price ?? '',
            }))
            : ((material?.secondaryUnit || material?.secondaryBarcode || material?.secondaryUnitQuantity || material?.secondaryUnitPrice)
                ? [{
                    unit: material?.secondaryUnit || '',
                    barcode: material?.secondaryBarcode || '',
                    quantity: material?.secondaryUnitQuantity ?? '',
                    price: material?.secondaryUnitPrice ?? '',
                }]
                : (material ? [] : [{ unit: '', barcode: '', quantity: '', price: '' }])),
        itemNumber: material?.itemNumber || nextItemNumber,
        name: material?.name || '',
        itemCategory: ['inventory', 'service', 'non_stock', 'bundle'].includes(String((material as any)?.itemCategory || '').trim())
            ? String((material as any)?.itemCategory || '').trim()
            : 'inventory',
        reorderMinimumQty: typeof (material as any)?.reorderMinimumQty === 'number' && Number.isFinite((material as any)?.reorderMinimumQty)
            ? (material as any).reorderMinimumQty
            : '',
        reorderUnit: String((material as any)?.reorderUnit || '').trim() || String(material?.primaryUnit || '').trim() || '',
        itemSymbolName: material?.itemSymbolName || '',
        globalReferenceNumber: (material as any)?.globalReferenceNumber || '',
        barcode: material?.barcode || '',
        secondaryBarcode: material?.secondaryBarcode || '',
        additionalBarcodes: material?.additionalBarcodes || [],
        groupId: material?.groupId || '',
        additionalDetails: material?.additionalDetails || '',
        imageUrl: material?.imageUrl || '',
        primaryUnit: material?.primaryUnit || '',
        primaryUnitQuantity: material
            ? (String(material?.primaryUnit || '').trim()
                ? (material?.primaryUnitQuantity ?? 1)
                : '')
            : 1,
        secondaryUnit: material?.secondaryUnit || '',
        secondaryUnitQuantity: material?.secondaryUnitQuantity ?? '',
        secondaryUnitPrice: material?.secondaryUnitPrice ?? '',
        alternativeItemIds: Array.isArray((material as any)?.alternativeItemIds)
            ? (material as any).alternativeItemIds
            : [],
        isWeighed: material?.isWeighed ?? false,
        isSized: (material as any)?.isSized ?? false,
        isManufactured: (material as any)?.isManufactured ?? false,
        productionOutputQuantity: (material as any)?.productionOutputQuantity ?? 1,
        productionFormula: Array.isArray((material as any)?.productionFormula)
            ? (material as any).productionFormula.map((entry: any) => ({
                materialId: entry?.materialId || '',
                quantity: entry?.quantity ?? '',
                unit: entry?.unit || '',
                notes: entry?.notes || '',
                wastePercent: entry?.wastePercent ?? '',
            }))
            : [],
        isDisassemblable: (material as any)?.isDisassemblable ?? false,
        disassemblyTemplate: Array.isArray((material as any)?.disassemblyTemplate)
            ? (material as any).disassemblyTemplate.map((entry: any) => ({
                partItemId: entry?.partItemId || '',
                quantity: entry?.quantity ?? 1,
                expectedSalePrice: entry?.expectedSalePrice ?? '',
                notes: entry?.notes || '',
            }))
            : [],
        shelfLifeYears: (material as any)?.shelfLifeYears ?? '',
        shelfLifeMonths: (material as any)?.shelfLifeMonths ?? '',
        shelfLifeDays: (material as any)?.shelfLifeDays ?? '',
        storeSectionId: (material as any)?.storeSectionId ?? '',
        storeBranchId: (material as any)?.storeBranchId ?? '',
        storeEnabled: (material as any)?.storeEnabled ?? false,
        printSectionId: (material as any)?.printSectionId ?? '',
        excludeFromPrepTicket: (material as any)?.excludeFromPrepTicket ?? false,
        printLabelOverride: (material as any)?.printLabelOverride ?? '',
        realEstateProjectId: (material as any)?.realEstateProjectId ?? '',
        realEstateUnitId: (material as any)?.realEstateUnitId ?? '',
        realEstateCostType: (material as any)?.realEstateCostType ?? 'general',
        realEstateAllocationMethod: (material as any)?.realEstateAllocationMethod ?? 'area',
        allowDescriptionEdit: material?.allowDescriptionEdit ?? false,
        purchasePrice: material?.purchasePrice ?? '',
        salePrice: material?.salePrice ?? '0.00',
        usesDefaultTax: material?.usesDefaultTax ?? true,
        taxRate: material?.taxRate ?? '',
        hasSerialNumber: material?.hasSerialNumber ?? false,
        hasRfid: material?.hasRfid ?? false,
        enableCustomTax: material?.usesDefaultTax === false,
        customTaxValue: material?.taxRate ?? '',
        enableProfitMargin: material?.enableProfitMargin ?? false,
        profitMargin: material?.profitMargin ?? '',
        categoryPrices: material?.categoryPrices ?? {},
        usesProductShapes: material?.usesProductShapes ?? false,
        productShapeType: material?.productShapeType ?? '',
        productShapes: (material?.productShapes || []).map((shape, index) => ({
            id: shape.id || `shape-${index + 1}`,
            name: shape.name || '',
            salePrice: shape.salePrice ?? 0,
            costPrice: shape.costPrice ?? '',
            type: shape.type || material?.productShapeType || '',
            isActive: shape.isActive ?? true,
        })),
        revenueAccountCode: (material as any)?.revenueAccountCode ?? '',
        inventoryAccountCode: (material as any)?.inventoryAccountCode ?? '',
        cogsAccountCode: (material as any)?.cogsAccountCode ?? '',
        purchaseAccountCode: (material as any)?.purchaseAccountCode ?? '',
    });

    const activeSchema: z.ZodTypeAny =
        itemType === 'material'
            ? materialItemSchema
            : itemType === 'expense'
                ? expenseItemSchema
                : itemType === 'customer'
                    ? customerItemSchema
                    : itemType === 'supplier'
                        ? supplierItemSchema
                        : itemType === 'sales-rep'
                            ? salesRepItemSchema
                            : itemType === 'unit'
                                ? unitItemSchema
                                : listItemSchema;

    const form = useForm<any>({
        resolver: zodResolver(activeSchema),
        defaultValues: itemType === 'material'
            ? materialDefaults(item as ProductionItem | undefined)
            : itemType === 'customer'
              ? {
                    customerNumber: (item as Customer | undefined)?.customerNumber || nextCustomerNumber,
                    name: item?.name || '',
                    category: (item as Customer | undefined)?.category || 'general',
                    phone: (item as Customer | undefined)?.phone || '',
                    creditLimit: (item as Customer | undefined)?.creditLimit ?? '',
                    address: (item as Customer | undefined)?.address || '',
                    allowedDiscount: (item as Customer | undefined)?.allowedDiscount ?? '',
                                        salesRepId: (item as Customer | undefined)?.salesRepId ?? '',
                }
                            : itemType === 'supplier'
                                ? supplierDefaults(item as Supplier | undefined)
                            : itemType === 'expense'
                                ? expenseDefaults(item as ProductionItem | undefined)
                            : itemType === 'sales-rep'
                                ? {
                                        name: (item as SalesRep | undefined)?.name || '',
                                        phone: (item as SalesRep | undefined)?.phone || '',
                                        region: (item as SalesRep | undefined)?.region || '',
                                        commissionRate: (item as SalesRep | undefined)?.commissionRate ?? '',
                                }
                            : itemType === 'unit'
                                ? {
                                    unitNumber: (item as ListManagedUnit | undefined)?.unitNumber || nextUnitNumber,
                                    description: (item as ListManagedUnit | undefined)?.description || '',
                                    unitType: ((item as ListManagedUnit | undefined)?.unitType === 'secondary' ? 'secondary' : 'primary'),
                                    shortCode: (item as ListManagedUnit | undefined)?.shortCode || '',
                                    notes: (item as ListManagedUnit | undefined)?.notes || '',
                                }
              : { name: item?.name || "" },
    });

    const watchedPrimaryUnit = form.watch('primaryUnit');
    const watchedSecondaryUnits = form.watch('secondaryUnits');

    const reorderUnitOptions = useMemo(() => {
        const options: Array<{ value: string; label: string }> = [];
        const primaryUnit = String(watchedPrimaryUnit || '').trim();
        if (primaryUnit) {
            options.push({
                value: primaryUnit,
                label: `${t.primaryUnitLabel || 'الوحدة الرئيسية'}: ${primaryUnit}`,
            });
        }

        const secondaryUnits = Array.isArray(watchedSecondaryUnits) ? watchedSecondaryUnits : [];
        const seen = new Set<string>(primaryUnit ? [primaryUnit] : []);
        secondaryUnits.forEach((entry: any) => {
            const unit = String(entry?.unit || '').trim();
            if (!unit || seen.has(unit)) return;
            seen.add(unit);
            options.push({
                value: unit,
                label: `${t.secondaryUnitLabel || 'الوحدة الفرعية'}: ${unit}`,
            });
        });

        return options;
    }, [watchedPrimaryUnit, watchedSecondaryUnits, t]);

    const applyCategoryDefaultAccounts = (categoryValue?: string, forceApply?: boolean) => {
        if (itemType !== 'material') return;
        const category = String(categoryValue || '').trim();
        const isService = category === 'service';
        const isInventory = category === 'inventory' || category === 'bundle' || !category;

        const currentValues = form.getValues();
        const revenueCode = String(currentValues.revenueAccountCode || '').trim();
        const inventoryCode = String(currentValues.inventoryAccountCode || '').trim();
        const cogsCode = String(currentValues.cogsAccountCode || '').trim();
        const purchaseCode = String(currentValues.purchaseAccountCode || '').trim();

        // Only apply defaults if field is empty, unless explicitly forced
        if (forceApply || !revenueCode) {
            form.setValue('revenueAccountCode', isService ? '4140' : '4110', { shouldDirty: true, shouldValidate: true });
        }
        if (forceApply || !inventoryCode) {
            form.setValue('inventoryAccountCode', isInventory ? '1170' : '', { shouldDirty: true, shouldValidate: true });
        }
        if (forceApply || !cogsCode) {
            form.setValue('cogsAccountCode', isService ? '' : '5110', { shouldDirty: true, shouldValidate: true });
        }
        if (forceApply || !purchaseCode) {
            form.setValue('purchaseAccountCode', isService ? '' : '5110', { shouldDirty: true, shouldValidate: true });
        }
    };

    useEffect(() => {
        if (itemType !== 'material' || item || !initialValues) return;
        const values = {
            ...form.getValues(),
            ...initialValues,
        };
        form.reset(values);
    }, [itemType, item, initialValues, form]);

    useEffect(() => {
        if (itemType !== 'material' || !item) return;
        form.reset(materialDefaults(item as ProductionItem));
    }, [itemType, item, form]);

    useEffect(() => {
        if (itemType !== 'supplier') return;
        form.reset(supplierDefaults(item as Supplier | undefined));
    }, [itemType, item, form, nextSupplierNumber]);

    useEffect(() => {
        setManagedUnitOptions(sortManagedUnits(unitDefinitions || []));
    }, [unitDefinitions]);

    useEffect(() => {
        setRuntimeSalesRepOptions(sortSalesRepOptions(salesReps || []));
    }, [salesReps]);

    useEffect(() => {
        setRuntimeCategoryOptions(sortCategoryOptions(categories || []));
    }, [categories]);

    useEffect(() => {
        if (!active || itemType !== 'material') return;

        let isMounted = true;
        const loadPrintingSettings = async () => {
            const result = await handleGetPrinterConfiguration();
            if (!isMounted || !result || 'error' in result) return;
            setPrintingSettings((result as any).settings || {
                customPrintersEnabled: false,
                printerConfigs: [],
                printSections: [],
            });
        };

        void loadPrintingSettings();

        return () => {
            isMounted = false;
        };
    }, [itemType, active]);

    useEffect(() => {
        if (!active || itemType !== 'material') return;
        if (managedUnitOptions.length > 0) return;

        let isMounted = true;
        const loadUnits = async () => {
            const result = await handleGetManagedUnits();
            if (!isMounted || !result?.success) return;
            const items = Array.isArray((result as any).items) ? ((result as any).items as ManagedUnit[]) : [];
            if (items.length > 0) {
                setManagedUnitOptions(sortManagedUnits(items));
            }
        };

        void loadUnits();

        return () => {
            isMounted = false;
        };
    }, [itemType, managedUnitOptions.length, active]);

    useEffect(() => {
        setRuntimeShapeDefinitionOptions((prev) => {
            if (prev.length === shapeDefinitionOptions.length && prev.every((entry, index) => (
                entry.id === shapeDefinitionOptions[index]?.id
                && entry.name === shapeDefinitionOptions[index]?.name
            ))) {
                return prev;
            }
            return shapeDefinitionOptions;
        });
    }, [shapeDefinitionOptions]);

    useEffect(() => {
        if (!active || itemType !== 'material') return;
        if (runtimeShapeDefinitionOptions.length > 0) return;

        let isMounted = true;
        const loadProductShapeDefinitions = async () => {
            const result = await handleGetProductShapeDefinitions();
            if (!isMounted || !result?.success) return;
            const fetched = Array.isArray((result as any).items)
                ? ((result as any).items as Array<{ id: string; name: string }>)
                : [];
            if (fetched.length > 0) {
                setRuntimeShapeDefinitionOptions(
                    fetched
                        .map((entry) => ({ id: String(entry.id || ''), name: String(entry.name || '').trim() }))
                        .filter((entry) => entry.id && entry.name),
                );
            }
        };

        void loadProductShapeDefinitions();

        return () => {
            isMounted = false;
        };
    }, [itemType, runtimeShapeDefinitionOptions.length, active]);

    useEffect(() => {
        if (itemType !== 'material' || !focusSalePrice) return;
        const id = setTimeout(() => {
            salePriceRef.current?.focus();
            salePriceRef.current?.select();
        }, 0);
        return () => clearTimeout(id);
    }, [itemType, focusSalePrice]);

    useEffect(() => {
        if (itemType !== 'material' || focusSalePrice) return;
        const id = setTimeout(() => {
            materialNameRef.current?.focus();
        }, 0);
        return () => clearTimeout(id);
    }, [itemType, focusSalePrice]);

    const { fields: additionalBarcodeFields, append: appendBarcode, remove: removeBarcode } = useFieldArray({
        control: form.control,
        name: 'additionalBarcodes',
    });

    const { fields: secondaryUnitFields, append: appendSecondaryUnit, remove: removeSecondaryUnit } = useFieldArray({
        control: form.control,
        name: 'secondaryUnits',
    });

    const { fields: productShapeFields, append: appendProductShape, remove: removeProductShape } = useFieldArray({
        control: form.control,
        name: 'productShapes',
    });

    const { fields: productionFormulaFields, append: appendProductionFormula, remove: removeProductionFormula } = useFieldArray({
        control: form.control,
        name: 'productionFormula',
    });

    const { fields: disassemblyTemplateFields, append: appendDisassemblyTemplate, remove: removeDisassemblyTemplate } = useFieldArray({
        control: form.control,
        name: 'disassemblyTemplate',
    });

    const watchedImageUrl = form.watch('imageUrl');

    const enableProfitMargin = form.watch('enableProfitMargin');
    const profitMarginValue = Number(form.watch('profitMargin') || 0);
    const purchasePriceValue = Number(form.watch('purchasePrice') || 0);
    const isManufacturedValue = !!form.watch('isManufactured');
    const isDisassemblableValue = !!form.watch('isDisassemblable');
    const productionOutputQuantityValue = Number(form.watch('productionOutputQuantity') || 1);
    const productionFormulaValue = form.watch('productionFormula') || [];
    const disassemblyTemplateValue = form.watch('disassemblyTemplate') || [];
    const secondaryUnitsValue = form.watch('secondaryUnits') || [];

    const roundTo2 = (value: number) => Math.round(value * 100) / 100;

    const getSecondaryUnitCost = (row: any, basePurchasePrice: number) => {
        const quantity = Number(row?.quantity || 0);
        if (!Number.isFinite(basePurchasePrice) || basePurchasePrice <= 0) return 0;
        if (!Number.isFinite(quantity) || quantity <= 0) return 0;
        return basePurchasePrice / quantity;
    };

    const secondaryRowsBelowCost = useMemo(() => {
        const rows = Array.isArray(secondaryUnitsValue) ? secondaryUnitsValue : [];
        return rows.map((row: any, index: number) => {
            const salePrice = Number(row?.price || 0);
            const unitCost = getSecondaryUnitCost(row, purchasePriceValue);
            const isBelow = Number.isFinite(salePrice) && Number.isFinite(unitCost) && unitCost > 0 && salePrice < unitCost;
            return { index, isBelow, unitCost, salePrice, unitLabel: String(row?.unit || '').trim() };
        });
    }, [secondaryUnitsValue, purchasePriceValue]);

    const disassemblyExpectedTotal = useMemo(() => {
        const rows = Array.isArray(disassemblyTemplateValue) ? disassemblyTemplateValue : [];
        return rows.reduce((sum: number, row: any) => {
            const quantity = Number(row?.quantity || 0);
            const expectedSalePrice = Number(row?.expectedSalePrice || 0);
            if (!Number.isFinite(quantity) || quantity <= 0 || !Number.isFinite(expectedSalePrice) || expectedSalePrice < 0) {
                return sum;
            }
            return sum + (quantity * expectedSalePrice);
        }, 0);
    }, [disassemblyTemplateValue]);

    const syncSecondaryPricesFromPurchase = (purchasePrice: number, marginPercent: number) => {
        const marginMultiplier = 1 + (Number.isFinite(marginPercent) ? (marginPercent / 100) : 0);
        const rows = form.getValues('secondaryUnits') || [];
        if (!Array.isArray(rows)) return;
        rows.forEach((row: any, index: number) => {
            const quantity = Number(row?.quantity || 0);
            if (!Number.isFinite(quantity) || quantity <= 0) return;
            const baseSecondaryPrice = purchasePrice / quantity;
            const computedSecondaryPrice = roundTo2(baseSecondaryPrice * marginMultiplier);
            const currentSecondaryPrice = Number(form.getValues(`secondaryUnits.${index}.price`) || 0);
            if (Math.abs(currentSecondaryPrice - computedSecondaryPrice) > 0.0001) {
                form.setValue(`secondaryUnits.${index}.price`, computedSecondaryPrice, { shouldDirty: true });
            }
        });
    };

    const materialsById = useMemo(() => {
        if (itemType !== 'material') return new Map<string, ProductionItem>();
        return new Map((items as ProductionItem[]).map((entry) => [String(entry.id || ''), entry]));
    }, [itemType, items]);

    const itemGroupsById = useMemo(() => {
        const groups = Array.isArray(itemGroups) ? itemGroups : [];
        return new Map(groups.map((group) => [String(group.id || ''), group]));
    }, [itemGroups]);

    const selectedPrintSectionId = String(form.watch('printSectionId') || '').trim();
    const selectedRealEstateProjectId = String(form.watch('realEstateProjectId') || '').trim();
    const selectedRealEstateCostType = String(form.watch('realEstateCostType') || 'general').trim();
    const selectedRealEstateProject = useMemo(
        () => realEstateProjectOptions.find((project) => String(project.id || '').trim() === selectedRealEstateProjectId),
        [realEstateProjectOptions, selectedRealEstateProjectId],
    );
    const selectedRealEstateUnits = Array.isArray(selectedRealEstateProject?.units) ? selectedRealEstateProject.units : [];
    const selectedPrintSection = useMemo(
        () => (printingSettings.printSections || []).find((section) => String(section?.id || '').trim() === selectedPrintSectionId),
        [printingSettings, selectedPrintSectionId],
    );
    const selectedPrintSectionPrinterName = useMemo(() => {
        const printerId = String(selectedPrintSection?.printerId || '').trim();
        if (!printerId) return '';
        const printer = (printingSettings.printerConfigs || []).find((entry) => String(entry?.id || '').trim() === printerId);
        return String(printer?.name || '').trim();
    }, [printingSettings, selectedPrintSection]);

    const refreshPrintingSettings = async () => {
        const result = await handleGetPrinterConfiguration();
        if (!result || 'error' in result) return;
        setPrintingSettings((result as any).settings || {
            customPrintersEnabled: false,
            printerConfigs: [],
            printSections: [],
        });
    };

    const resetQuickSectionDraft = () => {
        setQuickSectionName('');
        setQuickSectionPrinterId('none');
        setQuickSectionCopies(1);
        setQuickSectionPrintPrices(false);
        setQuickSectionEnabled(true);
    };

    const resetQuickPrinterDraft = () => {
        setQuickPrinterName('');
        setQuickPrinterConnectionType('network');
        setQuickPrinterIpAddress('');
        setQuickPrinterPort('9100');
        setQuickPrinterShareName('');
        setQuickPrinterPaperWidth('80mm');
        setQuickPrinterRole('prep');
        setQuickPrinterEnabled(true);
    };

    const onQuickAddSection = async () => {
        const normalizedName = String(quickSectionName || '').trim();
        if (!normalizedName) {
            toast({
                title: t?.validationError || 'خطأ في التحقق',
                description: t?.printSectionNameRequired || 'اسم القسم مطلوب.',
                variant: 'destructive',
            });
            return;
        }

        setIsQuickSectionSaving(true);
        const result = await handleQuickAddPrintSection({
            name: normalizedName,
            printerId: quickSectionPrinterId === 'none' ? '' : quickSectionPrinterId,
            copies: quickSectionCopies,
            printPrices: quickSectionPrintPrices,
            enabled: quickSectionEnabled,
        });
        setIsQuickSectionSaving(false);

        if (!result || 'error' in result) {
            toast({
                title: t?.saveErrorTitle || 'خطأ',
                description: (result as any)?.error || 'تعذر إضافة قسم الطباعة.',
                variant: 'destructive',
            });
            return;
        }

        await refreshPrintingSettings();

        const createdId = String((result as any)?.section?.id || '').trim();
        if (createdId) {
            form.setValue('printSectionId', createdId, { shouldDirty: true, shouldValidate: true });
        }

        toast({
            title: t?.saveSuccessTitle || 'تم الحفظ',
            description: t?.quickPrintSectionAdded || 'تمت إضافة قسم الطباعة وربطه بالصنف.',
        });

        resetQuickSectionDraft();
        setQuickPrintDialogOpen(false);
    };

    const onQuickAddPrinter = async () => {
        const normalizedName = String(quickPrinterName || '').trim();
        if (!normalizedName) {
            toast({
                title: t?.validationError || 'خطأ في التحقق',
                description: t?.printerNameRequired || 'اسم الطابعة مطلوب.',
                variant: 'destructive',
            });
            return;
        }

        const normalizedPort = quickPrinterPort.trim();
        const parsedPort = normalizedPort ? Number(normalizedPort) : undefined;
        if (quickPrinterConnectionType === 'network' && (!Number.isFinite(parsedPort) || Number(parsedPort) <= 0)) {
            toast({
                title: t?.validationError || 'خطأ في التحقق',
                description: t?.printerPortRequired || 'منفذ الطابعة الشبكية مطلوب.',
                variant: 'destructive',
            });
            return;
        }

        setIsQuickPrinterSaving(true);
        const result = await handleQuickAddPrinterConfig({
            name: normalizedName,
            connectionType: quickPrinterConnectionType,
            ipAddress: quickPrinterConnectionType === 'network' ? quickPrinterIpAddress : '',
            port: Number.isFinite(parsedPort) ? Number(parsedPort) : undefined,
            shareName: quickPrinterConnectionType === 'windows' ? quickPrinterShareName : '',
            paperWidth: quickPrinterPaperWidth,
            role: quickPrinterRole,
            enabled: quickPrinterEnabled,
        });
        setIsQuickPrinterSaving(false);

        if (!result || 'error' in result) {
            toast({
                title: t?.saveErrorTitle || 'خطأ',
                description: (result as any)?.error || 'تعذر إضافة الطابعة.',
                variant: 'destructive',
            });
            return;
        }

        const createdPrinterId = String((result as any)?.printer?.id || '').trim();
        await refreshPrintingSettings();
        if (createdPrinterId) {
            setQuickSectionPrinterId(createdPrinterId);
        }

        toast({
            title: t?.saveSuccessTitle || 'تم الحفظ',
            description: t?.quickPrinterAdded || 'تمت إضافة الطابعة بنجاح.',
        });

        resetQuickPrinterDraft();
        setQuickPrinterDialogOpen(false);
    };

    useEffect(() => {
        if (selectedRealEstateCostType !== 'direct-unit' || !selectedRealEstateProjectId) {
            const currentUnitId = String(form.getValues('realEstateUnitId') || '').trim();
            if (currentUnitId) {
                form.setValue('realEstateUnitId', '', { shouldDirty: true });
            }
        }
    }, [form, selectedRealEstateCostType, selectedRealEstateProjectId]);

    const convertFormulaQuantityToPrimary = (source: ProductionItem | undefined, formulaUnit: string | undefined, rawQuantity: number) => {
        if (!source || !Number.isFinite(rawQuantity) || rawQuantity <= 0) return 0;

        const quantity = Number(rawQuantity);
        const selectedUnit = String(formulaUnit || '').trim().toLowerCase();
        if (!selectedUnit) return quantity;

        const primaryUnit = String(source.primaryUnit || '').trim().toLowerCase();
        if (primaryUnit && selectedUnit === primaryUnit) return quantity;

        const primaryUnitQuantity = Number(source.primaryUnitQuantity || 1);
        const safePrimaryUnitQuantity = Number.isFinite(primaryUnitQuantity) && primaryUnitQuantity > 0 ? primaryUnitQuantity : 1;

        const secondaryCandidates = Array.isArray((source as any).secondaryUnits) && (source as any).secondaryUnits.length > 0
            ? (source as any).secondaryUnits
            : ((source.secondaryUnit || typeof source.secondaryUnitQuantity === 'number')
                ? [{ unit: source.secondaryUnit, quantity: source.secondaryUnitQuantity }]
                : []);

        const matchedSecondary = secondaryCandidates.find((entry: any) => String(entry?.unit || '').trim().toLowerCase() === selectedUnit);
        const secondaryRatio = Number(matchedSecondary?.quantity || 0);
        if (Number.isFinite(secondaryRatio) && secondaryRatio > 0) {
            return quantity * (safePrimaryUnitQuantity / secondaryRatio);
        }

        return quantity;
    };

    const getMaterialEffectiveTaxRate = (sourceMaterial: ProductionItem | undefined) => {
        if (!sourceMaterial) return 0;
        if (sourceMaterial.usesDefaultTax === false) {
            const customRate = Number(sourceMaterial?.taxRate || 0);
            return Number.isFinite(customRate) && customRate > 0 ? customRate : 0;
        }
        const ownRate = Number(sourceMaterial?.taxRate || 0);
        if (Number.isFinite(ownRate) && ownRate > 0) {
            return ownRate;
        }
        const groupId = String(sourceMaterial?.groupId || '').trim();
        const groupRate = Number(itemGroupsById.get(groupId)?.taxRate || 0);
        return Number.isFinite(groupRate) && groupRate > 0 ? groupRate : 0;
    };

    const productionCostMeta = useMemo(() => {
        if (itemType !== 'material' || !isManufacturedValue) {
            return { totalInputCost: 0, computedUnitCost: 0, unresolvedCount: 0 };
        }

        const outputQty = Number.isFinite(productionOutputQuantityValue) && productionOutputQuantityValue > 0
            ? productionOutputQuantityValue
            : 1;

        let totalInputCost = 0;
        let unresolvedCount = 0;
        const rows = Array.isArray(productionFormulaValue) ? productionFormulaValue : [];

        rows.forEach((entry: any) => {
            const materialId = String(entry?.materialId || '').trim();
            const quantity = Number(entry?.quantity || 0);
            if (!materialId || !Number.isFinite(quantity) || quantity <= 0) return;

            const wastePercent = Number(entry?.wastePercent || 0);
            const wasteMultiplier = 1 + ((Number.isFinite(wastePercent) && wastePercent > 0) ? (wastePercent / 100) : 0);
            const sourceMaterial = materialsById.get(materialId);
            const quantityInPrimaryUnits = convertFormulaQuantityToPrimary(sourceMaterial, entry?.unit, quantity);
            if (!Number.isFinite(quantityInPrimaryUnits) || quantityInPrimaryUnits <= 0) return;
            const sourceCost = Number(sourceMaterial?.purchasePrice || 0);

            if (!Number.isFinite(sourceCost) || sourceCost <= 0) {
                unresolvedCount += 1;
                return;
            }

            const effectiveTaxRate = getMaterialEffectiveTaxRate(sourceMaterial);

            const sourceCostInclTax = sourceCost * (1 + (effectiveTaxRate > 0 ? (effectiveTaxRate / 100) : 0));
            totalInputCost += sourceCostInclTax * quantityInPrimaryUnits * wasteMultiplier;
        });

        return {
            totalInputCost,
            computedUnitCost: outputQty > 0 ? roundTo2(totalInputCost / outputQty) : 0,
            unresolvedCount,
        };
    }, [itemType, isManufacturedValue, productionOutputQuantityValue, productionFormulaValue, materialsById, itemGroupsById]);

    useEffect(() => {
        if (itemType !== 'material' || !isManufacturedValue) return;
        const currentPurchasePrice = Number(form.getValues('purchasePrice') || 0);
        const nextPurchasePrice = productionCostMeta.computedUnitCost;
        if (Math.abs(currentPurchasePrice - nextPurchasePrice) > 0.0001) {
            form.setValue('purchasePrice', nextPurchasePrice, { shouldDirty: true });
        }
    }, [itemType, isManufacturedValue, productionCostMeta.computedUnitCost, form]);

    useEffect(() => {
        if (itemType !== 'material' || !enableProfitMargin) return;
        if (!Number.isFinite(purchasePriceValue) || purchasePriceValue <= 0) return;

        const marginMultiplier = 1 + (Number.isFinite(profitMarginValue) ? (profitMarginValue / 100) : 0);
        const computedPrimarySalePrice = roundTo2(purchasePriceValue * marginMultiplier);
        const currentSalePrice = Number(form.getValues('salePrice') || 0);

        if (computedPrimarySalePrice > 0 && Math.abs(currentSalePrice - computedPrimarySalePrice) > 0.0001) {
            form.setValue('salePrice', computedPrimarySalePrice, { shouldDirty: true });
        }

        syncSecondaryPricesFromPurchase(purchasePriceValue, profitMarginValue);
    }, [itemType, enableProfitMargin, profitMarginValue, purchasePriceValue, secondaryUnitsValue, form]);

    const getFirstErrorInfo = (
        errors: any,
        path: Array<string | number> = []
    ): { message: string; path: string | null } | null => {
        if (!errors) return null;

        if (typeof errors === 'object' && errors.message) {
            return {
                message: String(errors.message),
                path: path.length > 0 ? path.join('.') : null,
            };
        }

        if (typeof errors === 'object') {
            for (const key of Object.keys(errors)) {
                if (key === 'ref' || key === 'type') continue;
                const info = getFirstErrorInfo(errors[key], [...path, key]);
                if (info) return info;
            }
        }

        return null;
    };

    const formatValidationError = (info: { message: string; path: string | null } | null): string | null => {
        if (!info?.message) return null;

        const path = info.path || '';
        const secondaryQtyMatch = path.match(/^secondaryUnits\.(\d+)\.quantity$/);
        if (secondaryQtyMatch) {
            const rowNumber = Number(secondaryQtyMatch[1]) + 1;
            return `في الوحدات الفرعية (السطر ${rowNumber}): ${info.message}`;
        }

        return info.message;
    };

    const promptAndCreateManagedUnit = async (defaultType: 'primary' | 'secondary' = 'primary'): Promise<string | null> => {
        return new Promise((resolve) => {
            managedUnitResolverRef.current = resolve;
            setManagedUnitDescriptionDraft('');
            setManagedUnitTypeDraft(defaultType);
            setManagedUnitDialogOpen(true);
        });
    };

    const resolveManagedUnitDialog = (value: string | null) => {
        const resolver = managedUnitResolverRef.current;
        managedUnitResolverRef.current = null;
        managedUnitSubmitInFlightRef.current = false;
        if (resolver) {
            resolver(value);
        }
        setManagedUnitDialogOpen(false);
        setManagedUnitDescriptionDraft('');
        setManagedUnitTypeDraft('primary');
        setIsManagedUnitSaving(false);
    };

    const saveManagedUnitFromDialog = async () => {
        if (managedUnitSubmitInFlightRef.current) {
            return;
        }
        const description = String(managedUnitDescriptionDraft || '').trim();
        if (!description) {
            toast({
                title: t.saveErrorTitle || 'خطأ',
                description: t.addUnitPromptLabel || 'أدخل اسم الوحدة الجديدة',
                variant: 'destructive',
            });
            return;
        }

        managedUnitSubmitInFlightRef.current = true;
        setIsManagedUnitSaving(true);
        const result = await handleEnsureManagedUnit(description);
        if (!result?.success || !result.item) {
            managedUnitSubmitInFlightRef.current = false;
            setIsManagedUnitSaving(false);
            toast({
                title: t.saveErrorTitle || 'خطأ',
                description: result?.error || (t.addUnitFailedDescription || 'تعذر إضافة الوحدة.'),
                variant: 'destructive',
            });
            return;
        }

        const created = result.item as ManagedUnit;
        setManagedUnitOptions((prev) => {
            const exists = prev.some((entry) => String(entry.description || '').toLowerCase() === String(created.description || '').toLowerCase());
            if (exists) return prev;
            return sortManagedUnits([...prev, created]);
        });

        toast({
            title: t.saveSuccessTitle || 'تم الحفظ',
            description: t.addUnitSuccessDescription || 'تمت إضافة الوحدة بنجاح.',
        });

        resolveManagedUnitDialog(created.description);
    };

    const handleManagedUnitSelection = (
        selectedValue: string,
        onChange: (value: string) => void,
        sourceElement?: HTMLSelectElement | null,
        desiredType: 'primary' | 'secondary' = 'primary',
    ) => {
        if (selectedValue === 'none') {
            onChange('');
            return;
        }
        if (selectedValue === addUnitOptionValue) {
            sourceElement?.blur();
            void (async () => {
                const createdValue = await promptAndCreateManagedUnit(desiredType);
                if (createdValue) {
                    onChange(createdValue);
                }
            })();
            return;
        }
        onChange(selectedValue);
    };

    const saveQuickStoreSection = async () => {
        const trimmedName = storeSectionQuickName.trim();
        if (!trimmedName) return;
        setIsStoreSectionSaving(true);
        const result = await handleAddItemGroup({ name: trimmedName, isPosEnabled: false, usesDefaultTax: false, taxRate: 0 });
        setIsStoreSectionSaving(false);
        if ('error' in result && result.error) {
            toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
            return;
        }
        const created = (result as any)?.item || {};
        const newGroup: ItemGroup = {
            id: String(created.id || `grp-${Date.now()}`),
            name: String(created.name || trimmedName),
            isPosEnabled: false,
        } as ItemGroup;
        setRuntimeItemGroupOptions((prev) => {
            if (prev.some((g) => g.id === newGroup.id)) return prev;
            return sortItemGroupOptions([...prev, newGroup]);
        });
        toast({ title: 'تم', description: `تمت إضافة القسم "${newGroup.name}" بنجاح.` });
        setStoreSectionQuickName('');
    };

    const saveQuickProductShapeDefinition = async () => {
        if (isProductShapeQuickSaving) return;

        const trimmedName = String(productShapeQuickAddName || '').trim();
        if (!trimmedName) {
            toast({
                title: t.saveErrorTitle || 'خطأ',
                description: t.productShapeNameRequired || 'يرجى إدخال اسم الشكل.',
                variant: 'destructive',
            });
            return;
        }

        setIsProductShapeQuickSaving(true);
        const result = await handleAddListItem('product-shape', { name: trimmedName });
        setIsProductShapeQuickSaving(false);

        if ('error' in result && result.error) {
            toast({
                title: t.saveErrorTitle || 'خطأ',
                description: result.error || (t.addProductShapeFailed || 'تعذر إضافة الشكل.'),
                variant: 'destructive',
            });
            return;
        }

        const created = (result as any)?.item || {};
        const normalizedId = String(created.id || created.itemNumber || `shape-${Date.now()}`).trim();
        const normalizedName = String(created.name || trimmedName).trim();

        setRuntimeShapeDefinitionOptions((prev) => {
            const exists = prev.some((entry) => String(entry.name || '').trim().toLowerCase() === normalizedName.toLowerCase());
            if (exists) return prev;
            return [...prev, { id: normalizedId, name: normalizedName }].sort((a, b) => a.name.localeCompare(b.name));
        });

        toast({
            title: t.saveSuccessTitle || 'تم الحفظ',
            description: t.addProductShapeSuccess || 'تمت إضافة الشكل بنجاح.',
        });

        setProductShapeQuickAddOpen(false);
        setProductShapeQuickAddName('');
    };

    const persistListItem = (normalizedValues: any) => {
        startTransition(async () => {
            const result = isEditMode
                ? await handleUpdateListItem(itemType, item!.id, normalizedValues)
                : await handleAddListItem(itemType, normalizedValues);

            if (!('error' in result) || !result.error) {
                toast({ title: t.saveSuccessTitle, description: isEditMode ? t.updateSuccessDescription : t.addSuccessDescription });
                const createdItem = (result as any)?.item;
                if (!isEditMode && createdItem && onCreated) {
                    onCreated(createdItem);
                }
                if (typeof document !== 'undefined') {
                    (document.activeElement as HTMLElement | null)?.blur();
                }
                onFinished();
            } else {
                const details = (result as any)?.details;
                const serverFirstFieldError = details?.fieldErrors
                    ? Object.values(details.fieldErrors).find((entry: any) => Array.isArray(entry) && entry.length > 0)?.[0]
                    : undefined;
                const serverFirstFormError = Array.isArray(details?.formErrors) && details.formErrors.length > 0
                    ? details.formErrors[0]
                    : undefined;
                const validationSummary = (result as any)?.validationSummary;
                const errorDescription = validationSummary || serverFirstFieldError || serverFirstFormError || result.error;

                toast({ title: t.saveErrorTitle || 'خطأ', description: errorDescription, variant: "destructive" });
            }
        });
    };

    async function onSubmit(values: any) {
        const normalizedValues = { ...values };
        if (itemType === 'material') {
            const normalizedCategory = String(values.itemCategory || '').trim();
            normalizedValues.itemCategory = ['inventory', 'service', 'non_stock', 'bundle'].includes(normalizedCategory)
                ? normalizedCategory
                : 'inventory';

            // Auto-fill accounting fields for new items if left empty
            if (!isEditMode) {
                const isService = normalizedValues.itemCategory === 'service';
                const isInventory = normalizedValues.itemCategory === 'inventory' || normalizedValues.itemCategory === 'bundle';
                if (!String(normalizedValues.revenueAccountCode || '').trim()) {
                    normalizedValues.revenueAccountCode = isService ? '4140' : '4110';
                }
                if (!String(normalizedValues.inventoryAccountCode || '').trim()) {
                    normalizedValues.inventoryAccountCode = isInventory ? '1170' : '';
                }
                if (!String(normalizedValues.cogsAccountCode || '').trim()) {
                    normalizedValues.cogsAccountCode = isService ? '' : '5110';
                }
                if (!String(normalizedValues.purchaseAccountCode || '').trim()) {
                    normalizedValues.purchaseAccountCode = isService ? '' : '5110';
                }
            }

            normalizedValues.reorderMinimumQty = values.reorderMinimumQty === '' || values.reorderMinimumQty === undefined
                ? undefined
                : Math.max(0, Number(values.reorderMinimumQty));
            normalizedValues.reorderUnit = String(values.reorderUnit || '').trim() || undefined;
            if (normalizedValues.reorderMinimumQty === undefined) {
                normalizedValues.reorderUnit = undefined;
            }
            if (normalizedValues.reorderMinimumQty !== undefined && !normalizedValues.reorderUnit) {
                toast({
                    title: t?.validationError ?? 'خطأ في التحقق',
                    description: t?.reorderUnitRequired || 'يرجى اختيار وحدة إعادة الطلب عند تحديد الحد الأدنى.',
                    variant: 'destructive',
                });
                return;
            }

            const rawBarcode = String(values.barcode || '').trim();
            if (!rawBarcode) {
                const now = new Date();
                const pad = (num: number) => String(num).padStart(2, '0');
                const base = `A${pad(now.getDate())}${pad(now.getMonth() + 1)}${now.getFullYear()}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
                const materialItems = items as ProductionItem[];
                const isBarcodeTaken = (code: string) => materialItems.some((item) => {
                    const allSecondaryUnitCodes = Array.isArray((item as any).secondaryUnits)
                        ? (item as any).secondaryUnits.map((entry: any) => entry?.barcode).filter(Boolean)
                        : [];
                    const allCodes = [item.barcode, item.secondaryBarcode, ...(item.additionalBarcodes || []), ...allSecondaryUnitCodes].filter(Boolean) as string[];
                    return allCodes.includes(code);
                });
                let generated = base;
                let counter = 1;
                while (isBarcodeTaken(generated)) {
                    generated = `${base}${String(counter).padStart(2, '0')}`;
                    counter += 1;
                }
                normalizedValues.barcode = generated;
            } else {
                normalizedValues.barcode = rawBarcode;
            }
            if (Array.isArray(normalizedValues.additionalBarcodes)) {
                normalizedValues.additionalBarcodes = normalizedValues.additionalBarcodes.filter((code: string) => code && code.trim().length > 0);
                if (normalizedValues.additionalBarcodes.length === 0) {
                    delete normalizedValues.additionalBarcodes;
                }
            }
            if (!normalizedValues.groupId) {
                delete normalizedValues.groupId;
            }
            if (!normalizedValues.imageUrl) {
                delete normalizedValues.imageUrl;
            }
            const normalizedSecondaryUnits = (Array.isArray(values.secondaryUnits) ? values.secondaryUnits : [])
                .map((entry: any) => {
                    const unit = String(entry?.unit || '').trim();
                    const barcode = String(entry?.barcode || '').trim();
                    const quantity = entry?.quantity === '' || entry?.quantity === undefined ? undefined : Number(entry.quantity);
                    const price = entry?.price === '' || entry?.price === undefined ? undefined : Number(entry.price);
                    return { unit, barcode, quantity, price };
                })
                .filter((entry: any) => entry.unit || entry.barcode || typeof entry.quantity === 'number' || typeof entry.price === 'number');

            if (normalizedSecondaryUnits.length === 0) {
                delete normalizedValues.secondaryUnits;
                delete normalizedValues.secondaryUnit;
                delete normalizedValues.secondaryBarcode;
                delete normalizedValues.secondaryUnitQuantity;
                delete normalizedValues.secondaryUnitPrice;
            } else {
                normalizedValues.secondaryUnits = normalizedSecondaryUnits;
                const firstSecondary = normalizedSecondaryUnits[0];
                normalizedValues.secondaryUnit = firstSecondary.unit || undefined;
                normalizedValues.secondaryBarcode = firstSecondary.barcode || undefined;
                normalizedValues.secondaryUnitQuantity = typeof firstSecondary.quantity === 'number' ? firstSecondary.quantity : undefined;
                normalizedValues.secondaryUnitPrice = typeof firstSecondary.price === 'number' ? firstSecondary.price : undefined;
            }

            const selfId = String(values.itemNumber || item?.id || '').trim();
            const normalizedAlternativeIds = Array.from(new Set((Array.isArray(values.alternativeItemIds) ? values.alternativeItemIds : [])
                .map((altId: any) => String(altId || '').trim())
                .filter((altId: string) => altId && altId !== selfId)));
            normalizedValues.alternativeItemIds = normalizedAlternativeIds;

            if (values.enableCustomTax) {
                normalizedValues.usesDefaultTax = false;
                if (values.customTaxValue === '' || values.customTaxValue === undefined) {
                    normalizedValues.taxRate = 0;
                } else {
                    normalizedValues.taxRate = Number(values.customTaxValue);
                }
            } else {
                normalizedValues.usesDefaultTax = true;
                delete normalizedValues.taxRate;
            }

            if (!values.enableProfitMargin) {
                normalizedValues.enableProfitMargin = false;
                delete normalizedValues.profitMargin;
            } else {
                normalizedValues.enableProfitMargin = true;
                normalizedValues.profitMargin = values.profitMargin === '' || values.profitMargin === undefined
                    ? 0
                    : Number(values.profitMargin);
            }

            if ((values.salePrice === '' || values.salePrice === undefined || Number(values.salePrice) <= 0) && values.enableProfitMargin) {
                const purchasePrice = values.purchasePrice === '' || values.purchasePrice === undefined ? 0 : Number(values.purchasePrice);
                const marginPercent = values.profitMargin === '' || values.profitMargin === undefined ? 0 : Number(values.profitMargin);
                if (Number.isFinite(purchasePrice) && purchasePrice > 0) {
                    normalizedValues.salePrice = roundTo2(purchasePrice * (1 + (Number.isFinite(marginPercent) ? (marginPercent / 100) : 0)));
                } else {
                    normalizedValues.salePrice = 0.01;
                }
            }

            if (values.isManufactured) {
                const outputQuantity = values.productionOutputQuantity === '' || values.productionOutputQuantity === undefined
                    ? 1
                    : Number(values.productionOutputQuantity);

                const normalizedFormula = (Array.isArray(values.productionFormula) ? values.productionFormula : [])
                    .map((entry: any) => ({
                        materialId: String(entry?.materialId || '').trim(),
                        quantity: entry?.quantity === '' || entry?.quantity === undefined ? 0 : Number(entry.quantity),
                        unit: String(entry?.unit || '').trim() || undefined,
                        notes: String(entry?.notes || '').trim() || undefined,
                        wastePercent: entry?.wastePercent === '' || entry?.wastePercent === undefined ? undefined : Number(entry.wastePercent),
                    }))
                    .filter((entry: any) => entry.materialId && Number.isFinite(entry.quantity) && entry.quantity > 0);

                normalizedValues.isManufactured = true;
                normalizedValues.productionOutputQuantity = Number.isFinite(outputQuantity) && outputQuantity > 0 ? outputQuantity : 1;
                normalizedValues.productionFormula = normalizedFormula;
            } else {
                normalizedValues.isManufactured = false;
                delete normalizedValues.productionOutputQuantity;
                normalizedValues.productionFormula = [];
            }

            if (values.isDisassemblable) {
                const normalizedDisassemblyTemplate = (Array.isArray(values.disassemblyTemplate) ? values.disassemblyTemplate : [])
                    .map((entry: any) => ({
                        partItemId: String(entry?.partItemId || '').trim(),
                        quantity: entry?.quantity === '' || entry?.quantity === undefined ? 0 : Number(entry.quantity),
                        expectedSalePrice: entry?.expectedSalePrice === '' || entry?.expectedSalePrice === undefined ? 0 : Number(entry.expectedSalePrice),
                        notes: String(entry?.notes || '').trim() || undefined,
                    }))
                    .filter((entry: any) => entry.partItemId && Number.isFinite(entry.quantity) && entry.quantity > 0);

                normalizedValues.isDisassemblable = true;
                normalizedValues.disassemblyTemplate = normalizedDisassemblyTemplate;
            } else {
                normalizedValues.isDisassemblable = false;
                normalizedValues.disassemblyTemplate = [];
            }

            const normalizedShelfLifeYears = values.shelfLifeYears === '' || values.shelfLifeYears === undefined
                ? undefined
                : (() => {
                    const parsed = Number(values.shelfLifeYears);
                    return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : undefined;
                })();
            const normalizedShelfLifeMonths = values.shelfLifeMonths === '' || values.shelfLifeMonths === undefined
                ? undefined
                : (() => {
                    const parsed = Number(values.shelfLifeMonths);
                    return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : undefined;
                })();
            const normalizedShelfLifeDays = values.shelfLifeDays === '' || values.shelfLifeDays === undefined
                ? undefined
                : (() => {
                    const parsed = Number(values.shelfLifeDays);
                    return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : undefined;
                })();

            normalizedValues.shelfLifeYears = normalizedShelfLifeYears;
            normalizedValues.shelfLifeMonths = normalizedShelfLifeMonths;
            normalizedValues.shelfLifeDays = normalizedShelfLifeDays;

            normalizedValues.storeSectionId = String(values.storeSectionId || '').trim() || undefined;
            normalizedValues.storeBranchId = String(values.storeBranchId || '').trim() || undefined;
            normalizedValues.storeEnabled = Boolean(values.storeEnabled ?? false);
            normalizedValues.printSectionId = String(values.printSectionId || '').trim() || undefined;
            normalizedValues.excludeFromPrepTicket = values.excludeFromPrepTicket === true;
            normalizedValues.printLabelOverride = String(values.printLabelOverride || '').trim() || undefined;
            normalizedValues.globalReferenceNumber = String((values as any).globalReferenceNumber || '').trim() || undefined;

            delete normalizedValues.enableCustomTax;
            delete normalizedValues.customTaxValue;

            if (values.usesProductShapes) {
                if (runtimeShapeDefinitionOptions.length === 0) {
                    toast({
                        title: t.saveErrorTitle || 'خطأ',
                        description: t.noProductShapeDefinitions || 'لا توجد بيانات في إدارة الاحجام و الاشكال. أضف القيم أولاً.',
                        variant: 'destructive',
                    });
                    return;
                }

                const sourceShapes = Array.isArray(values.productShapes) ? values.productShapes : [];
                const hasEmptyShapeSelection = sourceShapes.some((shape: any) => String(shape?.name || '').trim().length === 0);
                if (hasEmptyShapeSelection) {
                    toast({
                        title: t.validationError || 'خطأ في التحقق',
                        description: t.productShapeSelectionRequired || 'يرجى اختيار اسم الشكل لكل صف قبل الحفظ.',
                        variant: 'destructive',
                    });
                    return;
                }

                const shapeType = String(values.productShapeType || '').trim();
                const normalizedShapes = (Array.isArray(values.productShapes) ? values.productShapes : [])
                    .map((shape: any, index: number) => ({
                        id: String(shape?.id || `shape-${Date.now()}-${index}`),
                        name: String(shape?.name || '').trim(),
                        salePrice: Number(shape?.salePrice ?? 0),
                        costPrice: shape?.costPrice === '' || shape?.costPrice === undefined ? undefined : Number(shape?.costPrice),
                        type: String(shape?.type || shapeType || '').trim() || undefined,
                        isActive: shape?.isActive !== false,
                    }))
                    .filter((shape: any) => shape.name.length > 0);

                normalizedValues.productShapeType = shapeType || undefined;
                normalizedValues.productShapes = normalizedShapes;
            } else {
                delete normalizedValues.productShapeType;
                normalizedValues.productShapes = [];
            }

            const normalizedSalePrice = Number(normalizedValues.salePrice ?? values.salePrice ?? 0);
            const normalizedPurchasePrice = Number(normalizedValues.purchasePrice ?? values.purchasePrice ?? 0);

            const violatingSecondaryRow = (Array.isArray(normalizedValues.secondaryUnits) ? normalizedValues.secondaryUnits : [])
                .map((entry: any) => {
                    const unitLabel = String(entry?.unit || '').trim();
                    const unitQty = Number(entry?.quantity || 0);
                    const unitSalePrice = Number(entry?.price || 0);
                    const unitCost = Number.isFinite(unitQty) && unitQty > 0
                        ? (normalizedPurchasePrice / unitQty)
                        : 0;
                    return { unitLabel, unitQty, unitSalePrice, unitCost };
                })
                .find((row: any) => (
                    Number.isFinite(row.unitSalePrice)
                    && Number.isFinite(row.unitCost)
                    && row.unitQty > 0
                    && row.unitSalePrice < row.unitCost
                ));

            if (violatingSecondaryRow) {
                setPendingNormalizedValues(normalizedValues);
                setLowPriceComparison({
                    salePrice: violatingSecondaryRow.unitSalePrice,
                    purchasePrice: violatingSecondaryRow.unitCost,
                    isSecondary: true,
                    unitLabel: violatingSecondaryRow.unitLabel || undefined,
                });
                setLowPriceWarningOpen(true);
                return;
            }

            if (
                Number.isFinite(normalizedSalePrice)
                && Number.isFinite(normalizedPurchasePrice)
                && normalizedSalePrice < normalizedPurchasePrice
            ) {
                setPendingNormalizedValues(normalizedValues);
                setLowPriceComparison({ salePrice: normalizedSalePrice, purchasePrice: normalizedPurchasePrice });
                setLowPriceWarningOpen(true);
                return;
            }
        }
        persistListItem(normalizedValues);
    }
    
    const contentProps = asPage ? {} : {
        onOpenAutoFocus: (event: Event) => {
            if (itemType !== 'material') return;
            event.preventDefault();
            setTimeout(() => {
                if (focusSalePrice) {
                    salePriceRef.current?.focus();
                    salePriceRef.current?.select();
                    return;
                }
                materialNameRef.current?.focus();
                materialNameRef.current?.select();
            }, 0);
        },
    };
    const ContentWrapper: React.ElementType = asPage ? 'div' : DialogContent;
    const contentClassName = asPage
        ? 'w-full'
        : 'max-h-[85vh] overflow-y-auto w-[97vw] max-w-6xl';
    return (
        <ContentWrapper
            className={contentClassName}
            aria-labelledby={dialogTitleId}
            aria-describedby={dialogDescriptionId}
            {...contentProps}
        >
            {asPage ? (
                <>
                    <h2 id={dialogTitleId} className="sr-only">{dialogTitleText}</h2>
                    <p id={dialogDescriptionId} className="sr-only">{dialogDescriptionText}</p>
                </>
            ) : (
                <DialogHeader>
                    <DialogTitle id={dialogTitleId}>{dialogTitleText}</DialogTitle>
                    <DialogDescription id={dialogDescriptionId}>{dialogDescriptionText}</DialogDescription>
                </DialogHeader>
            )}
                        <Form {...form}>
                                <form
                                    onSubmit={form.handleSubmit(onSubmit, () => {
                                        const firstErrorInfo = getFirstErrorInfo(form.formState.errors);
                                        const firstError = formatValidationError(firstErrorInfo);

                                        if (firstErrorInfo?.path) {
                                            try {
                                                form.setFocus(firstErrorInfo.path as any);
                                            } catch {
                                                // Some dynamic paths may not be focusable; keep toast as fallback.
                                            }
                                        }

                                        toast({
                                            title: t?.validationError ?? 'خطأ في التحقق',
                                            description: firstError || (t?.requiredFieldsNote ?? 'يرجى تعبئة الحقول الإلزامية المعلّمة بعلامة *.'),
                                            variant: 'destructive',
                                        });
                                    })}
                                    className="space-y-4"
                                >
                                        <p className="text-xs text-muted-foreground">
                                            {t?.requiredFieldsNote ?? 'الحقول المشار إليها بعلامة * إلزامية.'}
                                        </p>
                                        {itemType === 'material' && (
                      <>
                      <div className={`sticky top-0 z-10 border backdrop-blur supports-[backdrop-filter]:bg-background/80 ${asPage ? 'rounded-xl bg-gradient-to-r from-indigo-50/95 via-blue-50/70 to-sky-50/90 dark:from-indigo-950/60 dark:via-blue-950/40 dark:to-sky-950/50 border-indigo-200/70 dark:border-indigo-700/50 shadow-md p-4' : 'rounded-md bg-background/95 p-3'}`}>
                        <div className="grid grid-cols-1 gap-3 md:grid-cols-[2cm_minmax(0,1fr)_minmax(180px,220px)] md:items-end">
                          <FormField control={form.control} name="itemNumber" render={({ field }) => (
                              <FormItem>
                                  <FormLabel>
                                      {t.itemNumberLabel || 'رقم الصنف'}
                                      <span className="text-destructive"> *</span>
                                  </FormLabel>
                                  <FormControl><Input {...field} readOnly value={field.value || nextItemNumber} className="w-[2cm] min-w-[2cm]" /></FormControl>
                                  <FormMessage />
                              </FormItem>
                          )} />
                          <FormField control={form.control} name="name" render={({ field }) => (
                              <FormItem>
                                  <FormLabel>
                                      {t.itemNameLabel}
                                      <span className="text-destructive"> *</span>
                                  </FormLabel>
                                  <FormControl>
                                      <Input
                                          {...field}
                                          ref={(element) => {
                                              field.ref(element);
                                              materialNameRef.current = element;
                                          }}
                                      />
                                  </FormControl>
                                  <FormMessage />
                              </FormItem>
                          )} />
                          <FormField control={form.control} name="itemCategory" render={({ field }) => (
                              <FormItem>
                                  <FormLabel>{t.itemCategoryLabel || 'نوع الصنف'}</FormLabel>
                                  <Select value={field.value || 'inventory'} onValueChange={(value) => {
                                      field.onChange(value);
                                      applyCategoryDefaultAccounts(value);
                                  }}>
                                      <FormControl>
                                          <SelectTrigger>
                                              <SelectValue placeholder={t.itemCategoryPlaceholder || 'اختر نوع الصنف'} />
                                          </SelectTrigger>
                                      </FormControl>
                                      <SelectContent>
                                          <SelectItem value="inventory">{t.itemCategoryInventory || 'صنف مخزني'}</SelectItem>
                                          <SelectItem value="service">{t.itemCategoryService || 'خدمة'}</SelectItem>
                                          <SelectItem value="non_stock">{t.itemCategoryNonStock || 'صنف غير مخزني'}</SelectItem>
                                          <SelectItem value="bundle">{t.itemCategoryBundle || 'باقة/تجميعي'}</SelectItem>
                                      </SelectContent>
                                  </Select>
                                  <FormMessage />
                              </FormItem>
                          )} />
                        </div>
                      </div>
                      <Tabs value={materialActiveTab} onValueChange={setMaterialActiveTab} className="w-full">
                                                <TabsList className={`w-full justify-start ${asPage ? 'flex-wrap h-auto overflow-visible' : 'flex-nowrap overflow-x-auto overflow-y-hidden'} [&>button]:shrink-0 ${asPage ? 'bg-gradient-to-r from-violet-50 to-blue-50 dark:from-violet-950/30 dark:to-blue-950/30 border border-violet-200/60 dark:border-violet-800/40 p-1.5 rounded-xl gap-0.5 [&>[data-state=active]]:bg-white dark:[&>[data-state=active]]:bg-slate-900 [&>[data-state=active]]:text-violet-700 dark:[&>[data-state=active]]:text-violet-400 [&>[data-state=active]]:shadow-sm [&>[data-state=active]]:font-semibold' : ''}`}>
                          <TabsTrigger value="general">{t.generalTabLabel || 'تفاصيل عامة'}</TabsTrigger>
                          <TabsTrigger value="barcodes">{t.barcodesTabLabel || 'الباركود'}</TabsTrigger>
                                                    <TabsTrigger value="alternatives">{t.alternativesTabLabel || 'البدائل'}</TabsTrigger>
                                                    <TabsTrigger value="production-formula">{t.productionFormulaTabLabel || 'معادلة الإنتاج'}</TabsTrigger>
                                                    <TabsTrigger value="disassembly-parts">{t.disassemblyTabLabel || 'أجزاء التفكيك'}</TabsTrigger>
                          <TabsTrigger value="units">{t.unitsAndPricesTabLabel || 'الوحدات والأسعار'}</TabsTrigger>
                                                    <TabsTrigger value="reorder">{t.reorderTabLabel || 'إعادة الطلب'}</TabsTrigger>
                                                    <TabsTrigger value="product-shapes">{t.productShapesTabLabel || 'أشكال المنتج'}</TabsTrigger>
                                                    <TabsTrigger value="printing">{t.printingTabLabel || 'الطباعة'}</TabsTrigger>
                                                    <TabsTrigger value="real-estate">{t.realEstateProjectsTitle || 'الربط العقاري'}</TabsTrigger>
                                                    <TabsTrigger value="store">{t.storeTabLabel || 'المتجر'}</TabsTrigger>
                                                                                                        <TabsTrigger value="additional-details">{t.additionalDetailsTabLabel || 'تفاصيل اضافيه'}</TabsTrigger>
                                                                                                        <TabsTrigger value="accounting">{'المحاسبة'}</TabsTrigger>
                        </TabsList>

                        <TabsContent value="general" className="space-y-4">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <FormField control={form.control} name="itemSymbolName" render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t.itemSymbolNameLabel || 'اسم رمز الصنف'}</FormLabel>
                                    <FormControl><Input {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="globalReferenceNumber" render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t.globalReferenceNumberLabel || 'رقم مرجع عالمي'}</FormLabel>
                                    <FormControl><Input {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )} />
                          </div>
                                                    {itemGroups && itemGroups.length > 0 && (
                                                        <FormField control={form.control} name="groupId" render={({ field }) => (
                                                            <FormItem>
                                                                <FormLabel>{t.itemGroupLabel || 'مجموعة الصنف'}</FormLabel>
                                                                <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                                                    <FormControl>
                                                                        <SelectTrigger>
                                                                            <SelectValue placeholder={t.itemGroupPlaceholder || 'اختر مجموعة...'} />
                                                                        </SelectTrigger>
                                                                    </FormControl>
                                                                    <SelectContent>
                                                                        <SelectItem value="none">{t.itemGroupNone || 'بدون مجموعة'}</SelectItem>
                                                                        {itemGroups.map((group) => (
                                                                            <SelectItem key={group.id} value={group.id}>{group.name}</SelectItem>
                                                                        ))}
                                                                    </SelectContent>
                                                                </Select>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )} />
                                                    )}
                                                    {realEstateProjectOptions.length > 0 && (
                                                        <div className="rounded-md border p-3 space-y-3">
                                                            <div>
                                                                <p className="text-sm font-medium">{t.realEstateProjectsTitle || 'الربط العقاري الافتراضي'}</p>
                                                                <p className="text-xs text-muted-foreground">{t.realEstateProjectsDescription || 'حدد المشروع العقاري والوحدة ونوع التحميل لاستخدامها كقيمة افتراضية عند تسجيل الكلفة.'}</p>
                                                            </div>
                                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                <FormField control={form.control} name="realEstateCostType" render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.costTypeLabel || 'نوع التحميل'}</FormLabel>
                                                                        <Select value={field.value || 'general'} onValueChange={field.onChange}>
                                                                            <FormControl>
                                                                                <SelectTrigger>
                                                                                    <SelectValue placeholder={t.costTypeLabel || 'نوع التحميل'} />
                                                                                </SelectTrigger>
                                                                            </FormControl>
                                                                            <SelectContent>
                                                                                <SelectItem value="general">{t.generalLabel || 'عام'}</SelectItem>
                                                                                <SelectItem value="direct-unit">{t.directCostLabel || 'تكلفة مباشرة على وحدة'}</SelectItem>
                                                                                <SelectItem value="shared-project">{t.sharedCostsTitle || 'تكلفة مشتركة على المشروع'}</SelectItem>
                                                                            </SelectContent>
                                                                        </Select>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                <FormField control={form.control} name="realEstateProjectId" render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.realEstateProjectsTitle || 'المشروع العقاري'}</FormLabel>
                                                                        <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                                                            <FormControl>
                                                                                <SelectTrigger>
                                                                                    <SelectValue placeholder={t.projectNameLabel || 'اختر المشروع'} />
                                                                                </SelectTrigger>
                                                                            </FormControl>
                                                                            <SelectContent>
                                                                                <SelectItem value="none">{t.itemGroupNone || 'بدون ربط'}</SelectItem>
                                                                                {realEstateProjectOptions.map((project) => (
                                                                                    <SelectItem key={project.id} value={project.id}>{project.name}</SelectItem>
                                                                                ))}
                                                                            </SelectContent>
                                                                        </Select>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                {selectedRealEstateCostType === 'direct-unit' && (
                                                                    <FormField control={form.control} name="realEstateUnitId" render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormLabel>{t.unitNameLabel || 'الوحدة العقارية'}</FormLabel>
                                                                            <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)} disabled={!selectedRealEstateProjectId}>
                                                                                <FormControl>
                                                                                    <SelectTrigger>
                                                                                        <SelectValue placeholder={t.unitNamePlaceholder || 'اختر الوحدة'} />
                                                                                    </SelectTrigger>
                                                                                </FormControl>
                                                                                <SelectContent>
                                                                                    <SelectItem value="none">{t.itemGroupNone || 'بدون تحديد'}</SelectItem>
                                                                                    {selectedRealEstateUnits.map((unit: any) => (
                                                                                        <SelectItem key={unit.id} value={unit.id}>{unit.name || unit.unitCode}</SelectItem>
                                                                                    ))}
                                                                                </SelectContent>
                                                                            </Select>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )} />
                                                                )}
                                                                {selectedRealEstateCostType === 'shared-project' && (
                                                                    <FormField control={form.control} name="realEstateAllocationMethod" render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormLabel>{t.allocationMethodLabel || 'أساس التوزيع'}</FormLabel>
                                                                            <Select value={field.value || 'area'} onValueChange={field.onChange}>
                                                                                <FormControl>
                                                                                    <SelectTrigger>
                                                                                        <SelectValue placeholder={t.allocationMethodLabel || 'أساس التوزيع'} />
                                                                                    </SelectTrigger>
                                                                                </FormControl>
                                                                                <SelectContent>
                                                                                    <SelectItem value="area">{t.allocateByAreaLabel || 'حسب المساحة'}</SelectItem>
                                                                                    <SelectItem value="sale-value">{t.allocateBySaleValueLabel || 'حسب القيمة البيعية'}</SelectItem>
                                                                                    <SelectItem value="manual-share">{t.allocateByManualShareLabel || 'حسب النسبة اليدوية'}</SelectItem>
                                                                                </SelectContent>
                                                                            </Select>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )} />
                                                                )}
                                                            </div>
                                                        </div>
                                                    )}
                                                    <div className="rounded-md border p-3 space-y-3">
                                                        <div>
                                                            <p className="text-sm font-medium">{t.shelfLifeSectionLabel || 'الصلاحية'}</p>
                                                            <p className="text-xs text-muted-foreground">{t.shelfLifeSectionHint || 'حدد مدة صلاحية المنتج (سنة / شهر / يوم) ليظهر في تقرير فحص الصلاحية وفق FIFO.'}</p>
                                                        </div>
                                                        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                                                            <FormField control={form.control} name="shelfLifeYears" render={({ field }) => (
                                                                <FormItem>
                                                                    <FormLabel>{t.shelfLifeYearsLabel || 'سنوات'}</FormLabel>
                                                                    <FormControl><Input type="number" min={0} step="1" {...field} value={field.value ?? ''} /></FormControl>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                            <FormField control={form.control} name="shelfLifeMonths" render={({ field }) => (
                                                                <FormItem>
                                                                    <FormLabel>{t.shelfLifeMonthsLabel || 'أشهر'}</FormLabel>
                                                                    <FormControl><Input type="number" min={0} step="1" {...field} value={field.value ?? ''} /></FormControl>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                            <FormField control={form.control} name="shelfLifeDays" render={({ field }) => (
                                                                <FormItem>
                                                                    <FormLabel>{t.shelfLifeDaysLabel || 'أيام'}</FormLabel>
                                                                    <FormControl><Input type="number" min={0} step="1" {...field} value={field.value ?? ''} /></FormControl>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                        </div>
                                                    </div>
                                                    <FormField control={form.control} name="imageUrl" render={({ field }) => (
                                                            <FormItem>
                                                                    <FormLabel>{t.itemImageLabel || 'صورة الصنف (رابط)'}</FormLabel>
                                                                    <FormControl>
                                                                        <Input
                                                                            {...field}
                                                                            placeholder="https://"
                                                                            onPaste={(e) => {
                                                                                const clipboardItems = e.clipboardData?.items || [];
                                                                                const imageItem = Array.from(clipboardItems).find((item) => item.type.startsWith('image/'));
                                                                                if (imageItem) {
                                                                                    const file = imageItem.getAsFile();
                                                                                    if (file) {
                                                                                        const reader = new FileReader();
                                                                                        reader.onload = () => {
                                                                                            const result = typeof reader.result === 'string' ? reader.result : '';
                                                                                            if (result) {
                                                                                                form.setValue('imageUrl', result, { shouldValidate: true, shouldDirty: true });
                                                                                            }
                                                                                        };
                                                                                        reader.readAsDataURL(file);
                                                                                        e.preventDefault();
                                                                                        return;
                                                                                    }
                                                                                }

                                                                                const text = e.clipboardData.getData('text');
                                                                                if (text) {
                                                                                    form.setValue('imageUrl', text, { shouldValidate: true, shouldDirty: true });
                                                                                    e.preventDefault();
                                                                                }
                                                                            }}
                                                                        />
                                                                    </FormControl>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {t.itemImagePasteHint || 'يمكنك لصق صورة مباشرة من الحافظة أو لصق رابط.'}
                                                                    </p>
                                                                    {watchedImageUrl ? (
                                                                        <div className="mt-2 rounded-md border p-2 bg-muted/30">
                                                                            <div className="text-xs text-muted-foreground mb-2">{t.itemImagePreviewLabel || 'معاينة الصورة'}</div>
                                                                            <img
                                                                                src={watchedImageUrl}
                                                                                alt={t.itemImageAlt || 'معاينة الصنف'}
                                                                                className="h-32 w-32 object-cover rounded-md border"
                                                                                onError={(e) => {
                                                                                    (e.currentTarget as HTMLImageElement).style.display = 'none';
                                                                                }}
                                                                            />
                                                                        </div>
                                                                    ) : null}
                                                                    <FormMessage />
                                                            </FormItem>
                                                    )} />
                        </TabsContent>

                        <TabsContent value="alternatives" className="space-y-4">
                            <FormField
                                control={form.control}
                                name="alternativeItemIds"
                                render={({ field }) => {
                                    const selectedSet = new Set((Array.isArray(field.value) ? field.value : []).map((id: any) => String(id || '').trim()).filter(Boolean));
                                    const notSelectedSuggestions = smartAlternativeSuggestions.filter((entry) => !selectedSet.has(entry.id));
                                    const selectedAlternatives = materialAlternativeOptions.filter((entry) => selectedSet.has(String(entry.id || '').trim()));
                                    const manualOptions = materialAlternativeOptions.filter((entry) => !selectedSet.has(String(entry.id || '').trim()));
                                    const filteredManualOptions = manualOptions.filter((alt) => matchesAdvancedAlternativeSearch(alt, manualAlternativeQuery));
                                    return (
                                        <FormItem>
                                            <FormLabel>{t?.alternativeItemsLabel || 'الأصناف البديلة'}</FormLabel>
                                            <div className="rounded-md border p-3 space-y-3">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <Button type="button" variant="outline" size="sm" onClick={runSmartAlternativeSuggestion}>
                                                        {t?.smartSuggestAlternatives || 'اقتراح بدائل ذكي'}
                                                    </Button>
                                                    {notSelectedSuggestions.length > 0 && (
                                                        <Button
                                                            type="button"
                                                            size="sm"
                                                            onClick={() => {
                                                                const next = new Set(selectedSet);
                                                                notSelectedSuggestions.forEach((entry) => next.add(entry.id));
                                                                field.onChange(Array.from(next));
                                                            }}
                                                        >
                                                            {t?.addAllSuggestedAlternatives || 'إضافة كل المقترحات'}
                                                        </Button>
                                                    )}
                                                </div>

                                                {smartSuggestionTried && smartAlternativeSuggestions.length === 0 && (
                                                    <p className="text-xs text-muted-foreground">{t?.noSmartAlternativeMatches || 'لا توجد بدائل مقترحة بنسبة تطابق 70% أو أكثر.'}</p>
                                                )}

                                                {smartAlternativeSuggestions.length > 0 && (
                                                    <div className="space-y-2">
                                                        <p className="text-xs font-medium text-muted-foreground">{t?.smartSuggestionsList || 'مقترحات ذكية'}</p>
                                                        <div className="max-h-44 overflow-y-auto space-y-2">
                                                            {smartAlternativeSuggestions.map((entry) => {
                                                                const isAlreadySelected = selectedSet.has(entry.id);
                                                                const detailsPreview = String(entry.additionalDetails || '')
                                                                    .split(/\r?\n/)
                                                                    .map((line) => line.trim())
                                                                    .filter(Boolean)
                                                                    .slice(0, 2)
                                                                    .join(' - ');
                                                                return (
                                                                    <div key={`suggest-${entry.id}`} className="flex items-center justify-between gap-2 rounded-md border p-2">
                                                                        <div className="min-w-0">
                                                                            <p className="text-sm truncate">{entry.name} <span className="text-xs text-muted-foreground">({entry.itemNumber || entry.id})</span></p>
                                                                            <p className="text-xs text-muted-foreground">{entry.reason} - {(entry.score * 100).toFixed(0)}%</p>
                                                                            {(entry.globalReferenceNumber || entry.itemSymbolName) && (
                                                                                <p className="text-xs text-muted-foreground truncate">
                                                                                    {entry.globalReferenceNumber ? `GRN: ${entry.globalReferenceNumber}` : ''}
                                                                                    {entry.globalReferenceNumber && entry.itemSymbolName ? ' | ' : ''}
                                                                                    {entry.itemSymbolName ? `SYMBOL: ${entry.itemSymbolName}` : ''}
                                                                                </p>
                                                                            )}
                                                                            {detailsPreview && (
                                                                                <p className="text-xs text-muted-foreground line-clamp-2">{detailsPreview}</p>
                                                                            )}
                                                                        </div>
                                                                        <div className="flex items-center gap-2">
                                                                            <Button
                                                                                type="button"
                                                                                variant="ghost"
                                                                                size="sm"
                                                                                onClick={() => {
                                                                                    const suggestionItem = materialAlternativeById.get(String(entry.id || '').trim());
                                                                                    if (!suggestionItem) return;
                                                                                    setSuggestionPreviewItem(suggestionItem);
                                                                                }}
                                                                            >
                                                                                {t?.previewLabel || 'معاينة'}
                                                                            </Button>
                                                                            <Button
                                                                                type="button"
                                                                                variant={isAlreadySelected ? 'secondary' : 'outline'}
                                                                                size="sm"
                                                                                onClick={() => {
                                                                                    const next = new Set(selectedSet);
                                                                                    if (isAlreadySelected) next.delete(entry.id);
                                                                                    else next.add(entry.id);
                                                                                    field.onChange(Array.from(next));
                                                                                }}
                                                                            >
                                                                                {isAlreadySelected ? (t?.removeSuggestion ?? 'إزالة') : (t?.addSuggestion ?? 'إضافة')}
                                                                            </Button>
                                                                        </div>
                                                                    </div>
                                                                );
                                                            })}
                                                        </div>
                                                    </div>
                                                )}
                                            </div>
                                            <div className="rounded-md border p-3 space-y-3">
                                                <p className="text-xs font-medium text-muted-foreground">{t?.selectedAlternativesLabel || 'البدائل المختارة'}</p>
                                                {selectedAlternatives.length === 0 && (
                                                    <p className="text-sm text-muted-foreground">{t?.noSelectedAlternatives ?? 'لا توجد بدائل مختارة.'}</p>
                                                )}
                                                {selectedAlternatives.length > 0 && (
                                                    <div className="max-h-52 overflow-y-auto space-y-2">
                                                        {selectedAlternatives.map((alt) => {
                                                            const altId = String(alt.id || '').trim();
                                                            return (
                                                                <div key={`selected-${altId}`} className="flex items-center justify-between gap-2 rounded-md border p-2">
                                                                    <div className="min-w-0 text-sm truncate">
                                                                        {alt.name} <span className="text-xs text-muted-foreground">({alt.itemNumber || alt.id})</span>
                                                                    </div>
                                                                    <Button
                                                                        type="button"
                                                                        variant="ghost"
                                                                        size="sm"
                                                                        onClick={() => {
                                                                            const next = new Set(selectedSet);
                                                                            next.delete(altId);
                                                                            field.onChange(Array.from(next));
                                                                        }}
                                                                    >
                                                                        {t?.removeSuggestion ?? 'إزالة'}
                                                                    </Button>
                                                                </div>
                                                            );
                                                        })}
                                                    </div>
                                                )}

                                                <div className="grid grid-cols-1 md:grid-cols-[1fr_auto] gap-2 items-end">
                                                    <div className="space-y-1">
                                                        <p className="text-xs font-medium text-muted-foreground">{t?.addAlternativeManually ?? 'إضافة بديل يدوي'}</p>
                                                        <Input
                                                            value={manualAlternativeQuery}
                                                            onChange={(event) => setManualAlternativeQuery(event.target.value)}
                                                            placeholder={t?.advancedSearchPlaceholder || 'بحث متقدم في جميع الأعمدة...'}
                                                            className="sm:max-w-lg"
                                                        />
                                                        <p className="text-xs text-muted-foreground">
                                                            {(t?.searchResultsCount ?? 'عدد النتائج')}: {filteredManualOptions.length}
                                                        </p>
                                                        {manualAlternativeQuery.trim() !== '' && (
                                                            <div className="max-h-36 overflow-y-auto rounded-md border p-2 space-y-1">
                                                                {filteredManualOptions.length === 0 && (
                                                                    <p className="text-xs text-muted-foreground">{t?.noSearchResults ?? 'لا توجد نتائج مطابقة.'}</p>
                                                                )}
                                                                {filteredManualOptions.map((alt) => (
                                                                    <button
                                                                        key={`manual-result-${alt.id}`}
                                                                        type="button"
                                                                        className="w-full text-start rounded px-2 py-1 text-sm hover:bg-muted"
                                                                        onClick={() => setManualAlternativeToAdd(String(alt.id))}
                                                                    >
                                                                        {alt.name} <span className="text-xs text-muted-foreground">({alt.itemNumber || alt.id})</span>
                                                                    </button>
                                                                ))}
                                                            </div>
                                                        )}
                                                        <Select value={manualAlternativeToAdd} onValueChange={setManualAlternativeToAdd}>
                                                            <SelectTrigger>
                                                                <SelectValue placeholder={t?.selectAlternativePlaceholder ?? 'اختر صنفًا لإضافته كبديل'} />
                                                            </SelectTrigger>
                                                            <SelectContent>
                                                                <SelectItem value="none">{t?.selectPlaceholder || 'اختر...'}</SelectItem>
                                                                {filteredManualOptions
                                                                    .map((alt) => (
                                                                    <SelectItem key={`manual-${alt.id}`} value={String(alt.id)}>{alt.name} ({alt.itemNumber || alt.id})</SelectItem>
                                                                ))}
                                                            </SelectContent>
                                                        </Select>
                                                    </div>
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        onClick={() => {
                                                            if (!manualAlternativeToAdd || manualAlternativeToAdd === 'none') return;
                                                            const next = new Set(selectedSet);
                                                            next.add(manualAlternativeToAdd);
                                                            field.onChange(Array.from(next));
                                                            setManualAlternativeToAdd('none');
                                                            setManualAlternativeQuery('');
                                                        }}
                                                    >
                                                        {t?.addSuggestion ?? 'إضافة'}
                                                    </Button>
                                                </div>
                                            </div>
                                            <p className="text-xs text-muted-foreground">
                                                {t?.alternativeItemsHint || 'عند اختيار بديل هنا، سيصبح هذا الصنف بديلًا للصنف الآخر تلقائيًا.'}
                                            </p>
                                            <FormMessage />
                                        </FormItem>
                                    );
                                }}
                            />
                        </TabsContent>

                        <TabsContent value="store" className="space-y-4">
                            <div className="rounded-md border p-3 space-y-3">
                                <div>
                                    <p className="text-sm font-medium">{t.storeSectionTitle || 'إعدادات الظهور في المتجر'}</p>
                                    <p className="text-xs text-muted-foreground">{t.storeSectionHint || 'اختر القسم والفرع الذي سيظهر فيه الصنف داخل المتجر لاحقًا.'}</p>
                                </div>
                                <FormField
                                    control={form.control}
                                    name="storeEnabled"
                                    render={({ field }) => (
                                        <FormItem className="flex items-center justify-between rounded-md border px-3 py-2">
                                            <div>
                                                <FormLabel className="text-sm font-medium">{t.storeEnabledLabel || 'إظهار في المتجر'}</FormLabel>
                                                <p className="text-xs text-muted-foreground">{t.storeEnabledHint || 'عند التفعيل يظهر الصنف فوراً في صفحة المتجر'}</p>
                                            </div>
                                            <FormControl>
                                                <Switch checked={!!field.value} onCheckedChange={field.onChange} />
                                            </FormControl>
                                        </FormItem>
                                    )}
                                />
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                    <FormField
                                        control={form.control}
                                        name="storeSectionId"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>{t.storeSectionLabel || 'القسم'}</FormLabel>
                                                <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder={t.storeSectionPlaceholder || 'اختر القسم...'} />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="none">{t.selectPlaceholder || 'اختر...'}</SelectItem>
                                                        {runtimeItemGroupOptions.map((group) => (
                                                            <SelectItem key={`store-section-${group.id}`} value={group.id}>{group.name}</SelectItem>
                                                        ))}
                                                        <div className="border-t mt-1 pt-1 px-2 pb-1" onPointerDown={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}>
                                                            <p className="text-xs text-muted-foreground mb-1">إضافة قسم جديد</p>
                                                            <div className="flex gap-1">
                                                                <Input
                                                                    value={storeSectionQuickName}
                                                                    onChange={(e) => setStoreSectionQuickName(e.target.value)}
                                                                    onPointerDown={(e) => e.stopPropagation()}
                                                                    onKeyDown={(e) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); saveQuickStoreSection(); } }}
                                                                    placeholder="اسم القسم..."
                                                                    className="h-7 text-xs"
                                                                />
                                                                <Button
                                                                    type="button"
                                                                    size="icon"
                                                                    variant="outline"
                                                                    className="h-7 w-7 shrink-0"
                                                                    disabled={isStoreSectionSaving || !storeSectionQuickName.trim()}
                                                                    onClick={(e) => { e.stopPropagation(); saveQuickStoreSection(); }}
                                                                >
                                                                    {isStoreSectionSaving ? <Loader2 className="h-3 w-3 animate-spin" /> : <PlusCircle className="h-3 w-3" />}
                                                                </Button>
                                                            </div>
                                                        </div>
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="storeBranchId"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>{t.storeBranchLabel || 'الفرع'}</FormLabel>
                                                <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder={t.storeBranchPlaceholder || 'اختر الفرع...'} />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="none">{t.selectPlaceholder || 'اختر...'}</SelectItem>
                                                        {warehouses.map((warehouse) => (
                                                            <SelectItem key={`store-branch-${warehouse.id}`} value={warehouse.id}>{warehouse.name}</SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                            </div>
                        </TabsContent>

                        <TabsContent value="production-formula" className="space-y-4">
                            <div className="rounded-md border p-3 space-y-3">
                                <FormField
                                    control={form.control}
                                    name="isManufactured"
                                    render={({ field }) => (
                                        <FormItem className="flex items-center justify-between rounded-md border p-3">
                                            <div className="space-y-1">
                                                <FormLabel>{t.isManufacturedLabel || 'صنف مُصنَّع (غير مشتَرى)'}</FormLabel>
                                                <p className="text-xs text-muted-foreground">{t.isManufacturedHint || 'عند التفعيل يمكنك تعريف مكونات معادلة الإنتاج لهذا الصنف.'}</p>
                                            </div>
                                            <FormControl>
                                                <Checkbox checked={!!field.value} onCheckedChange={(checked) => field.onChange(checked === true)} />
                                            </FormControl>
                                        </FormItem>
                                    )}
                                />

                                {form.watch('isManufactured') && (
                                    <>
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                            <FormField
                                                control={form.control}
                                                name="productionOutputQuantity"
                                                render={({ field }) => (
                                                    <FormItem>
                                                        <FormLabel>{t.productionOutputQuantityLabel || 'كمية الإنتاج الناتجة (للوصفة)'}</FormLabel>
                                                        <FormControl>
                                                            <Input type="number" min="0.0001" step="0.01" {...field} />
                                                        </FormControl>
                                                        <FormMessage />
                                                    </FormItem>
                                                )}
                                            />
                                        </div>

                                        <div className="space-y-2 rounded-md border p-3">
                                            <div className="flex items-center justify-between">
                                                <p className="text-xs font-medium text-muted-foreground">{t.productionFormulaRowsLabel || 'مكونات المعادلة'}</p>
                                                <Button
                                                    type="button"
                                                    size="sm"
                                                    variant="outline"
                                                    onClick={() => appendProductionFormula({ materialId: '', quantity: '', unit: '', notes: '', wastePercent: '' })}
                                                >
                                                    <PlusCircle className="mr-2 h-4 w-4" />
                                                    {t.addFormulaRowLabel || 'إضافة مكوّن'}
                                                </Button>
                                            </div>

                                            <div className="rounded-md bg-muted/40 p-2 text-xs text-muted-foreground flex flex-wrap gap-4">
                                                <span>{t.productionInputsCostLabel || 'تكلفة المدخلات'}: {formatCurrency(productionCostMeta.totalInputCost, currencySymbol)}</span>
                                                <span>{t.productionComputedUnitCostLabel || 'التكلفة المحسوبة للوحدة'}: {formatCurrency(productionCostMeta.computedUnitCost, currencySymbol)}</span>
                                                {productionCostMeta.unresolvedCount > 0 && (
                                                    <span className="text-destructive">{t.productionUnresolvedIngredientsLabel || 'مكونات بدون تكلفة شراء'}: {productionCostMeta.unresolvedCount}</span>
                                                )}
                                            </div>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                                                <div className="space-y-1">
                                                    <FormLabel>{t.productionInputsCostLabel || 'تكلفة المدخلات'}</FormLabel>
                                                    <Input readOnly value={formatCurrency(productionCostMeta.totalInputCost, currencySymbol)} />
                                                </div>
                                                <div className="space-y-1">
                                                    <FormLabel>{t.productionComputedUnitCostLabel || 'التكلفة المحسوبة للوحدة'}</FormLabel>
                                                    <Input readOnly value={formatCurrency(productionCostMeta.computedUnitCost, currencySymbol)} />
                                                </div>
                                            </div>
                                            <p className="text-xs text-muted-foreground">
                                                {t.productionUnitConversionHint || 'ملاحظة: إذا اخترت وحدة فرعية للمكوّن، سيتم تحويل الكمية تلقائيًا إلى ما يعادلها من الوحدة الرئيسية في حساب التكلفة.'}
                                            </p>

                                            {productionFormulaFields.length === 0 && (
                                                <div className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">
                                                    {t.noProductionFormulaRows || 'لا توجد مكونات مضافة بعد.'}
                                                </div>
                                            )}

                                            {productionFormulaFields.map((formulaField, index) => {
                                                const selectedMaterialId = String(form.getValues(`productionFormula.${index}.materialId`) || '').trim();
                                                const selectedMaterial = materialsById.get(selectedMaterialId);
                                                const availableUnits = collectMaterialAvailableUnits(selectedMaterial);
                                                const formulaQuantity = Number(form.getValues(`productionFormula.${index}.quantity`) || 0);
                                                const formulaUnit = String(form.getValues(`productionFormula.${index}.unit`) || '').trim();
                                                const quantityInPrimary = convertFormulaQuantityToPrimary(selectedMaterial, formulaUnit, formulaQuantity);
                                                const primaryUnitLabel = String(selectedMaterial?.primaryUnit || '').trim() || (t.primaryUnitLabel || 'الوحدة الرئيسية');

                                                return (
                                                <div
                                                    key={formulaField.id}
                                                    className="grid grid-cols-1 md:grid-cols-[minmax(180px,1.3fr)_minmax(110px,.9fr)_minmax(90px,.7fr)_minmax(90px,.7fr)_minmax(110px,.8fr)_minmax(150px,1fr)_44px] gap-2 items-start"
                                                >
                                                    <FormField
                                                        control={form.control}
                                                        name={`productionFormula.${index}.materialId`}
                                                        render={({ field }) => (
                                                            <FormItem className="space-y-1">
                                                                <FormLabel>{t.ingredientItemLabel || 'الصنف الخام'}</FormLabel>
                                                                <FormControl>
                                                                    <Select
                                                                        value={field.value || 'none'}
                                                                        onValueChange={(value) => {
                                                                            const nextMaterialId = value === 'none' ? '' : value;
                                                                            field.onChange(nextMaterialId);

                                                                            const materialForUnit = materialsById.get(nextMaterialId);
                                                                            const nextAvailableUnits = collectMaterialAvailableUnits(materialForUnit);
                                                                            const currentUnit = String(form.getValues(`productionFormula.${index}.unit`) || '').trim();
                                                                            const isCurrentValid = nextAvailableUnits.some((unit) => unit.toLowerCase() === currentUnit.toLowerCase());

                                                                            if (!isCurrentValid) {
                                                                                form.setValue(`productionFormula.${index}.unit`, nextAvailableUnits[0] || '', { shouldDirty: true });
                                                                            }
                                                                        }}
                                                                    >
                                                                        <SelectTrigger>
                                                                            <SelectValue placeholder={t.selectIngredientPlaceholder || 'اختر صنفًا'} />
                                                                        </SelectTrigger>
                                                                        <SelectContent>
                                                                            <SelectItem value="none">{t.selectPlaceholder || 'اختر...'}</SelectItem>
                                                                            {materialAlternativeOptions.map((mat) => (
                                                                                <SelectItem key={`formula-${mat.id}`} value={String(mat.id)}>
                                                                                    {mat.name} ({mat.itemNumber || mat.id})
                                                                                </SelectItem>
                                                                            ))}
                                                                        </SelectContent>
                                                                    </Select>
                                                                </FormControl>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )}
                                                    />

                                                    <FormField
                                                        control={form.control}
                                                        name={`productionFormula.${index}.unit`}
                                                        render={({ field }) => (
                                                            <FormItem className="space-y-1">
                                                                <FormLabel>{t.ingredientUnitLabel || 'الوحدة'}</FormLabel>
                                                                <FormControl>
                                                                    <Select
                                                                        value={field.value || 'none'}
                                                                        onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}
                                                                        disabled={!selectedMaterialId || availableUnits.length === 0}
                                                                    >
                                                                        <SelectTrigger>
                                                                            <SelectValue placeholder={t.secondaryUnitPlaceholder || 'الوحدة'} />
                                                                        </SelectTrigger>
                                                                        <SelectContent>
                                                                            <SelectItem value="none">{t.selectPlaceholder || 'اختر...'}</SelectItem>
                                                                            {availableUnits.map((unitValue) => (
                                                                                <SelectItem key={`${formulaField.id}-${unitValue}`} value={unitValue}>{unitValue}</SelectItem>
                                                                            ))}
                                                                        </SelectContent>
                                                                    </Select>
                                                                </FormControl>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )}
                                                    />

                                                    <FormField
                                                        control={form.control}
                                                        name={`productionFormula.${index}.quantity`}
                                                        render={({ field }) => (
                                                            <FormItem className="space-y-1">
                                                                <FormLabel>{t.ingredientQuantityLabel || 'الكمية'}</FormLabel>
                                                                <FormControl>
                                                                    <Input type="number" min="0.0001" step="0.01" {...field} />
                                                                </FormControl>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )}
                                                    />

                                                    <FormField
                                                        control={form.control}
                                                        name={`productionFormula.${index}.wastePercent`}
                                                        render={({ field }) => (
                                                            <FormItem className="space-y-1">
                                                                <FormLabel>{t.wastePercentLabel || 'هالك %'}</FormLabel>
                                                                <FormControl>
                                                                    <Input type="number" min="0" max="100" step="0.01" {...field} />
                                                                </FormControl>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )}
                                                    />

                                                    <div className="space-y-1">
                                                        <FormLabel>{t?.formulaLineCostLabel || 'تكلفة المكون'}</FormLabel>
                                                        <Input
                                                            readOnly
                                                            value={(() => {
                                                                const sourceCost = Number(selectedMaterial?.purchasePrice || 0);
                                                                const effectiveTaxRate = getMaterialEffectiveTaxRate(selectedMaterial);
                                                                const sourceCostInclTax = sourceCost * (1 + (effectiveTaxRate > 0 ? (effectiveTaxRate / 100) : 0));
                                                                const wastePercent = Number(form.getValues(`productionFormula.${index}.wastePercent`) || 0);
                                                                const wasteMultiplier = 1 + ((Number.isFinite(wastePercent) && wastePercent > 0) ? (wastePercent / 100) : 0);
                                                                const lineCost = Number.isFinite(sourceCostInclTax) && Number.isFinite(quantityInPrimary)
                                                                    ? (sourceCostInclTax * quantityInPrimary * wasteMultiplier)
                                                                    : 0;
                                                                return formatCurrency(lineCost, currencySymbol);
                                                            })()}
                                                        />
                                                    </div>

                                                    <FormField
                                                        control={form.control}
                                                        name={`productionFormula.${index}.notes`}
                                                        render={({ field }) => (
                                                            <FormItem className="space-y-1">
                                                                <FormLabel>{t.formulaLineNotesLabel || 'ملاحظات'}</FormLabel>
                                                                <FormControl>
                                                                    <Input {...field} placeholder={t.notesPlaceholder || 'ملاحظات'} />
                                                                </FormControl>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )}
                                                    />

                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="icon"
                                                        className="mt-1"
                                                        onClick={() => removeProductionFormula(index)}
                                                    >
                                                        <Trash2 className="h-4 w-4 text-destructive" />
                                                    </Button>
                                                    {selectedMaterialId && Number.isFinite(formulaQuantity) && formulaQuantity > 0 && (
                                                        <div className="md:col-span-6 text-[11px] text-muted-foreground">
                                                            {(t.productionRowConversionPreview || 'التحويل: {qty} {unit} = {primaryQty} {primaryUnit}')
                                                                .replace('{qty}', String(formulaQuantity))
                                                                .replace('{unit}', formulaUnit || (t.selectPlaceholder || 'اختر'))
                                                                .replace('{primaryQty}', Number.isFinite(quantityInPrimary) ? String(roundTo2(quantityInPrimary)) : '0')
                                                                .replace('{primaryUnit}', primaryUnitLabel)}
                                                        </div>
                                                    )}
                                                </div>
                                            )})}
                                        </div>
                                    </>
                                )}
                            </div>
                        </TabsContent>

                        <TabsContent value="disassembly-parts" className="space-y-4">
                            <div className="rounded-md border p-3 space-y-3">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm font-medium">{t.disassemblySectionTitle || 'قالب التفكيك'}</p>
                                        <p className="text-xs text-muted-foreground">
                                            {t.disassemblySectionDescription || 'حدّد الأجزاء الناتجة من هذا الصنف عند التفكيك مع الكمية المتوقعة وسعر البيع المرجعي لتوزيع التكلفة تلقائياً.'}
                                        </p>
                                    </div>
                                    <Button
                                        type="button"
                                        size="sm"
                                        variant="outline"
                                        disabled={!isDisassemblableValue}
                                        onClick={() => appendDisassemblyTemplate({ partItemId: '', quantity: 1, expectedSalePrice: '', notes: '' })}
                                    >
                                        <PlusCircle className="mr-2 h-4 w-4" />
                                        {t.addDisassemblyPartButton || 'إضافة جزء'}
                                    </Button>
                                </div>

                                {!isDisassemblableValue && (
                                    <div className="rounded-md border border-dashed bg-muted/30 p-3 text-xs text-muted-foreground">
                                        {t.disassemblyDisabledHint || 'فعّل خيار "الصنف قابل للتفكيك" أولاً من خيارات التفعيل ليصبح هذا القالب نشطاً.'}
                                    </div>
                                )}

                                {isDisassemblableValue && (
                                    <>
                                        <div className="rounded-md border">
                                            <Table>
                                                <TableHeader>
                                                    <TableRow>
                                                        <TableHead>{t.disassemblyPartLabel || 'الجزء الناتج'}</TableHead>
                                                        <TableHead>{t.quantityLabel || 'الكمية'}</TableHead>
                                                        <TableHead>{t.expectedSalePriceLabel || 'سعر البيع المرجعي'}</TableHead>
                                                        <TableHead>{t.notesLabel || 'ملاحظات'}</TableHead>
                                                        <TableHead className="w-[60px]"></TableHead>
                                                    </TableRow>
                                                </TableHeader>
                                                <TableBody>
                                                    {disassemblyTemplateFields.length === 0 && (
                                                        <TableRow className="sticky top-0 z-20 bg-background shadow-sm">
                                                            <TableCell colSpan={5} className="text-center text-muted-foreground h-20">
                                                                {t.noDisassemblyParts || 'لا توجد أجزاء مضافة بعد.'}
                                                            </TableCell>
                                                        </TableRow>
                                                    )}
                                                    {disassemblyTemplateFields.map((fieldRow, index) => (
                                                        <TableRow key={fieldRow.id}>
                                                            <TableCell>
                                                                <FormField
                                                                    control={form.control}
                                                                    name={`disassemblyTemplate.${index}.partItemId`}
                                                                    render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormControl>
                                                                                <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                                                                    <SelectTrigger>
                                                                                        <SelectValue placeholder={t.selectPlaceholder || 'اختر...'} />
                                                                                    </SelectTrigger>
                                                                                    <SelectContent>
                                                                                        <SelectItem value="none">{t.selectPartPlaceholder || 'اختر الجزء'}</SelectItem>
                                                                                        {materialAlternativeOptions.map((candidate) => (
                                                                                            <SelectItem key={`${candidate.id}-disassembly-${index}`} value={String(candidate.id)}>
                                                                                                {candidate.name}
                                                                                            </SelectItem>
                                                                                        ))}
                                                                                    </SelectContent>
                                                                                </Select>
                                                                            </FormControl>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )}
                                                                />
                                                            </TableCell>
                                                            <TableCell>
                                                                <FormField
                                                                    control={form.control}
                                                                    name={`disassemblyTemplate.${index}.quantity`}
                                                                    render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormControl>
                                                                                <Input type="number" step="0.01" min="0.0001" {...field} />
                                                                            </FormControl>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )}
                                                                />
                                                            </TableCell>
                                                            <TableCell>
                                                                <FormField
                                                                    control={form.control}
                                                                    name={`disassemblyTemplate.${index}.expectedSalePrice`}
                                                                    render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormControl>
                                                                                <Input type="number" step="0.01" min="0" {...field} />
                                                                            </FormControl>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )}
                                                                />
                                                            </TableCell>
                                                            <TableCell>
                                                                <FormField
                                                                    control={form.control}
                                                                    name={`disassemblyTemplate.${index}.notes`}
                                                                    render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormControl>
                                                                                <Input {...field} value={field.value ?? ''} placeholder={t.notesPlaceholder || 'ملاحظات'} />
                                                                            </FormControl>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )}
                                                                />
                                                            </TableCell>
                                                            <TableCell className="text-right">
                                                                <Button type="button" variant="ghost" size="icon" onClick={() => removeDisassemblyTemplate(index)}>
                                                                    <Trash2 className="h-4 w-4 text-destructive" />
                                                                </Button>
                                                            </TableCell>
                                                        </TableRow>
                                                    ))}
                                                </TableBody>
                                            </Table>
                                        </div>
                                        <div className="rounded-md bg-muted/30 p-3 text-xs text-muted-foreground">
                                            <div>{t.disassemblyExpectedValueHint || 'إجمالي القيمة البيعية المرجعية للأجزاء'}: <span className="font-medium text-foreground">{formatCurrency(disassemblyExpectedTotal, currencySymbol)}</span></div>
                                            <div className="mt-1">{t.disassemblyTraceabilityHint || 'يمكن للجزء الواحد أن يأتي من أكثر من صنف أب عبر مستندات تفكيك مختلفة، وسيتم تتبع المصدر في سجل التفكيك وليس بحصره في والد واحد فقط.'}</div>
                                        </div>
                                    </>
                                )}
                            </div>
                        </TabsContent>

                        <TabsContent value="barcodes" className="space-y-4">
                          <FormField control={form.control} name="barcode" render={({ field }) => (
                              <FormItem>
                                  <FormLabel>{t.barcodeLabel || 'الباركود'}</FormLabel>
                                  <FormControl><Input {...field} /></FormControl>
                                  <FormMessage />
                              </FormItem>
                          )} />
                                                    <div className="space-y-2">
                                                        <div className="flex items-center justify-between">
                                                            <FormLabel>{t.additionalBarcodesLabel || 'باركودات إضافية'}</FormLabel>
                                                            <Button type="button" size="sm" variant="outline" onClick={() => appendBarcode('')}>
                                                                <PlusCircle className="mr-2 h-4 w-4" />
                                                                {t.addBarcodeRow ?? 'إضافة صف'}
                                                            </Button>
                                                        </div>
                                                        <div className="rounded-md border">
                                                            <Table>
                                                                <TableHeader>
                                                                    <TableRow>
                                                                        <TableHead>{t.barcodeLabel || 'الباركود'}</TableHead>
                                                                        <TableHead className="w-[60px]"></TableHead>
                                                                    </TableRow>
                                                                </TableHeader>
                                                                <TableBody>
                                                                    {additionalBarcodeFields.length === 0 && (
                                                                        <TableRow>
                                                                            <TableCell colSpan={2} className="text-center text-muted-foreground h-20">
                                                                                {t.noAdditionalBarcodes ?? 'لا توجد باركودات إضافية بعد.'}
                                                                            </TableCell>
                                                                        </TableRow>
                                                                    )}
                                                                    {additionalBarcodeFields.map((field, index) => (
                                                                        <TableRow key={field.id}>
                                                                            <TableCell>
                                                                                <FormField
                                                                                    control={form.control}
                                                                                    name={`additionalBarcodes.${index}`}
                                                                                    render={({ field }) => (
                                                                                        <FormItem>
                                                                                            <FormControl>
                                                                                                <Input
                                                                                                    {...field}
                                                                                                    placeholder={t.additionalBarcodePlaceholder ?? 'أدخل الباركود'}
                                                                                                />
                                                                                            </FormControl>
                                                                                            <FormMessage />
                                                                                        </FormItem>
                                                                                    )}
                                                                                />
                                                                            </TableCell>
                                                                            <TableCell className="text-right">
                                                                                <Button type="button" variant="ghost" size="icon" onClick={() => removeBarcode(index)}>
                                                                                    <Trash2 className="h-4 w-4 text-destructive" />
                                                                                </Button>
                                                                            </TableCell>
                                                                        </TableRow>
                                                                    ))}
                                                                </TableBody>
                                                            </Table>
                                                        </div>
                                                    </div>
                        </TabsContent>

                                                <TabsContent value="units" className="space-y-4">
                                                    <div className="flex items-center justify-between">
                                                        <p className="text-sm font-medium">{t.unitsTabLabel || 'الوحدات'}</p>
                                                        <Button
                                                            type="button"
                                                            size="sm"
                                                            variant="outline"
                                                            onClick={() => appendSecondaryUnit({ unit: '', barcode: '', quantity: '', price: '' })}
                                                        >
                                                            <PlusCircle className="mr-2 h-4 w-4" />
                                                            {t.addUnitRowLabel || t.addBarcodeRow || 'إضافة صف'}
                                                        </Button>
                                                    </div>

                                                    <div className="space-y-2 rounded-md border p-3">
                                                        <p className="text-xs font-medium text-muted-foreground">
                                                            {t.primaryUnitRowLabel || 'رئيسية'}
                                                        </p>
                                                        <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
                                                            <FormField control={form.control} name="primaryUnit" render={({ field }) => (
                                                                <FormItem className="space-y-1">
                                                                    <FormLabel>{t.primaryUnitLabel || 'الوحدة الرئيسية'}</FormLabel>
                                                                    <FormControl>
                                                                        <select
                                                                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                                                                            value={field.value || 'none'}
                                                                            onChange={(event) => {
                                                                                handleManagedUnitSelection(event.target.value, field.onChange, event.currentTarget, 'primary');
                                                                            }}
                                                                        >
                                                                            <option value="none">{t.selectPlaceholder || 'اختر...'}</option>
                                                                            <option value={addUnitOptionValue}>{t.addUnitFromFieldLabel || '+ إضافة وحدة جديدة'}</option>
                                                                            {primaryManagedUnitOptions.map((unit) => (
                                                                                <option key={unit.id} value={unit.description}>{formatManagedUnitLabel(unit)}</option>
                                                                            ))}
                                                                        </select>
                                                                    </FormControl>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                            <FormField control={form.control} name="primaryUnitQuantity" render={({ field }) => (
                                                                <FormItem className="space-y-1">
                                                                    <FormLabel>{t.primaryUnitQuantityLabel || 'كمية الوحدة الرئيسية'}</FormLabel>
                                                                    <FormControl>
                                                                        <Input type="number" step="0.01" {...field} ref={salePriceRef} placeholder={t.unitQuantityLabel || 'الكمية'} />
                                                                    </FormControl>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                            <FormField control={form.control} name="salePrice" render={({ field }) => (
                                                                <FormItem className="space-y-1">
                                                                    <FormLabel>{t.primaryUnitSalePriceLabel || 'سعر بيع الوحدة الرئيسية'}</FormLabel>
                                                                    <FormControl>
                                                                        <Input type="number" step="0.01" {...field} placeholder={t.unitPriceLabel || 'السعر'} />
                                                                    </FormControl>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                        </div>
                                                    </div>

                                                    <div className="space-y-2 rounded-md border p-3">
                                                        <div className="flex items-center justify-between gap-2">
                                                            <p className="text-xs font-medium text-muted-foreground">
                                                                {t.secondaryUnitRowLabel || 'وحدات فرعية'}
                                                            </p>
                                                            <Button
                                                                type="button"
                                                                size="sm"
                                                                variant="outline"
                                                                onClick={() => appendSecondaryUnit({ unit: '', barcode: '', quantity: '', price: '' })}
                                                            >
                                                                <PlusCircle className="mr-2 h-4 w-4" />
                                                                {t.addSecondaryUnitRow ?? 'إضافة وحدة فرعية'}
                                                            </Button>
                                                        </div>

                                                        {secondaryUnitFields.length === 0 && (
                                                            <div className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">
                                                                {t.noSecondaryUnits ?? 'لا توجد وحدات فرعية بعد.'}
                                                            </div>
                                                        )}

                                                        {secondaryUnitFields.map((secondaryField, index) => {
                                                            const rowState = secondaryRowsBelowCost[index];
                                                            const isBelowCost = !!rowState?.isBelow;

                                                            return (
                                                            <div
                                                                key={secondaryField.id}
                                                                className={`grid grid-cols-1 md:grid-cols-[minmax(140px,1fr)_minmax(160px,1.2fr)_minmax(100px,.8fr)_minmax(100px,.8fr)_44px] gap-2 items-start ${isBelowCost ? 'rounded-md border border-destructive/70 p-2 bg-destructive/5' : ''}`}
                                                            >
                                                                <FormField control={form.control} name={`secondaryUnits.${index}.unit`} render={({ field }) => (
                                                                    <FormItem className="space-y-1">
                                                                        <FormLabel>{t.secondaryUnitLabel || 'الوحدة الفرعية'}</FormLabel>
                                                                        <FormControl>
                                                                            <select
                                                                                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                                                                                value={field.value || 'none'}
                                                                                onChange={(event) => {
                                                                                    handleManagedUnitSelection(event.target.value, field.onChange, event.currentTarget, 'secondary');
                                                                                }}
                                                                            >
                                                                                <option value="none">{t.selectPlaceholder || 'اختر...'}</option>
                                                                                <option value={addUnitOptionValue}>{t.addUnitFromFieldLabel || '+ إضافة وحدة جديدة'}</option>
                                                                                {secondaryManagedUnitOptions.map((unit) => (
                                                                                    <option key={unit.id} value={unit.description}>{formatManagedUnitLabel(unit)}</option>
                                                                                ))}
                                                                            </select>
                                                                        </FormControl>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                <FormField control={form.control} name={`secondaryUnits.${index}.barcode`} render={({ field }) => (
                                                                    <FormItem className="space-y-1">
                                                                        <FormLabel>{t.secondaryUnitBarcodeLabel || 'باركود الوحدة الفرعية'}</FormLabel>
                                                                        <FormControl>
                                                                            <Input {...field} placeholder={t.secondaryBarcodeLabel || 'الباركود'} />
                                                                        </FormControl>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                <FormField control={form.control} name={`secondaryUnits.${index}.quantity`} render={({ field }) => (
                                                                    <FormItem className="space-y-1">
                                                                        <FormLabel>{t.secondaryUnitQuantityLabel || 'كمية الوحدة الفرعية'}</FormLabel>
                                                                        <FormControl>
                                                                            <Input type="number" step="0.01" {...field} placeholder={t.unitQuantityLabel || 'الكمية'} />
                                                                        </FormControl>
                                                                        <p className="text-xs text-muted-foreground">{t.secondaryUnitQuantityHint || 'عدد الوحدات الفرعية الموجودة في الوحدة الرئيسية — يجب أن يكون أكبر من 1'}</p>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                <FormField control={form.control} name={`secondaryUnits.${index}.price`} render={({ field }) => (
                                                                    <FormItem className="space-y-1">
                                                                        <FormLabel>{t.secondaryUnitPriceLabel || 'سعر بيع الوحدة الفرعية'}</FormLabel>
                                                                        <FormControl>
                                                                            <Input type="number" step="0.01" {...field} placeholder={t.unitPriceLabel || 'السعر'} />
                                                                        </FormControl>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                <Button
                                                                    type="button"
                                                                    variant="ghost"
                                                                    size="icon"
                                                                    className="mt-1"
                                                                    onClick={() => removeSecondaryUnit(index)}
                                                                >
                                                                    <Trash2 className="h-4 w-4 text-destructive" />
                                                                </Button>
                                                                {isBelowCost && (
                                                                    <p className="md:col-span-5 text-xs text-destructive">
                                                                        {(t?.lowSecondarySaleInline || 'تحذير: سعر بيع الوحدة الفرعية أقل من تكلفتها. التكلفة التقريبية: {cost}')
                                                                            .replace('{cost}', String(roundTo2(Number(rowState?.unitCost || 0))))}
                                                                    </p>
                                                                )}
                                                            </div>
                                                        )})}
                                                    </div>

                                                    <p className="text-xs text-muted-foreground">
                                                        {t.unitsNote || 'لا يجب تكرار الوحدة الرئيسية. كمية الوحدة الفرعية يجب أن تكون أكبر من كمية الوحدة الرئيسية.'}
                                                    </p>

                                                    <div className="pt-2 border-t">
                                                        <p className="text-sm font-medium mb-3">{t.pricesTabLabel || 'الأسعار'}</p>
                                                        <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
                                                        <div className="space-y-3 rounded-md border p-4 bg-muted/30">
                                                            <FormField control={form.control} name="purchasePrice" render={({ field }) => (
                                                                <FormItem>
                                                                    <FormLabel>{t.purchasePriceLabel || 'سعر الشراء'}</FormLabel>
                                                                    <FormControl>
                                                                        <Input type="number" step="0.01" className="max-w-[220px]" {...field} readOnly />
                                                                    </FormControl>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {form.watch('isManufactured')
                                                                            ? (t.manufacturedPurchasePriceNote || 'يتم احتساب تكلفة الصنف المُصنَّع تلقائيًا من معادلة الإنتاج.')
                                                                            : (t.purchasePriceNote || 'يتم تحديث سعر الشراء من فاتورة المشتريات.')}
                                                                    </p>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {t.purchasePriceIncludesTaxNote || 'ملاحظة: سعر الشراء المعروض يشمل الضريبة عند وجودها.'}
                                                                    </p>
                                                                    <FormMessage />
                                                                </FormItem>
                                                            )} />
                                                        </div>

                                                        <div className="space-y-3 rounded-md border p-4 bg-muted/30">
                                                            {form.watch('enableCustomTax') && (
                                                                <FormField control={form.control} name="customTaxValue" render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.customTaxValueLabel || 'قيمة ضريبة الصنف (%)'}</FormLabel>
                                                                        <FormControl>
                                                                            <Input type="number" step="0.01" min="0" max="100" className="max-w-[220px]" {...field} />
                                                                        </FormControl>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                            )}
                                                            {!form.watch('enableCustomTax') && (
                                                                <p className="text-xs text-muted-foreground">{t.enableCustomTaxLabel || 'تفعيل ضريبة خاصة للصنف'}</p>
                                                            )}
                                                        </div>

                                                        <div className="space-y-3 rounded-md border p-4 bg-muted/30">
                                                            {form.watch('enableProfitMargin') && (
                                                                <FormField control={form.control} name="profitMargin" render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.profitMarginLabel || 'نسبة الربح (%)'}</FormLabel>
                                                                        <FormControl>
                                                                            <Input type="number" step="0.01" min="0" className="max-w-[220px]" {...field} />
                                                                        </FormControl>
                                                                        <p className="text-xs text-muted-foreground">
                                                                            {t.profitMarginHelp || 'عند التفعيل سيتم عكس أسعار البيع تلقائيًا بناءً على سعر الشراء ونسبة الربح.'}
                                                                        </p>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                            )}
                                                            {!form.watch('enableProfitMargin') && (
                                                                <p className="text-xs text-muted-foreground">{t.enableProfitMarginLabel || 'تفعيل نسبة الربح'}</p>
                                                            )}
                                                        </div>
                                                        </div>

                                                        {itemType === 'material' && (categories?.length ?? 0) > 0 && (
                                                            <div className="space-y-3 mt-4">
                                                                <p className="text-sm font-medium">{t.categoryPriceLabel || 'أسعار حسب تصنيف الزبون'}</p>
                                                                <div className="rounded-md border max-h-64 overflow-y-auto">
                                                                    <Table>
                                                                        <TableHeader>
                                                                            <TableRow>
                                                                                <TableHead>{t.customerCategoryLabel || 'تصنيف الزبون'}</TableHead>
                                                                                <TableHead className="text-right">{t.salePriceLabel || 'سعر البيع'}</TableHead>
                                                                            </TableRow>
                                                                        </TableHeader>
                                                                        <TableBody>
                                                                            {[...(categories || [])]
                                                                                .sort((a, b) => String(a.name).localeCompare(String(b.name)))
                                                                                .map((cat, index) => {
                                                                                    const categoryKey = cat.id && cat.id !== 'NaN' ? String(cat.id) : String(cat.name || index);
                                                                                    return (
                                                                                        <TableRow key={categoryKey}>
                                                                                            <TableCell className="font-medium">{cat.name}</TableCell>
                                                                                            <TableCell className="text-right">
                                                                                                <FormField
                                                                                                    control={form.control}
                                                                                                    name={`categoryPrices.${categoryKey}`}
                                                                                                    render={({ field }) => (
                                                                                                        <FormItem>
                                                                                                            <FormControl>
                                                                                                                <Input type="number" step="0.01" {...field} />
                                                                                                            </FormControl>
                                                                                                            <FormMessage />
                                                                                                        </FormItem>
                                                                                                    )}
                                                                                                />
                                                                                            </TableCell>
                                                                                        </TableRow>
                                                                                    );
                                                                                })}
                                                                        </TableBody>
                                                                    </Table>
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>
                        </TabsContent>

                                                <TabsContent value="reorder" className="space-y-4">
                                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                        <FormField control={form.control} name="reorderMinimumQty" render={({ field }) => (
                                                            <FormItem>
                                                                <FormLabel>{t.reorderMinimumQtyLabel || 'الحد الأدنى'}</FormLabel>
                                                                <FormControl>
                                                                    <Input type="number" step="0.01" min="0" {...field} value={field.value === undefined || field.value === null ? '' : field.value} />
                                                                </FormControl>
                                                                <p className="text-xs text-muted-foreground">
                                                                    {t.reorderMinimumQtyHint || 'عند وصول المخزون إلى هذا الحد أو أقل يمكن اعتباره بحاجة لإعادة طلب.'}
                                                                </p>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )} />
                                                        <FormField control={form.control} name="reorderUnit" render={({ field }) => (
                                                            <FormItem>
                                                                <FormLabel>{t.reorderUnitLabel || 'الوحدة المعتمدة'}</FormLabel>
                                                                <FormControl>
                                                                    <select
                                                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                                                                        value={field.value || 'none'}
                                                                        onChange={(event) => field.onChange(event.target.value === 'none' ? '' : event.target.value)}
                                                                    >
                                                                        <option value="none">{t.selectPlaceholder || 'اختر...'}</option>
                                                                        {reorderUnitOptions.map((option) => (
                                                                            <option key={option.value} value={option.value}>{option.label}</option>
                                                                        ))}
                                                                    </select>
                                                                </FormControl>
                                                                <p className="text-xs text-muted-foreground">
                                                                    {t.reorderUnitHint || 'اختر الوحدة التي يتم بناء حد إعادة الطلب عليها.'}
                                                                </p>
                                                                <FormMessage />
                                                            </FormItem>
                                                        )} />
                                                    </div>
                                                </TabsContent>

                                                <TabsContent value="product-shapes" className="space-y-4">
                                                    {form.watch('usesProductShapes') && (
                                                        <>
                                                            <div className="space-y-2">
                                                                <div className="flex items-center justify-between">
                                                                    <div className="flex items-center gap-2">
                                                                        <FormLabel>{t.productShapesListLabel || 'قائمة الأشكال'}</FormLabel>
                                                                        <Button
                                                                            type="button"
                                                                            size="icon"
                                                                            variant="ghost"
                                                                            className="h-7 w-7"
                                                                            onClick={() => {
                                                                                if (typeof document !== 'undefined') {
                                                                                    (document.activeElement as HTMLElement | null)?.blur();
                                                                                }
                                                                                setProductShapeQuickAddName('');
                                                                                setProductShapeQuickAddOpen(true);
                                                                            }}
                                                                            title={t.addProductShapeDefinition || 'إضافة شكل جديد'}
                                                                        >
                                                                            <PlusCircle className="h-4 w-4" />
                                                                        </Button>
                                                                    </div>
                                                                    <Button
                                                                        type="button"
                                                                        size="sm"
                                                                        variant="outline"
                                                                        onClick={() => {
                                                                            if (runtimeShapeDefinitionOptions.length === 0) {
                                                                                if (typeof document !== 'undefined') {
                                                                                    (document.activeElement as HTMLElement | null)?.blur();
                                                                                }
                                                                                setProductShapeQuickAddName('');
                                                                                setProductShapeQuickAddOpen(true);
                                                                                return;
                                                                            }

                                                                            appendProductShape({
                                                                                id: `shape-${Date.now()}`,
                                                                                name: runtimeShapeDefinitionOptions[0]?.name || '',
                                                                                salePrice: '',
                                                                                costPrice: '',
                                                                                type: runtimeShapeDefinitionOptions[0]?.name || '',
                                                                                isActive: true,
                                                                            });
                                                                        }}
                                                                    >
                                                                        <PlusCircle className="mr-2 h-4 w-4" />
                                                                        {t.addProductShapeRow ?? 'إضافة شكل'}
                                                                    </Button>
                                                                </div>
                                                                {runtimeShapeDefinitionOptions.length === 0 && (
                                                                    <p className="text-xs text-destructive">
                                                                        {t.noProductShapeDefinitions || 'لا توجد بيانات في إدارة الاحجام و الاشكال. أضف القيم أولاً.'}
                                                                    </p>
                                                                )}

                                                                <div className="rounded-md border">
                                                                    <Table>
                                                                        <TableHeader>
                                                                            <TableRow>
                                                                                <TableHead>{t.productShapeNameLabel || 'اسم الشكل'}</TableHead>
                                                                                <TableHead>{t.salePriceLabel || 'سعر البيع'}</TableHead>
                                                                                <TableHead>{t.productShapeCostLabel || 'سعر التكلفة'}</TableHead>
                                                                                <TableHead>{t.statusLabel || 'مفعل'}</TableHead>
                                                                                <TableHead className="w-[60px]"></TableHead>
                                                                            </TableRow>
                                                                        </TableHeader>
                                                                        <TableBody>
                                                                            {productShapeFields.length === 0 && (
                                                                                <TableRow>
                                                                                    <TableCell colSpan={5} className="text-center text-muted-foreground h-20">
                                                                                        {t.noProductShapes ?? 'لا توجد أشكال مضافة بعد.'}
                                                                                    </TableCell>
                                                                                </TableRow>
                                                                            )}
                                                                            {productShapeFields.map((shapeField, index) => (
                                                                                <TableRow key={shapeField.id}>
                                                                                    <TableCell>
                                                                                        <FormField
                                                                                            control={form.control}
                                                                                            name={`productShapes.${index}.name`}
                                                                                            render={({ field }) => (
                                                                                                <FormItem>
                                                                                                    <FormControl>
                                                                                                        <Select
                                                                                                            value={field.value || runtimeShapeDefinitionOptions[0]?.name}
                                                                                                            onValueChange={(value) => {
                                                                                                                const selectedName = String(value || '').trim();
                                                                                                                field.onChange(selectedName);
                                                                                                                form.setValue(`productShapes.${index}.type`, selectedName || undefined, { shouldDirty: true });
                                                                                                            }}
                                                                                                        >
                                                                                                            <SelectTrigger>
                                                                                                                <SelectValue placeholder={t.selectPlaceholder || 'اختر...'} />
                                                                                                            </SelectTrigger>
                                                                                                            <SelectContent>
                                                                                                                {runtimeShapeDefinitionOptions.map((shapeDef) => (
                                                                                                                    <SelectItem key={`${shapeDef.id}-${index}`} value={shapeDef.name}>
                                                                                                                        {shapeDef.name}
                                                                                                                    </SelectItem>
                                                                                                                ))}
                                                                                                            </SelectContent>
                                                                                                        </Select>
                                                                                                    </FormControl>
                                                                                                    <FormMessage />
                                                                                                </FormItem>
                                                                                            )}
                                                                                        />
                                                                                    </TableCell>
                                                                                    <TableCell>
                                                                                        <FormField
                                                                                            control={form.control}
                                                                                            name={`productShapes.${index}.salePrice`}
                                                                                            render={({ field }) => (
                                                                                                <FormItem>
                                                                                                    <FormControl>
                                                                                                        <Input
                                                                                                            type="number"
                                                                                                            step="0.01"
                                                                                                            {...field}
                                                                                                            onFocus={(event) => {
                                                                                                                event.currentTarget.select();
                                                                                                            }}
                                                                                                        />
                                                                                                    </FormControl>
                                                                                                    <FormMessage />
                                                                                                </FormItem>
                                                                                            )}
                                                                                        />
                                                                                    </TableCell>
                                                                                    <TableCell>
                                                                                        <FormField
                                                                                            control={form.control}
                                                                                            name={`productShapes.${index}.costPrice`}
                                                                                            render={({ field }) => (
                                                                                                <FormItem>
                                                                                                    <FormControl>
                                                                                                        <Input type="number" step="0.01" {...field} />
                                                                                                    </FormControl>
                                                                                                    <FormMessage />
                                                                                                </FormItem>
                                                                                            )}
                                                                                        />
                                                                                    </TableCell>
                                                                                    <TableCell>
                                                                                        <FormField
                                                                                            control={form.control}
                                                                                            name={`productShapes.${index}.isActive`}
                                                                                            render={({ field }) => (
                                                                                                <FormItem className="flex items-center">
                                                                                                    <FormControl>
                                                                                                        <Checkbox checked={field.value !== false} onCheckedChange={(checked) => field.onChange(!!checked)} />
                                                                                                    </FormControl>
                                                                                                </FormItem>
                                                                                            )}
                                                                                        />
                                                                                    </TableCell>
                                                                                    <TableCell className="text-right">
                                                                                        <Button type="button" variant="ghost" size="icon" onClick={() => removeProductShape(index)}>
                                                                                            <Trash2 className="h-4 w-4 text-destructive" />
                                                                                        </Button>
                                                                                    </TableCell>
                                                                                </TableRow>
                                                                            ))}
                                                                        </TableBody>
                                                                    </Table>
                                                                </div>
                                                                <p className="text-xs text-muted-foreground">
                                                                    {t.productShapesNote || 'عند تفعيل الأشكال وإدخالها، سيطلب النظام اختيار الشكل في شاشة نقطة البيع قبل الإضافة.'}
                                                                </p>
                                                            </div>
                                                        </>
                                                    )}
                                                </TabsContent>

                                                <TabsContent value="real-estate" className="space-y-4">
                                                    {realEstateProjectOptions.length === 0 ? (
                                                        <div className="rounded-md border border-dashed p-4 text-sm text-muted-foreground">
                                                            {t.noRealEstateProjects ?? 'لا توجد مشاريع عقارية مهيأة بعد. أنشئ مشروعاً أولاً من صفحة المشاريع العقارية.'}
                                                        </div>
                                                    ) : (
                                                        <div className="rounded-md border p-4 space-y-4">
                                                            <div>
                                                                <p className="font-medium">{t.realEstateProjectsTitle || 'الربط العقاري الافتراضي'}</p>
                                                                <p className="text-xs text-muted-foreground">{t.realEstateProjectsDescription || 'هذا الربط يُستخدم كقيمة افتراضية عند تحميل تكلفة المادة على مشروع أو وحدة عقارية.'}</p>
                                                            </div>
                                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                <FormField control={form.control} name="realEstateCostType" render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.costTypeLabel || 'نوع التحميل'}</FormLabel>
                                                                        <Select value={field.value || 'general'} onValueChange={field.onChange}>
                                                                            <FormControl>
                                                                                <SelectTrigger>
                                                                                    <SelectValue placeholder={t.costTypeLabel || 'نوع التحميل'} />
                                                                                </SelectTrigger>
                                                                            </FormControl>
                                                                            <SelectContent>
                                                                                <SelectItem value="general">{t.generalLabel || 'عام'}</SelectItem>
                                                                                <SelectItem value="direct-unit">{t.directCostLabel || 'تكلفة مباشرة على وحدة'}</SelectItem>
                                                                                <SelectItem value="shared-project">{t.sharedCostsTitle || 'تكلفة مشتركة على المشروع'}</SelectItem>
                                                                            </SelectContent>
                                                                        </Select>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                <FormField control={form.control} name="realEstateProjectId" render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.realEstateProjectsTitle || 'المشروع العقاري'}</FormLabel>
                                                                        <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                                                            <FormControl>
                                                                                <SelectTrigger>
                                                                                    <SelectValue placeholder={t.projectNameLabel || 'اختر المشروع'} />
                                                                                </SelectTrigger>
                                                                            </FormControl>
                                                                            <SelectContent>
                                                                                <SelectItem value="none">{t.itemGroupNone || 'بدون ربط'}</SelectItem>
                                                                                {realEstateProjectOptions.map((project) => (
                                                                                    <SelectItem key={project.id} value={project.id}>{project.name}</SelectItem>
                                                                                ))}
                                                                            </SelectContent>
                                                                        </Select>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )} />
                                                                {selectedRealEstateCostType === 'direct-unit' && (
                                                                    <FormField control={form.control} name="realEstateUnitId" render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormLabel>{t.unitNameLabel || 'الوحدة العقارية'}</FormLabel>
                                                                            <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)} disabled={!selectedRealEstateProjectId}>
                                                                                <FormControl>
                                                                                    <SelectTrigger>
                                                                                        <SelectValue placeholder={t.unitNamePlaceholder || 'اختر الوحدة'} />
                                                                                    </SelectTrigger>
                                                                                </FormControl>
                                                                                <SelectContent>
                                                                                    <SelectItem value="none">{t.itemGroupNone || 'بدون تحديد'}</SelectItem>
                                                                                    {selectedRealEstateUnits.map((unit: any) => (
                                                                                        <SelectItem key={unit.id} value={unit.id}>{unit.name || unit.unitCode}</SelectItem>
                                                                                    ))}
                                                                                </SelectContent>
                                                                            </Select>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )} />
                                                                )}
                                                                {selectedRealEstateCostType === 'shared-project' && (
                                                                    <FormField control={form.control} name="realEstateAllocationMethod" render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormLabel>{t.allocationMethodLabel || 'أساس التوزيع'}</FormLabel>
                                                                            <Select value={field.value || 'area'} onValueChange={field.onChange}>
                                                                                <FormControl>
                                                                                    <SelectTrigger>
                                                                                        <SelectValue placeholder={t.allocationMethodLabel || 'أساس التوزيع'} />
                                                                                    </SelectTrigger>
                                                                                </FormControl>
                                                                                <SelectContent>
                                                                                    <SelectItem value="area">{t.allocateByAreaLabel || 'حسب المساحة'}</SelectItem>
                                                                                    <SelectItem value="sale-value">{t.allocateBySaleValueLabel || 'حسب القيمة البيعية'}</SelectItem>
                                                                                    <SelectItem value="manual-share">{t.allocateByManualShareLabel || 'حسب النسبة اليدوية'}</SelectItem>
                                                                                </SelectContent>
                                                                            </Select>
                                                                            <FormMessage />
                                                                        </FormItem>
                                                                    )} />
                                                                )}
                                                            </div>
                                                        </div>
                                                    )}
                                                </TabsContent>

                                                <TabsContent value="printing" className="space-y-4">
                                                    <div className="rounded-md border p-3 space-y-3">
                                                        <div className="flex flex-wrap items-start justify-between gap-2">
                                                            <div>
                                                                <p className="text-sm font-medium">{t.printingSectionTitle || 'إعدادات الطباعة المخصصة'}</p>
                                                                <p className="text-xs text-muted-foreground">
                                                                    {t.printingSectionDescription || 'تتم إدارة الطابعات وأقسام التحضير من الإعدادات العامة. يمكنك أيضاً الإضافة السريعة من هنا دون مغادرة بطاقة الصنف.'}
                                                                </p>
                                                            </div>
                                                            <div className="flex items-center gap-2">
                                                                <Button type="button" variant="outline" size="sm" onClick={() => setQuickPrinterDialogOpen(true)}>
                                                                    <PlusCircle className="me-2 h-4 w-4" />
                                                                    {t.quickAddPrinterButton || 'إضافة طابعة'}
                                                                </Button>
                                                                <Button type="button" variant="outline" size="sm" onClick={() => setQuickPrintDialogOpen(true)}>
                                                                    <PlusCircle className="me-2 h-4 w-4" />
                                                                    {t.quickAddPrintSectionButton || 'إضافة قسم تحضير'}
                                                                </Button>
                                                            </div>
                                                        </div>

                                                        {!printingSettings.customPrintersEnabled && (
                                                            <div className="rounded-md border border-dashed bg-muted/30 p-3 text-xs text-muted-foreground">
                                                                {t.printingFeatureDisabledHint || 'ميزة الطابعات المخصصة غير مفعلة حالياً. فعّلها أولاً من إعدادات التطبيق ثم أضف الطابعات والأقسام.'}
                                                            </div>
                                                        )}

                                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                            <FormField
                                                                control={form.control}
                                                                name="printSectionId"
                                                                render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.printSectionLabel || 'قسم الطباعة'}</FormLabel>
                                                                        <Select
                                                                            value={field.value || 'none'}
                                                                            onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}
                                                                            disabled={!printingSettings.customPrintersEnabled || (printingSettings.printSections || []).length === 0}
                                                                        >
                                                                            <FormControl>
                                                                                <SelectTrigger>
                                                                                    <SelectValue placeholder={t.printSectionPlaceholder || 'اختر القسم المناسب'} />
                                                                                </SelectTrigger>
                                                                            </FormControl>
                                                                            <SelectContent>
                                                                                <SelectItem value="none">{t.noPrintSectionOption || 'بدون توجيه خاص'}</SelectItem>
                                                                                {(printingSettings.printSections || []).filter((section) => section?.enabled !== false).map((section) => (
                                                                                    <SelectItem key={String(section.id)} value={String(section.id)}>
                                                                                        {section.name}
                                                                                    </SelectItem>
                                                                                ))}
                                                                            </SelectContent>
                                                                        </Select>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )}
                                                            />

                                                            <FormField
                                                                control={form.control}
                                                                name="printLabelOverride"
                                                                render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{t.printLabelOverrideLabel || 'اسم مختصر في التذكرة'}</FormLabel>
                                                                        <FormControl>
                                                                            <Input
                                                                                {...field}
                                                                                value={field.value ?? ''}
                                                                                placeholder={t.printLabelOverridePlaceholder || 'مثال: برغر دبل - بدون بصل'}
                                                                                disabled={!printingSettings.customPrintersEnabled}
                                                                            />
                                                                        </FormControl>
                                                                        <FormMessage />
                                                                    </FormItem>
                                                                )}
                                                            />
                                                        </div>

                                                        <FormField
                                                            control={form.control}
                                                            name="excludeFromPrepTicket"
                                                            render={({ field }) => (
                                                                <FormItem className="flex items-start gap-3 rounded-md border p-3">
                                                                    <FormControl>
                                                                        <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                                                                    </FormControl>
                                                                    <div className="space-y-1">
                                                                        <FormLabel className="m-0">{t.excludeFromPrepTicketLabel || 'استبعاد من تذكرة التحضير'}</FormLabel>
                                                                        <p className="text-xs text-muted-foreground">
                                                                            {t.excludeFromPrepTicketDescription || 'فعّل هذا الخيار إذا كان الصنف يجب أن يظهر في إيصال الزبون فقط دون تذكرة المطبخ/المشروبات.'}
                                                                        </p>
                                                                    </div>
                                                                </FormItem>
                                                            )}
                                                        />

                                                        {selectedPrintSection && (
                                                            <div className="rounded-md bg-muted/30 p-3 text-xs text-muted-foreground">
                                                                {(t.printingRoutePreview || 'المسار الحالي:')} <span className="font-medium text-foreground">{selectedPrintSection.name}</span>
                                                                {selectedPrintSectionPrinterName ? (
                                                                    <>
                                                                        {' '}→ <span className="font-medium text-foreground">{selectedPrintSectionPrinterName}</span>
                                                                    </>
                                                                ) : null}
                                                            </div>
                                                        )}

                                                        <Dialog open={quickPrinterDialogOpen} onOpenChange={(next) => {
                                                            setQuickPrinterDialogOpen(next);
                                                            if (!next) {
                                                                resetQuickPrinterDraft();
                                                            }
                                                        }}>
                                                            <DialogContent className="max-w-md">
                                                                <DialogHeader>
                                                                    <DialogTitle>{t.quickAddPrinterDialogTitle || 'إضافة طابعة سريعة'}</DialogTitle>
                                                                    <DialogDescription>
                                                                        {t.quickAddPrinterDialogDescription || 'أضف طابعة جديدة مباشرة من بطاقة الصنف لتظهر ضمن إعدادات الطباعة.'}
                                                                    </DialogDescription>
                                                                </DialogHeader>
                                                                <div className="space-y-3">
                                                                    <div className="space-y-2">
                                                                        <Label>{t.printerNameLabel || 'اسم الطابعة'}</Label>
                                                                        <Input
                                                                            value={quickPrinterName}
                                                                            onChange={(event) => setQuickPrinterName(event.target.value)}
                                                                            placeholder={t.printerNamePlaceholder || 'مثال: Kitchen Printer 1'}
                                                                        />
                                                                    </div>

                                                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                        <div className="space-y-2">
                                                                            <Label>{t.printerConnectionTypeLabel || 'نوع الاتصال'}</Label>
                                                                            <Select value={quickPrinterConnectionType} onValueChange={(value: 'network' | 'windows' | 'usb') => setQuickPrinterConnectionType(value)}>
                                                                                <SelectTrigger>
                                                                                    <SelectValue />
                                                                                </SelectTrigger>
                                                                                <SelectContent>
                                                                                    <SelectItem value="network">{t.printerConnectionNetwork || 'شبكة (IP)'}</SelectItem>
                                                                                    <SelectItem value="windows">{t.printerConnectionWindows || 'Windows Share'}</SelectItem>
                                                                                    <SelectItem value="usb">{t.printerConnectionUsb || 'USB'}</SelectItem>
                                                                                </SelectContent>
                                                                            </Select>
                                                                        </div>
                                                                        <div className="space-y-2">
                                                                            <Label>{t.printerPaperWidthLabel || 'عرض الورق'}</Label>
                                                                            <Select value={quickPrinterPaperWidth} onValueChange={(value: '58mm' | '80mm' | 'a4') => setQuickPrinterPaperWidth(value)}>
                                                                                <SelectTrigger>
                                                                                    <SelectValue />
                                                                                </SelectTrigger>
                                                                                <SelectContent>
                                                                                    <SelectItem value="58mm">58mm</SelectItem>
                                                                                    <SelectItem value="80mm">80mm</SelectItem>
                                                                                    <SelectItem value="a4">A4</SelectItem>
                                                                                </SelectContent>
                                                                            </Select>
                                                                        </div>
                                                                    </div>

                                                                    {quickPrinterConnectionType === 'network' && (
                                                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                            <div className="space-y-2">
                                                                                <Label>{t.printerIpAddressLabel || 'عنوان IP'}</Label>
                                                                                <Input
                                                                                    value={quickPrinterIpAddress}
                                                                                    onChange={(event) => setQuickPrinterIpAddress(event.target.value)}
                                                                                    placeholder={t.printerIpAddressPlaceholder || '192.168.1.120'}
                                                                                />
                                                                            </div>
                                                                            <div className="space-y-2">
                                                                                <Label>{t.printerPortLabel || 'المنفذ'}</Label>
                                                                                <Input
                                                                                    type="number"
                                                                                    min={1}
                                                                                    max={65535}
                                                                                    value={quickPrinterPort}
                                                                                    onChange={(event) => setQuickPrinterPort(event.target.value)}
                                                                                />
                                                                            </div>
                                                                        </div>
                                                                    )}

                                                                    {quickPrinterConnectionType === 'windows' && (
                                                                        <div className="space-y-2">
                                                                            <Label>{t.printerShareNameLabel || 'اسم المشاركة'}</Label>
                                                                            <Input
                                                                                value={quickPrinterShareName}
                                                                                onChange={(event) => setQuickPrinterShareName(event.target.value)}
                                                                                placeholder={t.printerShareNamePlaceholder || '\\\\PC-NAME\\Printer'}
                                                                            />
                                                                        </div>
                                                                    )}

                                                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                        <div className="space-y-2">
                                                                            <Label>{t.printerRoleLabel || 'دور الطابعة'}</Label>
                                                                            <Select value={quickPrinterRole} onValueChange={(value: 'receipt' | 'prep' | 'both') => setQuickPrinterRole(value)}>
                                                                                <SelectTrigger>
                                                                                    <SelectValue />
                                                                                </SelectTrigger>
                                                                                <SelectContent>
                                                                                    <SelectItem value="prep">{t.printerRolePrep || 'تحضير'}</SelectItem>
                                                                                    <SelectItem value="receipt">{t.printerRoleReceipt || 'إيصال زبون'}</SelectItem>
                                                                                    <SelectItem value="both">{t.printerRoleBoth || 'كلاهما'}</SelectItem>
                                                                                </SelectContent>
                                                                            </Select>
                                                                        </div>
                                                                        <div className="flex items-end">
                                                                            <div className="flex items-center gap-2 rounded-md border p-3 w-full">
                                                                                <Checkbox checked={quickPrinterEnabled} onCheckedChange={(checked) => setQuickPrinterEnabled(checked === true)} />
                                                                                <Label className="m-0">{t.enabledLabel || 'مفعل'}</Label>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <DialogFooter>
                                                                    <Button type="button" variant="outline" onClick={() => setQuickPrinterDialogOpen(false)} disabled={isQuickPrinterSaving}>
                                                                        {t.cancel || 'إلغاء'}
                                                                    </Button>
                                                                    <Button type="button" onClick={() => void onQuickAddPrinter()} disabled={isQuickPrinterSaving}>
                                                                        {isQuickPrinterSaving ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : null}
                                                                        {t.add || 'إضافة'}
                                                                    </Button>
                                                                </DialogFooter>
                                                            </DialogContent>
                                                        </Dialog>

                                                        <Dialog open={quickPrintDialogOpen} onOpenChange={(next) => {
                                                            setQuickPrintDialogOpen(next);
                                                            if (!next) {
                                                                resetQuickSectionDraft();
                                                            }
                                                        }}>
                                                            <DialogContent className="max-w-md">
                                                                <DialogHeader>
                                                                    <DialogTitle>{t.quickAddPrintSectionDialogTitle || 'إضافة قسم تحضير سريع'}</DialogTitle>
                                                                    <DialogDescription>
                                                                        {t.quickAddPrintSectionDialogDescription || 'أضف قسماً مثل المطبخ أو المشروبات واربطه بطابعة مباشرة من بطاقة الصنف.'}
                                                                    </DialogDescription>
                                                                </DialogHeader>
                                                                <div className="space-y-3">
                                                                    <div className="space-y-2">
                                                                        <Label>{t.printSectionNameLabel || 'اسم القسم'}</Label>
                                                                        <Input
                                                                            value={quickSectionName}
                                                                            onChange={(event) => setQuickSectionName(event.target.value)}
                                                                            placeholder={t.printSectionNamePlaceholder || 'مثال: المطبخ'}
                                                                        />
                                                                    </div>

                                                                    <div className="space-y-2">
                                                                        <Label>{t.linkedPrinterLabel || 'الطابعة المرتبطة'}</Label>
                                                                        <Select value={quickSectionPrinterId} onValueChange={setQuickSectionPrinterId}>
                                                                            <SelectTrigger>
                                                                                <SelectValue placeholder={t.printSectionPrinterPlaceholder || 'اختر الطابعة'} />
                                                                            </SelectTrigger>
                                                                            <SelectContent>
                                                                                <SelectItem value="none">{t.itemGroupNone || 'بدون ربط'}</SelectItem>
                                                                                {(printingSettings.printerConfigs || []).filter((entry) => entry?.enabled !== false).map((entry) => (
                                                                                    <SelectItem key={String(entry.id)} value={String(entry.id)}>
                                                                                        {entry.name}
                                                                                    </SelectItem>
                                                                                ))}
                                                                            </SelectContent>
                                                                        </Select>
                                                                    </div>

                                                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                        <div className="space-y-2">
                                                                            <Label>{t.copiesLabel || 'عدد النسخ'}</Label>
                                                                            <Input
                                                                                type="number"
                                                                                min={1}
                                                                                max={5}
                                                                                value={String(quickSectionCopies)}
                                                                                onChange={(event) => {
                                                                                    const parsed = Number(event.target.value);
                                                                                    if (!Number.isFinite(parsed)) {
                                                                                        setQuickSectionCopies(1);
                                                                                        return;
                                                                                    }
                                                                                    setQuickSectionCopies(Math.max(1, Math.min(5, Math.floor(parsed))));
                                                                                }}
                                                                            />
                                                                        </div>
                                                                        <div className="flex items-end">
                                                                            <div className="flex items-center gap-2 rounded-md border p-3 w-full">
                                                                                <Checkbox checked={quickSectionEnabled} onCheckedChange={(checked) => setQuickSectionEnabled(checked === true)} />
                                                                                <Label className="m-0">{t.enabledLabel || 'مفعل'}</Label>
                                                                            </div>
                                                                        </div>
                                                                    </div>

                                                                    <div className="flex items-center gap-2 rounded-md border p-3">
                                                                        <Checkbox checked={quickSectionPrintPrices} onCheckedChange={(checked) => setQuickSectionPrintPrices(checked === true)} />
                                                                        <Label className="m-0">{t.printPricesLabel || 'إظهار الأسعار في التذكرة'}</Label>
                                                                    </div>
                                                                </div>
                                                                <DialogFooter>
                                                                    <Button type="button" variant="outline" onClick={() => setQuickPrintDialogOpen(false)} disabled={isQuickSectionSaving}>
                                                                        {t.cancel || 'إلغاء'}
                                                                    </Button>
                                                                    <Button type="button" onClick={() => void onQuickAddSection()} disabled={isQuickSectionSaving}>
                                                                        {isQuickSectionSaving ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : null}
                                                                        {t.add || 'إضافة'}
                                                                    </Button>
                                                                </DialogFooter>
                                                            </DialogContent>
                                                        </Dialog>
                                                    </div>
                                                </TabsContent>

                                                <TabsContent value="additional-details" className="space-y-4">
                                                    <FormField control={form.control} name="additionalDetails" render={({ field }) => (
                                                        <FormItem>
                                                            <FormLabel>{t.additionalDetailsLabel || 'تفاصيل اضافيه'}</FormLabel>
                                                            <FormControl>
                                                                <Textarea
                                                                    {...field}
                                                                    value={field.value ?? ''}
                                                                    placeholder={t.additionalDetailsPlaceholder || 'أدخل تفاصيل إضافية طويلة حول الصنف (وصف، مقاسات، مواصفات، ملاحظات...)'}
                                                                    className="min-h-[220px]"
                                                                />
                                                            </FormControl>
                                                            <p className="text-xs text-muted-foreground">
                                                                {t.additionalDetailsHelp || 'يمكنك إدخال نص طويل، وسيكون قابلًا للبحث من شاشة اختيار الصنف.'}
                                                            </p>
                                                            <FormMessage />
                                                        </FormItem>
                                                    )} />
                                                </TabsContent>

                                                <TabsContent value="accounting" className="space-y-4">
                                                    <div className="bg-emerald-50 dark:bg-emerald-950/20 border border-emerald-200 dark:border-emerald-800 rounded-lg p-4">
                                                        <div className="flex items-center justify-between mb-3">
                                                            <h3 className="font-semibold text-sm">{'الحسابات المحاسبية للصنف'}</h3>
                                                            <Button
                                                                type="button"
                                                                variant="outline"
                                                                size="sm"
                                                                className="gap-1.5 text-xs"
                                                                onClick={() => {
                                                                    const category = form.getValues('itemCategory') as string;
                                                                    applyCategoryDefaultAccounts(category, true);
                                                                }}
                                                            >
                                                                <RotateCcw className="h-3.5 w-3.5" />
                                                                {'إعادة الحسابات الافتراضية'}
                                                            </Button>
                                                        </div>
                                                        <p className="text-xs text-muted-foreground mb-4">
                                                            {'تُستخدم هذه الحسابات عند توليد القيود المحاسبية. إذا تركتها فارغة سيُستخدم الحساب الافتراضي للنظام.'}
                                                        </p>
                                                        
                                                        {(() => {
                                                            const isService = (form.getValues('itemCategory') as string) === 'service';
                                                            
                                                            return (
                                                                <div className="space-y-4">
                                                                    {/* حساب الإيرادات - يظهر لجميع الأنواع */}
                                                                    <FormField control={form.control} name="revenueAccountCode" render={({ field }) => (
                                                                <FormItem>
                                                                    <FormLabel>{'حساب الإيرادات'}</FormLabel>
                                                                    <FormControl>
                                                                        <AccountCodeSelector
                                                                            value={field.value || ''}
                                                                            options={revenueAccountOptions}
                                                                                    placeholder={isService ? '4140 - إيرادات خدمات' : '4110 - إيرادات مبيعات'}
                                                                            onValueChange={field.onChange}
                                                                        />
                                                                    </FormControl>
                                                                            <p className="text-xs text-muted-foreground">
                                                                                {isService 
                                                                                    ? 'يُستخدم في قيد فاتورة الخدمة (دائن)'
                                                                                    : 'يُستخدم في قيد فاتورة البيع (دائن)'}
                                                                            </p>
                                                                    <FormMessage />
                                                                </FormItem>
                                                                    )} />

                                                                    {/* حساب تكلفة الخدمة - يظهر فقط للخدمات */}
                                                                    {isService && (
                                                                        <FormField control={form.control} name="cogsAccountCode" render={({ field }) => (
                                                                <FormItem>
                                                                                <FormLabel>{'حساب تكلفة الخدمة (اختياري)'}</FormLabel>
                                                                    <FormControl>
                                                                        <AccountCodeSelector
                                                                            value={field.value || ''}
                                                                                        options={cogsAccountOptions}
                                                                                        placeholder={'اختياري - تكلفة الخدمة'}
                                                                            onValueChange={field.onChange}
                                                                        />
                                                                    </FormControl>
                                                                                <p className="text-xs text-muted-foreground">{'يُستخدم في تسجيل تكلفة الخدمة المباعة (اختياري)'}</p>
                                                                    <FormMessage />
                                                                </FormItem>
                                                                        )} />
                                                                    )}

                                                                    {/* حقول البضاعة - تظهر فقط للأصناف المخزنية */}
                                                                    {!isService && (
                                                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                                            <FormField control={form.control} name="inventoryAccountCode" render={({ field }) => (
                                                                <FormItem>
                                                                                    <FormLabel>{'حساب المخزون'}</FormLabel>
                                                                    <FormControl>
                                                                        <AccountCodeSelector
                                                                            value={field.value || ''}
                                                                                            options={inventoryAccountOptions}
                                                                                            placeholder={'1170 - مخزون بضاعة'}
                                                                            onValueChange={field.onChange}
                                                                        />
                                                                    </FormControl>
                                                                                    <p className="text-xs text-muted-foreground">{'يُستخدم في حركات المخزون (مدين)'}</p>
                                                                    <FormMessage />
                                                                </FormItem>
                                                                            )} />
                                                                            <FormField control={form.control} name="cogsAccountCode" render={({ field }) => (
                                                                <FormItem>
                                                                                    <FormLabel>{'تكلفة البضاعة المباعة'}</FormLabel>
                                                                    <FormControl>
                                                                        <AccountCodeSelector
                                                                            value={field.value || ''}
                                                                            options={cogsAccountOptions}
                                                                            placeholder={'5110 - تكلفة شراء بضاعة'}
                                                                            onValueChange={field.onChange}
                                                                        />
                                                                    </FormControl>
                                                                                    <p className="text-xs text-muted-foreground">{'يُستخدم في قيد تكلفة المبيعات (مدين)'}</p>
                                                                    <FormMessage />
                                                                </FormItem>
                                                                            )} />
                                                                            <FormField control={form.control} name="purchaseAccountCode" render={({ field }) => (
                                                                                <FormItem>
                                                                                    <FormLabel>{'حساب المشتريات'}</FormLabel>
                                                                                    <FormControl>
                                                                                        <AccountCodeSelector
                                                                                            value={field.value || ''}
                                                                                            options={cogsAccountOptions}
                                                                                            placeholder={'5110 - تكلفة شراء بضاعة'}
                                                                                            onValueChange={field.onChange}
                                                                                        />
                                                                                    </FormControl>
                                                                                    <p className="text-xs text-muted-foreground">{'يُستخدم في قيد فاتورة الشراء (مدين)'}</p>
                                                                                    <FormMessage />
                                                                                </FormItem>
                                                                            )} />
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            );
                                                        })()}
                                                    </div>
                                                </TabsContent>
                      </Tabs>

                      <div className={`mt-4 border ${asPage ? 'rounded-xl bg-gradient-to-br from-amber-50/80 via-yellow-50/40 to-orange-50/60 dark:from-amber-950/30 dark:via-yellow-950/20 dark:to-orange-950/25 border-amber-200/60 dark:border-amber-700/40 shadow-sm p-4' : 'rounded-md bg-muted/30 p-3'}`}>
                        <p className={`text-sm font-medium mb-2 ${asPage ? 'text-amber-800 dark:text-amber-300' : ''}`}>{t.activationOptionsLabel || 'خيارات التفعيل'}</p>
                        <div className="flex flex-wrap xl:flex-nowrap items-center gap-x-4 gap-y-2">
                            <FormField control={form.control} name="allowDescriptionEdit" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                      <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.allowDescriptionEditLabel ?? 'وصف قابل للتعديل في الفواتير'}</FormLabel>
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="hasSerialNumber" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                        <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.hasSerialNumberLabel ?? 'الصنف يحتوي على رقم تسلسلي'}</FormLabel>
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="hasRfid" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                        <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.hasRfidLabel ?? 'الصنف يحتوي على RFID'}</FormLabel>
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="isDisassemblable" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                        <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.isDisassemblableLabel ?? 'الصنف قابل للتفكيك'}</FormLabel>
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="isWeighed" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                                                            <Checkbox checked={!!field.value} onCheckedChange={(checked) => {
                                                                                const nextChecked = checked === true;
                                                                                field.onChange(nextChecked);
                                                                                if (nextChecked) {
                                                                                    form.setValue('isSized', false, { shouldDirty: true });
                                                                                }
                                                                            }} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.isWeighedLabel || 'يباع بالوزن'}</FormLabel>
                                </FormItem>
                            )} />
                                                        <FormField control={form.control} name="isSized" render={({ field }) => (
                                                                <FormItem className="flex items-center gap-2 space-y-0">
                                                                        <FormControl>
                                                                            <Checkbox checked={!!field.value} onCheckedChange={(checked) => {
                                                                                const nextChecked = checked === true;
                                                                                field.onChange(nextChecked);
                                                                                if (nextChecked) {
                                                                                    form.setValue('isWeighed', false, { shouldDirty: true });
                                                                                }
                                                                            }} />
                                                                        </FormControl>
                                                                        <FormLabel className="mb-0">{t.isSizedLabel || 'يباع بالحجم'}</FormLabel>
                                                                </FormItem>
                                                        )} />
                            <FormField control={form.control} name="enableCustomTax" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                        <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.enableCustomTaxLabel || 'تفعيل ضريبة خاصة للصنف'}</FormLabel>
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="enableProfitMargin" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                        <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.enableProfitMarginLabel || 'تفعيل نسبة الربح'}</FormLabel>
                                </FormItem>
                            )} />
                            <FormField control={form.control} name="usesProductShapes" render={({ field }) => (
                                <FormItem className="flex items-center gap-2 space-y-0">
                                    <FormControl>
                                        <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                                    </FormControl>
                                    <FormLabel className="mb-0">{t.productShapesEnabledLabel || 'تفعيل أشكال المنتج'}</FormLabel>
                                </FormItem>
                            )} />
                        </div>
                                            </div>
                                            </>
                    )}
                    {itemType === 'customer' && (
                      <>
                        <FormField control={form.control} name="customerNumber" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerNumberLabel || 'رقم الزبون'}</FormLabel>
                                <FormControl><Input {...field} readOnly value={field.value || nextCustomerNumber} /></FormControl>
                                <p className="text-xs text-muted-foreground">{t.customerNumberHelp || 'يُنشأ تلقائياً ويستخدم كمعرّف رئيسي'}</p>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="name" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerNameLabel || t.itemNameLabel}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="phone" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerPhoneLabel || 'رقم واتساب'}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="creditLimit" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerCreditLimitLabel || 'الحد المسموح للدين'}</FormLabel>
                                <FormControl><Input type="number" step="0.01" {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="address" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerAddressLabel || 'العنوان'}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="allowedDiscount" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerAllowedDiscountLabel || 'الخصم المسموح به (%)'}</FormLabel>
                                <FormControl><Input type="number" step="0.01" min="0" max="100" {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                                                {(
                                                    <FormField control={form.control} name="salesRepId" render={({ field }) => (
                                                            <FormItem>
                                                                    <FormLabel>{t.customerSalesRepLabel || 'مندوب المبيعات'}</FormLabel>
                                                                    <Select
                                                                        value={field.value || 'none'}
                                                                        onValueChange={(value) => {
                                                                            if (value === addSalesRepOptionValue) {
                                                                                setSalesRepQuickAddOpen(true);
                                                                                return;
                                                                            }
                                                                            field.onChange(value === 'none' ? '' : value);
                                                                        }}
                                                                    >
                                                                        <FormControl>
                                                                            <SelectTrigger>
                                                                                <SelectValue placeholder={t.customerSalesRepPlaceholder || 'اختر مندوب المبيعات'} />
                                                                            </SelectTrigger>
                                                                        </FormControl>
                                                                        <SelectContent>
                                                                            <SelectItem value="none">{t.customerSalesRepNone || 'بدون مندوب'}</SelectItem>
                                                                            <SelectItem value={addSalesRepOptionValue}>{t.addSalesRepInlineOption || 'إضافة مندوب جديد'}</SelectItem>
                                                                            {runtimeSalesRepOptions.map((rep) => (
                                                                                <SelectItem key={rep.id} value={rep.id}>{rep.name}</SelectItem>
                                                                            ))}
                                                                        </SelectContent>
                                                                    </Select>
                                                                    <FormMessage />
                                                            </FormItem>
                                                    )} />
                                                )}
                        <FormField control={form.control} name="category" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.customerCategoryLabel || 'تصنيف الزبون'}</FormLabel>
                                                                <Select
                                                                    onValueChange={(value) => {
                                                                        if (value === addCategoryOptionValue) {
                                                                            setCategoryQuickAddOpen(true);
                                                                            return;
                                                                        }
                                                                        field.onChange(value);
                                                                    }}
                                                                    value={field.value || undefined}
                                                                >
                                  <FormControl>
                                    <SelectTrigger>
                                      <SelectValue placeholder={t.selectCustomerCategoryPlaceholder || 'اختر تصنيف الزبون'} />
                                    </SelectTrigger>
                                  </FormControl>
                                  <SelectContent>
                                                                        <SelectItem value={addCategoryOptionValue}>{t.addCategoryInlineOption || 'إضافة تصنيف جديد'}</SelectItem>
                                                                        {runtimeCategoryOptions.map((cat) => (
                                                                            <SelectItem key={cat.id || cat.name} value={cat.name}>{cat.name}</SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )} />
                      </>
                    )}
                    {(itemType === 'expense' || itemType === 'product-shape') && (
                        <FormField control={form.control} name="name" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{itemType === 'product-shape' ? (t.productShapeNameLabel || 'اسم الحجم/الشكل') : t.itemNameLabel}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                    )}
                    {itemType === 'expense' && realEstateProjectOptions.length > 0 && (
                        <div className="rounded-md border p-3 space-y-3">
                            <div>
                                <p className="text-sm font-medium">{t.realEstateProjectsTitle || 'الربط العقاري الافتراضي'}</p>
                                <p className="text-xs text-muted-foreground">{t.realEstateProjectsDescription || 'استخدم هذا الربط لتوجيه المصروف افتراضياً إلى مشروع عقاري أو إلى تكلفة مشتركة أو مباشرة على وحدة.'}</p>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <FormField control={form.control} name="realEstateCostType" render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>{t.costTypeLabel || 'نوع التحميل'}</FormLabel>
                                        <Select value={field.value || 'general'} onValueChange={field.onChange}>
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder={t.costTypeLabel || 'نوع التحميل'} />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                <SelectItem value="general">{t.generalLabel || 'عام'}</SelectItem>
                                                <SelectItem value="direct-unit">{t.directCostLabel || 'تكلفة مباشرة على وحدة'}</SelectItem>
                                                <SelectItem value="shared-project">{t.sharedCostsTitle || 'تكلفة مشتركة على المشروع'}</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )} />
                                <FormField control={form.control} name="realEstateProjectId" render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>{t.realEstateProjectsTitle || 'المشروع العقاري'}</FormLabel>
                                        <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder={t.projectNameLabel || 'اختر المشروع'} />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                <SelectItem value="none">{t.itemGroupNone || 'بدون ربط'}</SelectItem>
                                                {realEstateProjectOptions.map((project) => (
                                                    <SelectItem key={project.id} value={project.id}>{project.name}</SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )} />
                                {selectedRealEstateCostType === 'direct-unit' && (
                                    <FormField control={form.control} name="realEstateUnitId" render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>{t.unitNameLabel || 'الوحدة العقارية'}</FormLabel>
                                            <Select value={field.value || 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)} disabled={!selectedRealEstateProjectId}>
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder={t.unitNamePlaceholder || 'اختر الوحدة'} />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    <SelectItem value="none">{t.itemGroupNone || 'بدون تحديد'}</SelectItem>
                                                    {selectedRealEstateUnits.map((unit: any) => (
                                                        <SelectItem key={unit.id} value={unit.id}>{unit.name || unit.unitCode}</SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )} />
                                )}
                                {selectedRealEstateCostType === 'shared-project' && (
                                    <FormField control={form.control} name="realEstateAllocationMethod" render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>{t.allocationMethodLabel || 'أساس التوزيع'}</FormLabel>
                                            <Select value={field.value || 'area'} onValueChange={field.onChange}>
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder={t.allocationMethodLabel || 'أساس التوزيع'} />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    <SelectItem value="area">{t.allocateByAreaLabel || 'حسب المساحة'}</SelectItem>
                                                    <SelectItem value="sale-value">{t.allocateBySaleValueLabel || 'حسب القيمة البيعية'}</SelectItem>
                                                    <SelectItem value="manual-share">{t.allocateByManualShareLabel || 'حسب النسبة اليدوية'}</SelectItem>
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )} />
                                )}
                            </div>
                        </div>
                    )}
                    {itemType === 'supplier' && (
                      <>
                        <FormField control={form.control} name="supplierNumber" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.supplierNumberLabel || 'رقم المورد'}</FormLabel>
                                <FormControl><Input {...field} readOnly value={field.value ?? nextSupplierNumber ?? ''} /></FormControl>
                                <p className="text-xs text-muted-foreground">{t.supplierNumberHelp || 'يُنشأ تلقائياً ويستخدم كمعرّف رئيسي'}</p>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="name" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.supplierNameLabel || 'اسم المورد'}</FormLabel>
                                <FormControl><Input {...field} value={field.value ?? ''} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="phone" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.supplierPhoneLabel || 'رقم الهاتف'}</FormLabel>
                                <FormControl><Input {...field} value={field.value ?? ''} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="address" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.supplierAddressLabel || 'العنوان'}</FormLabel>
                                <FormControl><Input {...field} value={field.value ?? ''} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="paymentTerms" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.supplierPaymentTermsLabel || 'شروط الدفع (أيام)'}</FormLabel>
                                <FormControl><Input type="number" step="1" min="0" {...field} value={field.value ?? ''} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="taxNumber" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.supplierTaxNumberLabel || 'الرقم الضريبي'}</FormLabel>
                                <FormControl><Input {...field} value={field.value ?? ''} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                      </>
                    )}
                    {itemType === 'sales-rep' && (
                      <>
                        <FormField control={form.control} name="name" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.salesRepNameLabel || 'اسم المندوب'}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="phone" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.salesRepPhoneLabel || 'رقم الهاتف'}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="region" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.salesRepRegionLabel || 'المنطقة'}</FormLabel>
                                <FormControl><Input {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="commissionRate" render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.salesRepCommissionLabel || 'نسبة العمولة (%)'}</FormLabel>
                                <FormControl><Input type="number" step="0.01" min="0" max="100" {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                      </>
                    )}
                                        {itemType === 'unit' && (
                                            <>
                                            <div className="rounded-xl border bg-muted/25 p-4 space-y-3">
                                            <FormField control={form.control} name="unitNumber" render={({ field }) => (
                                                        <FormItem>
                                                                <FormLabel>{t.unitNumberLabel || 'رقم الوحدة'}</FormLabel>
                                                    <FormControl><Input {...field} readOnly placeholder={isEditMode ? '' : (t.autoGeneratedLabel || 'يُولَّد تلقائياً عند الحفظ')} /></FormControl>
                                                                <FormMessage />
                                                        </FormItem>
                                                )} />
                                                <FormField control={form.control} name="description" render={({ field }) => (
                                                        <FormItem>
                                                                <FormLabel>{t.unitDescriptionLabel || 'الوصف'}</FormLabel>
                                                                <FormControl><Input {...field} placeholder={t.unitDescriptionPlaceholder || 'مثال: حبة'} /></FormControl>
                                                                <FormMessage />
                                                        </FormItem>
                                                )} />
                                                <FormField control={form.control} name="unitType" render={({ field }) => (
                                                    <FormItem>
                                                        <FormLabel>{t.unitTypeLabel || 'نوع الوحدة'}</FormLabel>
                                                        <Select value={(field.value === 'secondary' ? 'secondary' : 'primary')} onValueChange={field.onChange}>
                                                            <FormControl>
                                                                <SelectTrigger>
                                                                    <SelectValue placeholder={t.unitTypePlaceholder || 'اختر نوع الوحدة'} />
                                                                </SelectTrigger>
                                                            </FormControl>
                                                            <SelectContent>
                                                                <SelectItem value="primary">{t.primaryUnitLabel || 'وحدة رئيسية'}</SelectItem>
                                                                <SelectItem value="secondary">{t.secondaryUnitLabel || 'وحدة فرعية'}</SelectItem>
                                                            </SelectContent>
                                                        </Select>
                                                        <FormMessage />
                                                    </FormItem>
                                                )} />
                                                <FormField control={form.control} name="shortCode" render={({ field }) => (
                                                    <FormItem>
                                                        <FormLabel>{t.unitShortCodeLabel || 'الاختصار'}</FormLabel>
                                                        <FormControl><Input {...field} value={field.value || ''} placeholder={t.unitShortCodePlaceholder || 'مثال: كغ أو ctn'} /></FormControl>
                                                        <FormMessage />
                                                    </FormItem>
                                                )} />
                                            <FormField control={form.control} name="notes" render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>{t.notesLabel || 'ملاحظات'}</FormLabel>
                                                    <FormControl><Textarea {...field} value={field.value || ''} rows={3} placeholder={t.notesPlaceholder || 'ملاحظات اختيارية عن استخدام الوحدة'} /></FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )} />
                                            </div>
                                            </>
                                        )}
                    <DialogFooter className={`mt-4 border-t px-2 py-3 ${asPage ? 'bg-gradient-to-r from-slate-50/90 to-blue-50/50 dark:from-slate-900/90 dark:to-blue-950/30' : 'sticky bottom-0 bg-background/95 backdrop-blur'}`}>
                        <div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-2 rounded-xl border bg-muted/30 px-3 py-2">
                            <Button type="button" variant="outline" onClick={onFinished}>{tGlobal.cancel}</Button>
                            {itemType === 'material' && (
                                <Button type="button" variant="outline" onClick={runSmartAlternativeSuggestion} disabled={isPending}>
                                    {t?.smartSuggestAlternatives || 'اقتراح بدائل ذكي'}
                                </Button>
                            )}
                            <Button type="submit" disabled={isPending} className={asPage ? 'bg-gradient-to-r from-violet-600 to-blue-600 hover:from-violet-700 hover:to-blue-700 text-white shadow-md shadow-violet-200/50 dark:shadow-violet-900/30 border-0' : ''}>
                                {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                {t.saveChangesButton || tGlobal.submit || 'حفظ'}
                            </Button>
                        </div>
                    </DialogFooter>
                </form>
            </Form>

            <AlertDialog open={lowPriceWarningOpen} onOpenChange={setLowPriceWarningOpen}>
                <AlertDialogContent className="bg-destructive text-destructive-foreground border-destructive">
                    <AlertDialogHeader>
                        <AlertDialogTitle>
                            {lowPriceComparison?.isSecondary
                                ? (t?.lowSecondarySalePriceTitle || 'تنبيه: سعر بيع وحدة فرعية أقل من تكلفتها')
                                : (t?.lowSalePriceTitle || 'تنبيه: سعر البيع أقل من التكلفة')}
                        </AlertDialogTitle>
                        <AlertDialogDescription className="text-destructive-foreground/95">
                            {(lowPriceComparison?.isSecondary
                                ? (t?.lowSecondarySalePriceDescription || 'سعر بيع الوحدة الفرعية {unit} ({sale}) أقل من تكلفتها ({cost}). هل تريد المتابعة بالحفظ؟')
                                : (t?.lowSalePriceDescription || 'سعر البيع ({sale}) أقل من سعر التكلفة ({cost}). هل تريد المتابعة بالحفظ؟'))
                                .replace('{unit}', String(lowPriceComparison?.unitLabel || (t?.secondaryUnitLabel || 'الوحدة الفرعية')))
                                .replace('{sale}', String(lowPriceComparison?.salePrice ?? 0))
                                .replace('{cost}', String(lowPriceComparison?.purchasePrice ?? 0))}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel
                            className="border-destructive-foreground/40 text-destructive-foreground hover:bg-destructive-foreground/10"
                            onClick={() => {
                                setPendingNormalizedValues(null);
                                setLowPriceComparison(null);
                            }}
                        >
                            {tGlobal.cancel || 'إلغاء'}
                        </AlertDialogCancel>
                        <AlertDialogAction
                            className="bg-background text-destructive hover:bg-background/90"
                            onClick={() => {
                                const payload = pendingNormalizedValues;
                                setLowPriceWarningOpen(false);
                                setPendingNormalizedValues(null);
                                setLowPriceComparison(null);
                                if (payload) {
                                    persistListItem(payload);
                                }
                            }}
                        >
                            {t?.continueSaveLabel || 'متابعة الحفظ'}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            <Dialog open={!!suggestionPreviewItem} onOpenChange={(open) => { if (!open) setSuggestionPreviewItem(null); }}>
                <DialogContent className="max-w-3xl">
                    <DialogHeader>
                        <DialogTitle>{t?.previewTitle || 'معاينة'}</DialogTitle>
                        <DialogDescription>{t?.previewDescription || 'عرض كامل لبيانات الصنف المقترح.'}</DialogDescription>
                    </DialogHeader>
                    {suggestionPreviewItem && (
                        <div className="space-y-3 text-sm">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 rounded-md border p-3 bg-muted/20">
                                <div><span className="font-medium">{t?.itemNumberLabel || 'رقم الصنف'}:</span> {suggestionPreviewItem.itemNumber || '-'}</div>
                                <div><span className="font-medium">{t?.itemNameLabel || 'اسم الصنف'}:</span> {suggestionPreviewItem.name || '-'}</div>
                                <div><span className="font-medium">{t?.itemSymbolNameLabel || 'اسم رمز الصنف'}:</span> {suggestionPreviewItem.itemSymbolName || '-'}</div>
                                <div><span className="font-medium">{t?.globalReferenceNumberLabel || 'رقم مرجع عالمي'}:</span> {String((suggestionPreviewItem as any).globalReferenceNumber || '').trim() || '-'}</div>
                                <div className="md:col-span-2"><span className="font-medium">{t?.barcodeLabel || 'الباركود'}:</span> {[String(suggestionPreviewItem.barcode || '').trim(), ...(suggestionPreviewItem.additionalBarcodes || []).map((code) => String(code || '').trim())].filter(Boolean).join('، ') || '-'}</div>
                                <div className="md:col-span-2"><span className="font-medium">{t?.secondaryBarcodeLabel || 'باركود الوحدة الفرعية'}:</span> {String(suggestionPreviewItem.secondaryBarcode || '').trim() || '-'}</div>
                                <div><span className="font-medium">{t?.purchasePriceLabel || 'سعر الشراء'}:</span> {formatCurrency(Number(suggestionPreviewItem.purchasePrice || 0), currencySymbol)}</div>
                                <div><span className="font-medium">{t?.salePriceLabel || 'سعر البيع'}:</span> {formatCurrency(Number(suggestionPreviewItem.salePrice || 0), currencySymbol)}</div>
                                <div className="md:col-span-2"><span className="font-medium">{t?.additionalDetailsLabel || 'تفاصيل اضافيه'}:</span> {String(suggestionPreviewItem.additionalDetails || '').trim() || '-'}</div>
                            </div>
                            <div className="rounded-md border p-3">
                                <p className="mb-2 text-xs font-medium text-muted-foreground">{t?.allDataLabel || 'جميع البيانات'}</p>
                                <pre className="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/30 p-2 text-xs" dir="ltr">
                                    {JSON.stringify(suggestionPreviewItem, null, 2)}
                                </pre>
                            </div>
                        </div>
                    )}
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={() => setSuggestionPreviewItem(null)}>
                            {tGlobal?.close || tGlobal?.cancel || 'إغلاق'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog
                open={managedUnitDialogOpen}
                onOpenChange={(open) => {
                    if (!open) {
                        resolveManagedUnitDialog(null);
                    }
                }}
                modal={false}
            >
                <DialogContent className="max-w-md z-[70]">
                    <DialogHeader>
                        <DialogTitle>{t.addNewUnitLabel || 'إضافة عنصر جديد'}</DialogTitle>
                        <DialogDescription>
                            {t.addUnitPromptLabel || 'أدخل اسم الوحدة الجديدة'}
                        </DialogDescription>
                    </DialogHeader>
                    <div className="rounded-xl border bg-muted/25 p-3 space-y-3">
                        <div className="space-y-2">
                            <Label>{t.unitDescriptionLabel || 'الوصف'}</Label>
                            <Input
                                value={managedUnitDescriptionDraft}
                                onChange={(e) => setManagedUnitDescriptionDraft(e.target.value)}
                                placeholder={t.unitDescriptionPlaceholder || 'مثال: كرتونة'}
                                autoFocus
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        void saveManagedUnitFromDialog();
                                    }
                                }}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>{t.unitTypeLabel || 'نوع الوحدة'}</Label>
                            <Select value={managedUnitTypeDraft} onValueChange={(value) => setManagedUnitTypeDraft(value === 'secondary' ? 'secondary' : 'primary')}>
                                <SelectTrigger>
                                    <SelectValue placeholder={t.unitTypePlaceholder || 'اختر نوع الوحدة'} />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="primary">{t.primaryUnitLabel || 'وحدة رئيسية'}</SelectItem>
                                    <SelectItem value="secondary">{t.secondaryUnitLabel || 'وحدة فرعية'}</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            disabled={isManagedUnitSaving}
                            onClick={() => resolveManagedUnitDialog(null)}
                        >
                            {tGlobal.cancel || 'إلغاء'}
                        </Button>
                        <Button
                            type="button"
                            disabled={isManagedUnitSaving}
                            onClick={() => {
                                if (isManagedUnitSaving) return;
                                void saveManagedUnitFromDialog();
                            }}
                        >
                            {isManagedUnitSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            {t.saveChangesButton || tGlobal.submit || 'حفظ'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog
                open={productShapeQuickAddOpen}
                onOpenChange={(open) => {
                    if (!open) {
                        setProductShapeQuickAddOpen(false);
                        setProductShapeQuickAddName('');
                        setIsProductShapeQuickSaving(false);
                    }
                }}
                modal={false}
            >
                <DialogContent
                    className="max-w-md z-[70]"
                    onOpenAutoFocus={(event) => {
                        event.preventDefault();
                        setTimeout(() => {
                            productShapeQuickInputRef.current?.focus();
                            productShapeQuickInputRef.current?.select();
                        }, 0);
                    }}
                >
                    <DialogHeader>
                        <DialogTitle>{t.addProductShapeDefinition || 'إضافة شكل جديد'}</DialogTitle>
                        <DialogDescription>
                            {t.addProductShapeDefinitionHint || 'أدخل اسم الشكل ليتم إضافته مباشرة إلى إدارة الأحجام والأشكال.'}
                        </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-2">
                        <Label>{t.productShapeNameLabel || 'اسم الشكل'}</Label>
                        <Input
                            ref={productShapeQuickInputRef}
                            value={productShapeQuickAddName}
                            onChange={(e) => setProductShapeQuickAddName(e.target.value)}
                            placeholder={t.productShapeNamePlaceholder || 'مثال: كبير'}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    e.preventDefault();
                                    void saveQuickProductShapeDefinition();
                                }
                            }}
                        />
                    </div>
                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            disabled={isProductShapeQuickSaving}
                            onClick={() => {
                                setProductShapeQuickAddOpen(false);
                                setProductShapeQuickAddName('');
                            }}
                        >
                            {tGlobal.cancel || 'إلغاء'}
                        </Button>
                        <Button
                            type="button"
                            disabled={isProductShapeQuickSaving}
                            onClick={() => {
                                void saveQuickProductShapeDefinition();
                            }}
                        >
                            {isProductShapeQuickSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            {t.saveChangesButton || tGlobal.submit || 'حفظ'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>


            {/* ─── Bulk add shapes dialog ─────────────────────────────────── */}
            <EmployeeAddDialog
                open={salesRepQuickAddOpen}
                onOpenChange={setSalesRepQuickAddOpen}
                t={{ ...t, ...tGlobal }}
                defaultBusinessRole="مندوب مبيعات"
                lockBusinessRole
                onEmployeeCreated={(employee) => {
                    const createdRep: SalesRep | null = employee?.id
                        ? {
                            id: String(employee.id),
                            name: String(employee.name || '').trim(),
                            phone: String(employee.phone || '').trim(),
                            region: String(employee.region || '').trim(),
                            commissionRate: Number.isFinite(employee.commissionRate) ? Number(employee.commissionRate) : 0,
                        }
                        : null;
                    if (!createdRep) return;
                    setRuntimeSalesRepOptions((prev) => {
                        const exists = prev.some((entry) => String(entry.id || '') === createdRep.id);
                        if (exists) return prev;
                        return sortSalesRepOptions([...prev, createdRep]);
                    });
                    form.setValue('salesRepId', createdRep.id, { shouldDirty: true, shouldTouch: true });
                }}
            />

            <CustomerCategoryDialog
                open={categoryQuickAddOpen}
                onOpenChange={setCategoryQuickAddOpen}
                t={{ ...tGlobal, ...t }}
                onCategoryCreated={(category) => {
                    const normalized: CustomerCategory = {
                        id: String(category.id),
                        name: String(category.name),
                        categoryNumber: String(category.categoryNumber || '').trim() || undefined,
                        nameEn: String(category.nameEn || '').trim() || undefined,
                        discountPercent: Number(category.discountPercent || 0),
                        description: String(category.description || '').trim() || undefined,
                    };
                    setRuntimeCategoryOptions((prev) => {
                        if (prev.some((entry) => String(entry.id || '') === normalized.id || String(entry.name || '').trim().toLowerCase() === normalized.name.trim().toLowerCase())) {
                            return prev;
                        }
                        return sortCategoryOptions([...prev, normalized]);
                    });
                    form.setValue('category', normalized.name, { shouldDirty: true, shouldTouch: true });
                }}
            />
        </ContentWrapper>
    )
}

export function MaterialItemDialog({ items, t, tGlobal, itemGroups, categories, warehouses = [], initialValues, onFinished, onCreated, item, focusSalePrice, currencySymbol = '$', active = true }: { items: ProductionItem[], t: any, tGlobal: any, itemGroups?: ItemGroup[], categories?: CustomerCategory[], warehouses?: Warehouse[], initialValues?: Partial<ProductionItem>, onFinished: () => void, onCreated?: (item: Item) => void, item?: ProductionItem, focusSalePrice?: boolean, currencySymbol?: string, active?: boolean }) {
    return (
        <ItemDialog
            itemType="material"
            items={items}
            t={t}
            tGlobal={tGlobal}
            itemGroups={itemGroups}
            categories={categories}
            warehouses={warehouses}
            initialValues={initialValues}
            onFinished={onFinished}
            onCreated={onCreated}
            item={item}
            focusSalePrice={focusSalePrice}
            currencySymbol={currencySymbol}
            active={active}
        />
    );
}

export default function ListManager({ items, title, description, itemType, categories, itemGroups, salesReps, t, tGlobal, currencySymbol = '$', warehouses = [], warehousesEnabled = false, storeModuleEnabled = false, stockLocationsByMaterial = {}, internalTransferDocuments = [], inventoryMovements = [], unitDefinitions = [], productShapeDefinitions = [], realEstateProjects = [], chartOfAccounts = [], serverPagination }: ListManagerProps) {
    const router = useRouter();
    const pathname = usePathname();
    const isServerPaginatedMaterials = itemType === 'material' && serverPagination?.enabled;
    const [currentItems, setCurrentItems] = useState(items);
    const [dialogState, setDialogState] = useState<{ isOpen: boolean, item?: Item }>({ isOpen: false, item: undefined });
    const [initialValues, setInitialValues] = useState<Partial<ProductionItem> | undefined>(undefined);
    const [tableSearch, setTableSearch] = useState(serverPagination?.search || '');
    const [draftTableSearch, setDraftTableSearch] = useState(serverPagination?.search || '');
    const [isSearchInFlight, setIsSearchInFlight] = useState(false);
    const [currentPage, setCurrentPage] = useState(serverPagination?.page || 1);
    const [pageSize, setPageSize] = useState(serverPagination?.pageSize || 25);
    const [pageJumpInput, setPageJumpInput] = useState(String(serverPagination?.page || 1));
    const [showWarehouseBalance, setShowWarehouseBalance] = useState(false);
    const [dualRowView, setDualRowView] = useState(false);
    const [showAlternativesOnly, setShowAlternativesOnly] = useState(Boolean(serverPagination?.hasAlternativesOnly));
    const [showAvailableOnly, setShowAvailableOnly] = useState(Boolean(serverPagination?.availableOnly));
    type MaterialColumnFilterKey = 'itemNumber' | 'name' | 'itemSymbolName' | 'globalReferenceNumber' | 'barcode' | 'secondaryBarcode' | 'additionalDetails' | 'salePrice' | 'location';
    const emptyMaterialColumnFilters: Record<MaterialColumnFilterKey, string> = {
        itemNumber: '',
        name: '',
        itemSymbolName: '',
        globalReferenceNumber: '',
        barcode: '',
        secondaryBarcode: '',
        additionalDetails: '',
        salePrice: '',
        location: '',
    };
    const emptyMaterialFilterModes: Record<MaterialColumnFilterKey, MaterialFilterMatchMode> = {
        itemNumber: 'contains',
        name: 'contains',
        itemSymbolName: 'contains',
        globalReferenceNumber: 'contains',
        barcode: 'contains',
        secondaryBarcode: 'contains',
        additionalDetails: 'contains',
        salePrice: 'contains',
        location: 'contains',
    };
    const [materialColumnFilters, setMaterialColumnFilters] = useState<Record<MaterialColumnFilterKey, string>>({
        ...emptyMaterialColumnFilters,
        ...(serverPagination?.materialFilters || {}),
    });
    const [materialFilterModes, setMaterialFilterModes] = useState<Record<MaterialColumnFilterKey, MaterialFilterMatchMode>>({
        ...emptyMaterialFilterModes,
        ...(serverPagination?.materialFilterModes || {}),
    });
    const [draftMaterialColumnFilters, setDraftMaterialColumnFilters] = useState<Record<MaterialColumnFilterKey, string>>({
        ...emptyMaterialColumnFilters,
        ...(serverPagination?.materialFilters || {}),
    });
    const [activeMaterialColumnFilterKey, setActiveMaterialColumnFilterKey] = useState<MaterialColumnFilterKey | null>(null);
    const [isClientMounted, setIsClientMounted] = useState(false);
    type MaterialSortKey = 'itemNumber' | 'name' | 'itemSymbolName' | 'globalReferenceNumber' | 'barcode' | 'secondaryBarcode' | 'additionalDetails' | 'salePrice' | null;
    const [sortKey, setSortKey] = useState<MaterialSortKey>((serverPagination?.sortKey as MaterialSortKey) || null);
    const [sortDir, setSortDir] = useState<'asc' | 'desc'>(serverPagination?.sortDir || 'asc');
    const updateMaterialQuery = (updates: Record<string, string | number | null | undefined>) => {
        const currentSearch = typeof window !== 'undefined' ? window.location.search : '';
        const params = new URLSearchParams(currentSearch);
        Object.entries(updates).forEach(([key, value]) => {
            if (value === null || value === undefined || value === '') {
                params.delete(key);
                return;
            }
            params.set(key, String(value));
        });
        const qs = params.toString();
        const normalizedCurrent = currentSearch.startsWith('?') ? currentSearch.slice(1) : currentSearch;
        if (qs === normalizedCurrent) {
            setIsSearchInFlight(false);
            setActiveMaterialColumnFilterKey(null);
            return;
        }
        router.replace(qs ? `${pathname}?${qs}` : pathname);
    };
    const toggleSort = (key: MaterialSortKey) => {
        if (isServerPaginatedMaterials) {
            const nextDir = sortKey === key ? (sortDir === 'asc' ? 'desc' : 'asc') : 'asc';
            setSortKey(key);
            setSortDir(nextDir);
            updateMaterialQuery({ page: 1, sortKey: key, sortDir: nextDir });
            return;
        }
        if (sortKey === key) {
            setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
        } else {
            setSortKey(key);
            setSortDir('asc');
        }
    };
    const navigateToPage = (rawPage: number) => {
        const safePage = Math.min(totalPages, Math.max(1, Number(rawPage) || 1));
        if (isServerPaginatedMaterials) {
            updateMaterialQuery({ page: safePage });
            return;
        }
        setCurrentPage(safePage);
    };
    const [isMaterialImportOpen, setIsMaterialImportOpen] = useState(false);
    const [isBulkShapeDialogOpen, setIsBulkShapeDialogOpen] = useState(false);
    const [bulkShapeText, setBulkShapeText] = useState('');
    const [isBulkShapeSaving, setIsBulkShapeSaving] = useState(false);
    const [locationMaterialId, setLocationMaterialId] = useState<string | null>(null);
    const [transferDialogOpen, setTransferDialogOpen] = useState(false);
    const [previewItem, setPreviewItem] = useState<Item | null>(null);
    const [materialRowContextMenu, setMaterialRowContextMenu] = useState<{
        open: boolean;
        x: number;
        y: number;
        item: ProductionItem | null;
    }>({ open: false, x: 0, y: 0, item: null });
    const [transferMaterial, setTransferMaterial] = useState<ProductionItem | null>(null);
    const [lockedMaterialId, setLockedMaterialId] = useState<string | null>(null);
    const [transferState, setTransferState] = useState({
        fromWarehouseId: '',
        fromShelfId: '',
        toWarehouseId: '',
        toShelfId: '',
        quantity: '',
        date: '',
        note: '',
    });
    const [isDeletePending, startDeleteTransition] = useTransition();
    const [isTransferPending, startTransferTransition] = useTransition();
    const [isLockPending, startLockTransition] = useTransition();
    const { toast } = useToast();
    const handleBulkShapeAdd = async () => {
        const names = bulkShapeText
            .split('\n')
            .map((s) => s.trim())
            .filter(Boolean);
        if (names.length === 0) return;
        setIsBulkShapeSaving(true);
        const result = await handleBulkAddProductShapes(names);
        setIsBulkShapeSaving(false);
        if (result.error) {
            toast({ title: t.saveErrorTitle || 'خطأ', description: result.error, variant: 'destructive' });
            return;
        }
        const addedCount = (result.added || []).length;
        const skippedCount = (result.skipped || []).length;
        const msg = skippedCount > 0
            ? `تمت إضافة ${addedCount} شكل. تم تجاوز ${skippedCount} تكرار: ${(result.skipped || []).join('، ')}`
            : `تمت إضافة ${addedCount} شكل بنجاح.`;
        toast({ title: t.saveSuccessTitle || 'تم الحفظ', description: msg });
        setBulkShapeText('');
        setIsBulkShapeDialogOpen(false);
    };
    const shelvesByWarehouse = useMemo(() => {
        const map = new Map<string, { id: string; name: string }[]>();
        warehouses.forEach((wh) => map.set(wh.id, wh.shelves || []));
        return map;
    }, [warehouses]);
    const salesRepById = useMemo(() => {
        const map = new Map<string, SalesRep>();
        (salesReps || []).forEach((rep) => map.set(rep.id, rep));
        return map;
    }, [salesReps]);
    const realEstateProjectById = useMemo(() => {
        const map = new Map<string, RealEstateProject>();
        (realEstateProjects || []).forEach((project) => map.set(String(project.id || ''), project));
        return map;
    }, [realEstateProjects]);
    const getRealEstateCostTypeLabel = (value?: string) => {
        if (value === 'direct-unit') return t?.directCostLabel || 'تكلفة مباشرة';
        if (value === 'shared-project') return t?.sharedCostsTitle || 'تكلفة مشتركة';
        return t?.generalLabel || 'عام';
    };

    const getMaterialWarehouseTotals = (material: ProductionItem) => {
        if (!warehousesEnabled) return [] as Array<[string, number]>;
        const warehouseTotalsMap = (stockLocationsByMaterial[material.id] || []).reduce<Map<string, number>>((acc, entry) => {
            const warehouseName = String(entry.warehouseName || entry.warehouseId || '').trim();
            if (!warehouseName) return acc;
            acc.set(warehouseName, Number(acc.get(warehouseName) || 0) + Number(entry.quantity || 0));
            return acc;
        }, new Map<string, number>());

        return Array.from(warehouseTotalsMap.entries())
            .filter(([, qty]) => Number(qty || 0) > 0)
            .sort((a, b) => String(a[0]).localeCompare(String(b[0]), 'ar'));
    };

    const hasVisibleWarehouseBalance = (material: ProductionItem) => getMaterialWarehouseTotals(material).length > 0;

    const locationMaterial = locationMaterialId
        ? (currentItems.find((itm) => itm.id === locationMaterialId) as ProductionItem | undefined)
        : undefined;
    const locationEntriesRaw = locationMaterialId ? (stockLocationsByMaterial[locationMaterialId] || []) : [];
    const movementMetaByLocationKey = useMemo(() => {
        const meta = new Map<string, { latestAnyTs: number; latestInTs: number }>();
        if (!locationMaterialId) return meta;

        inventoryMovements.forEach((movement) => {
            const materialId = String((movement as any).materialId || '').trim();
            if (!materialId || materialId !== locationMaterialId) return;

            const warehouseId = String((movement as any).warehouseId || '').trim();
            const shelfId = String((movement as any).shelfId || '').trim();
            if (!warehouseId || !shelfId) return;

            const quantityIn = Number((movement as any).quantityIn || 0);
            const quantityOut = Number((movement as any).quantityOut || 0);
            if (!Number.isFinite(quantityIn) || !Number.isFinite(quantityOut)) return;
            if (quantityIn === 0 && quantityOut === 0) return;

            const rawDate = String((movement as any).date || (movement as any).movementDate || '').trim();
            const ts = rawDate ? Date.parse(rawDate) : NaN;
            const safeTs = Number.isFinite(ts) ? ts : 0;

            const key = `${warehouseId}::${shelfId}`;
            const current = meta.get(key) || { latestAnyTs: 0, latestInTs: 0 };
            current.latestAnyTs = Math.max(current.latestAnyTs, safeTs);
            if (quantityIn > 0) {
                current.latestInTs = Math.max(current.latestInTs, safeTs);
            }
            meta.set(key, current);
        });

        return meta;
    }, [inventoryMovements, locationMaterialId]);
    const locationEntries = useMemo(() => {
        if (!locationMaterialId) return [] as StockLocationBalance[];

        const quantityByKey = new Map<string, number>();
        const nameByKey = new Map<string, { warehouseName: string; shelfName: string }>();

        locationEntriesRaw.forEach((entry) => {
            const warehouseId = String(entry.warehouseId || '').trim();
            const shelfId = String(entry.shelfId || '').trim();
            if (!warehouseId || !shelfId) return;
            const key = `${warehouseId}::${shelfId}`;
            quantityByKey.set(key, Number(quantityByKey.get(key) || 0) + Number(entry.quantity || 0));
            nameByKey.set(key, {
                warehouseName: String(entry.warehouseName || '').trim(),
                shelfName: String(entry.shelfName || '').trim(),
            });
        });

        return Array.from(quantityByKey.entries())
            .map(([key, quantity]) => {
                const [warehouseId, shelfId] = key.split('::');
                const names = nameByKey.get(key);
                return {
                    materialId: locationMaterialId,
                    warehouseId,
                    warehouseName: names?.warehouseName || warehouseId,
                    shelfId,
                    shelfName: names?.shelfName || shelfId,
                    quantity,
                } as StockLocationBalance;
            })
            .filter((entry) => Number(entry.quantity || 0) > 0)
            .sort(
                (a, b) =>
                    (Number(movementMetaByLocationKey.get(`${b.warehouseId}::${b.shelfId}`)?.latestInTs || 0) - Number(movementMetaByLocationKey.get(`${a.warehouseId}::${a.shelfId}`)?.latestInTs || 0)) ||
                    (Number(movementMetaByLocationKey.get(`${b.warehouseId}::${b.shelfId}`)?.latestAnyTs || 0) - Number(movementMetaByLocationKey.get(`${a.warehouseId}::${a.shelfId}`)?.latestAnyTs || 0)) ||
                    Number(b.quantity || 0) - Number(a.quantity || 0) ||
                    String(a.warehouseName || '').localeCompare(String(b.warehouseName || ''), 'ar') ||
                    String(a.shelfName || '').localeCompare(String(b.shelfName || ''), 'ar')
            );
            }, [locationEntriesRaw, locationMaterialId, movementMetaByLocationKey]);
    const fromShelves = shelvesByWarehouse.get(transferState.fromWarehouseId) || [];
    const toShelves = shelvesByWarehouse.get(transferState.toWarehouseId) || [];
    const transferLocations = transferMaterial ? (stockLocationsByMaterial[transferMaterial.id] || []) : [];
    const selectedTransferLocation = transferLocations.find(
        (entry) => entry.warehouseId === transferState.fromWarehouseId && entry.shelfId === transferState.fromShelfId
    );
    const selectedAvailableQty = selectedTransferLocation?.quantity ?? 0;

    useEffect(() => {
        setCurrentItems(items);
    }, [items]);

    useEffect(() => {
        setIsClientMounted(true);
    }, []);

    useEffect(() => {
        if (!isServerPaginatedMaterials) return;
        setTableSearch(serverPagination?.search || '');
        setDraftTableSearch(serverPagination?.search || '');
        setMaterialColumnFilters({
            ...emptyMaterialColumnFilters,
            ...(serverPagination?.materialFilters || {}),
        });
        setMaterialFilterModes({
            ...emptyMaterialFilterModes,
            ...(serverPagination?.materialFilterModes || {}),
        });
        setDraftMaterialColumnFilters({
            ...emptyMaterialColumnFilters,
            ...(serverPagination?.materialFilters || {}),
        });
        setIsSearchInFlight(false);
        setActiveMaterialColumnFilterKey(null);
        setCurrentPage(serverPagination?.page || 1);
        setPageSize(serverPagination?.pageSize || 25);
        setSortKey((serverPagination?.sortKey as MaterialSortKey) || null);
        setSortDir(serverPagination?.sortDir || 'asc');
        setShowAlternativesOnly(Boolean(serverPagination?.hasAlternativesOnly));
        setShowAvailableOnly(Boolean(serverPagination?.availableOnly));
    }, [isServerPaginatedMaterials, serverPagination?.page, serverPagination?.pageSize, serverPagination?.search, serverPagination?.sortKey, serverPagination?.sortDir, serverPagination?.materialFilters, serverPagination?.materialFilterModes, serverPagination?.hasAlternativesOnly, serverPagination?.availableOnly]);

    useEffect(() => {
        setPageJumpInput(String(currentPage));
    }, [currentPage]);

    const handleItemCreated = (created: Item) => {
        setCurrentItems((prev) => {
            const exists = prev.some((itm) => itm.id === created.id);
            return exists ? prev : [created, ...prev];
        });
    };

    const openTransferDialog = (material: ProductionItem) => {
        const now = new Date();
        const todayLocal = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
        startLockTransition(async () => {
            const lockResult = await handleAcquireTransferLock({ materialId: material.id });
            if (!lockResult?.success) {
                const lockedBy = lockResult?.lockedBy || (t?.lockedByAnother ?? 'مستخدم آخر');
                toast({
                    title: t?.transferErrorTitle ?? tGlobal?.error ?? 'خطأ',
                    description: t?.transferLockedMessage
                        ? t.transferLockedMessage.replace('{name}', lockedBy)
                        : `الصنف قيد النقل من قبل ${lockedBy}`,
                    variant: 'destructive',
                });
                return;
            }

            setTransferMaterial(material);
            setLockedMaterialId(material.id);
            setTransferState({
                fromWarehouseId: '',
                fromShelfId: '',
                toWarehouseId: '',
                toShelfId: '',
                quantity: '',
                date: todayLocal,
                note: '',
            });
            setTransferDialogOpen(true);
        });
    };

    const closeTransferDialog = () => {
        if (lockedMaterialId) {
            startLockTransition(async () => {
                await handleReleaseTransferLock({ materialId: lockedMaterialId });
            });
        }
        setLockedMaterialId(null);
        setTransferDialogOpen(false);
        setTransferMaterial(null);
        setTransferState({
            fromWarehouseId: '',
            fromShelfId: '',
            toWarehouseId: '',
            toShelfId: '',
            quantity: '',
            date: '',
            note: '',
        });
    };

    const closeDialog = () => {
        setDialogState({ isOpen: false, item: undefined });
        setInitialValues(undefined);
    };

    const handleDuplicateMaterial = (material: ProductionItem) => {
        const normalizedSecondaryUnits = Array.isArray((material as any).secondaryUnits)
            ? (material as any).secondaryUnits.map((entry: any) => ({
                ...entry,
                barcode: '',
            }))
            : [];

        const alternatives = Array.from(new Set([
            ...((material as any).alternativeItemIds || []),
            material.id,
        ].map((id) => String(id || '').trim()).filter(Boolean)));

        const init: Partial<ProductionItem> = {
            ...material,
            // Leave item number empty so the form/server allocates a safe unique value.
            itemNumber: '',
            // Barcode must be entered manually or auto-generated on save if left empty.
            barcode: '',
            secondaryBarcode: '',
            additionalBarcodes: [],
            secondaryUnits: normalizedSecondaryUnits,
            alternativeItemIds: alternatives,
            name: `${material.name || ''} - ${t?.copySuffix || 'نسخة'}`.trim(),
        };

        setInitialValues(init);
        setDialogState({ isOpen: true, item: undefined });
    };

    const handleMaterialRowContextMenu = (event: ReactMouseEvent, material: ProductionItem) => {
        event.preventDefault();
        setMaterialRowContextMenu({
            open: true,
            x: event.clientX,
            y: event.clientY,
            item: material,
        });
    };

    useEffect(() => {
        if (itemType !== 'material' || typeof window === 'undefined') return;
        const params = new URLSearchParams(window.location.search);
        if (params.get('add') !== '1') return;

        const barcode = params.get('barcode') || '';
        const name = params.get('name') || '';
        const price = params.get('price');

        const init: Partial<ProductionItem> = {};
        if (barcode) init.barcode = barcode;
        if (name) init.name = name;
        if (price && !Number.isNaN(Number(price))) init.salePrice = Number(price);

        setInitialValues(init);
        setDialogState({ isOpen: true, item: undefined });

        params.delete('add');
        const newQuery = params.toString();
        const newUrl = `${window.location.pathname}${newQuery ? `?${newQuery}` : ''}`;
        window.history.replaceState({}, '', newUrl);
    }, [itemType]);

    useEffect(() => {
        return () => {
            if (lockedMaterialId) {
                handleReleaseTransferLock({ materialId: lockedMaterialId });
            }
        };
    }, [lockedMaterialId]);

    const onDelete = (id: string) => {
        startDeleteTransition(async () => {
            const result = await handleDeleteListItem(itemType, id);
            if (result.success) {
                toast({ title: t.deleteSuccessTitle });
                setCurrentItems((prev) => prev.filter((itm) => itm.id !== id));
            } else {
                toast({ title: t.deleteErrorTitle, description: result.error, variant: 'destructive' });
            }
        });
    }

    const onSubmitTransfer = () => {
        if (!transferMaterial) return;
        if (!warehousesEnabled) {
            toast({ title: tGlobal?.error ?? 'Error', description: t?.warehouseDisabled ?? 'المخازن غير مفعلة.', variant: 'destructive' });
            return;
        }
        if (!transferState.fromWarehouseId || !transferState.fromShelfId) {
            toast({ title: t?.transferErrorTitle ?? tGlobal?.error ?? 'خطأ', description: t?.selectSourceLocation ?? 'اختر موقع الصنف المراد النقل منه.', variant: 'destructive' });
            return;
        }
        const requestedQty = Number(transferState.quantity || 0);
        const availableQty = (stockLocationsByMaterial[transferMaterial.id] || []).find(
            (entry) => entry.warehouseId === transferState.fromWarehouseId && entry.shelfId === transferState.fromShelfId
        )?.quantity ?? 0;
        if (!Number.isFinite(requestedQty) || requestedQty <= 0) {
            toast({ title: t?.transferErrorTitle ?? tGlobal?.error ?? 'خطأ', description: t?.quantityInvalid ?? 'الكمية غير صحيحة.', variant: 'destructive' });
            return;
        }
        if (requestedQty > availableQty) {
            toast({ title: t?.transferErrorTitle ?? tGlobal?.error ?? 'خطأ', description: t?.insufficientStock ?? 'الكمية المطلوبة أكبر من الرصيد المتاح.', variant: 'destructive' });
            return;
        }
        startTransferTransition(async () => {
            const result = await handleCreateInternalTransfer({
                materialId: transferMaterial.id,
                quantity: requestedQty,
                fromWarehouseId: transferState.fromWarehouseId,
                fromShelfId: transferState.fromShelfId,
                toWarehouseId: transferState.toWarehouseId,
                toShelfId: transferState.toShelfId,
                date: transferState.date || undefined,
                note: transferState.note || undefined,
            });

            if (result.success) {
                if (lockedMaterialId) {
                    await handleReleaseTransferLock({ materialId: lockedMaterialId });
                }
                toast({ title: t?.transferSuccessTitle ?? 'تم نقل الصنف بنجاح' });
                closeTransferDialog();
            } else {
                toast({ title: t?.transferErrorTitle ?? tGlobal?.error ?? 'خطأ', description: result.error, variant: 'destructive' });
            }
        });
    };

    const normalizeSearchText = (value: string) => {
        return String(value || '')
            .toLowerCase()
            .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
            .replace(/[إأآٱ]/g, 'ا')
            .replace(/ى/g, 'ي')
            .replace(/ؤ/g, 'و')
            .replace(/ئ/g, 'ي')
            .replace(/ة/g, 'ه')
            .replace(/\s+/g, '')
            .replace(/[^\p{L}\p{N}]+/gu, '');
    };

    const sortChars = (value: string) => normalizeSearchText(value).split('').sort().join('');

    const fuzzyMatchToken = (token: string, field: string): boolean => {
        if (field.includes(token)) return true;
        const tLen = token.length;
        const fLen = field.length;
        if (Math.abs(tLen - fLen) > 1) {
            // Substring scan with edit-distance 1 for longer tokens
            if (tLen < 3) return false;
            const windowSize = tLen;
            for (let start = 0; start <= fLen - windowSize + 1; start++) {
                const window = field.slice(start, start + windowSize);
                let diff = 0;
                for (let k = 0; k < tLen && diff <= 1; k++) {
                    if (window[k] !== token[k]) diff++;
                }
                if (diff <= 1) return true;
            }
            return false;
        }
        // Full-string edit-distance 1
        const dp: number[] = Array.from({ length: tLen + 1 }, (_, i) => i);
        for (let j = 1; j <= fLen; j++) {
            let prev = dp[0];
            dp[0] = j;
            for (let i = 1; i <= tLen; i++) {
                const temp = dp[i];
                dp[i] = token[i - 1] === field[j - 1]
                    ? prev
                    : 1 + Math.min(prev, dp[i], dp[i - 1]);
                prev = temp;
            }
        }
        return dp[tLen] <= 1;
    };

    const fuzzyStartsWithToken = (token: string, field: string): boolean => {
        if (!token) return true;
        if (!field) return false;
        if (field.startsWith(token)) return true;

        const minLength = Math.max(1, token.length - 1);
        const maxLength = Math.min(field.length, token.length + 1);
        for (let length = minLength; length <= maxLength; length += 1) {
            const prefix = field.slice(0, length);
            if (fuzzyMatchToken(token, prefix)) return true;
        }
        return false;
    };

    const fuzzyEndsWithToken = (token: string, field: string): boolean => {
        if (!token) return true;
        if (!field) return false;
        if (field.endsWith(token)) return true;

        const minLength = Math.max(1, token.length - 1);
        const maxLength = Math.min(field.length, token.length + 1);
        for (let length = minLength; length <= maxLength; length += 1) {
            const suffix = field.slice(field.length - length);
            if (fuzzyMatchToken(token, suffix)) return true;
        }
        return false;
    };

    const filteredItems = useMemo(() => {
        let sourceItems = currentItems;

        if (itemType === 'material' && showAlternativesOnly) {
            sourceItems = sourceItems.filter((item) => {
                const alternativeIds = Array.isArray((item as any)?.alternativeItemIds)
                    ? (item as any).alternativeItemIds
                    : [];
                return alternativeIds.some((entry: any) => String(entry || '').trim() !== '');
            });
        }

        if (itemType === 'material' && showAvailableOnly) {
            sourceItems = sourceItems.filter((item) => {
                const material = item as ProductionItem;
                return hasVisibleWarehouseBalance(material);
            });
        }

        if (isServerPaginatedMaterials) return sourceItems;

        const query = tableSearch.trim();
        const hasMaterialColumnFilters = itemType === 'material'
            && Object.values(materialColumnFilters).some((value) => String(value || '').trim() !== '');
        if (!query && !hasMaterialColumnFilters) return sourceItems;

        const tokens = query
            .split(/\s+/)
            .map((part) => ({
                normalized: normalizeSearchText(part),
                sorted: sortChars(part),
            }))
            .filter((part) => part.normalized.length > 0);

        return sourceItems.filter((item) => {
            const materialItem = item as ProductionItem;
            const customerItem = item as Customer;
            const supplierItem = item as Supplier;
            const salesRepItem = item as SalesRep;
            const unitItem = item as ListManagedUnit;

            let fields: string[] = [];
            if (itemType === 'material') {
                const locationText = warehousesEnabled
                    ? (stockLocationsByMaterial[materialItem.id] || [])
                        .map((entry) => `${entry.warehouseName || ''} ${entry.shelfName || ''}`.trim())
                        .join(' ')
                    : '';

                const materialFieldValues: Record<MaterialColumnFilterKey, string> = {
                    itemNumber: String(materialItem.itemNumber || ''),
                    name: String(materialItem.name || ''),
                    itemSymbolName: String(materialItem.itemSymbolName || ''),
                    globalReferenceNumber: String((materialItem as any).globalReferenceNumber || ''),
                    barcode: `${String(materialItem.barcode || '')} ${(materialItem.additionalBarcodes || []).join(' ')}`,
                    secondaryBarcode: `${String(materialItem.secondaryBarcode || '')} ${Array.isArray((materialItem as any).secondaryUnits)
                        ? (materialItem as any).secondaryUnits.map((entry: any) => entry?.barcode).filter(Boolean).join(' ')
                        : ''}`,
                    additionalDetails: String(materialItem.additionalDetails || ''),
                    salePrice: String(materialItem.salePrice ?? ''),
                    location: String(locationText || ''),
                };

                const matchesColumnFilters = Object.entries(materialColumnFilters).every(([rawKey, rawValue]) => {
                    const key = rawKey as MaterialColumnFilterKey;
                    const filterToken = normalizeSearchText(String(rawValue || ''));
                    if (!filterToken) return true;
                    const fieldToken = normalizeSearchText(materialFieldValues[key] || '');
                    const mode = materialFilterModes[key] || 'contains';
                    if (mode === 'startsWith') return fuzzyStartsWithToken(filterToken, fieldToken);
                    if (mode === 'endsWith') return fuzzyEndsWithToken(filterToken, fieldToken);
                    if (fieldToken.includes(filterToken)) return true;
                    return fuzzyMatchToken(filterToken, fieldToken);
                });

                if (!matchesColumnFilters) {
                    return false;
                }

                fields = [
                    materialItem.itemNumber,
                    materialItem.name,
                    materialItem.itemSymbolName || '',
                    (materialItem as any).globalReferenceNumber || '',
                    materialItem.barcode || '',
                    (materialItem.additionalBarcodes || []).join(' '),
                    materialItem.secondaryBarcode || '',
                    Array.isArray((materialItem as any).secondaryUnits)
                        ? (materialItem as any).secondaryUnits.map((entry: any) => `${entry?.unit || ''} ${entry?.barcode || ''}`).join(' ')
                        : '',
                    String(materialItem.salePrice ?? ''),
                    materialItem.additionalDetails || '',
                    ...(warehousesEnabled ? [locationText] : []),
                ];
            } else if (itemType === 'customer') {
                const salesRepName = customerItem.salesRepId ? (salesRepById.get(customerItem.salesRepId)?.name || '') : '';
                fields = [
                    customerItem.customerNumber || '',
                    customerItem.name || '',
                    customerItem.phone || '',
                    String(customerItem.creditLimit ?? ''),
                    customerItem.address || '',
                    customerItem.category || '',
                    salesRepName,
                ];
            } else if (itemType === 'supplier') {
                fields = [
                    supplierItem.supplierNumber || '',
                    supplierItem.name || '',
                    supplierItem.phone || '',
                    supplierItem.address || '',
                    String(supplierItem.paymentTerms ?? ''),
                    supplierItem.taxNumber || '',
                ];
            } else if (itemType === 'sales-rep') {
                fields = [
                    salesRepItem.name || '',
                    salesRepItem.phone || '',
                    salesRepItem.region || '',
                    String(salesRepItem.commissionRate ?? ''),
                ];
            } else if (itemType === 'unit') {
                fields = [
                    unitItem.unitNumber || '',
                    unitItem.description || '',
                ];
            } else {
                fields = [item.name || ''];
            }

            const normalizedFields = fields.map((field) => normalizeSearchText(field)).filter(Boolean);
            const sortedFields = normalizedFields.map((field) => field.split('').sort().join(''));

            if (tokens.length === 0) {
                return true;
            }

            return tokens.every((token) => {
                if (!token.normalized) return true;
                return normalizedFields.some((field, index) => {
                    if (fuzzyMatchToken(token.normalized, field)) return true;
                    if (!token.sorted) return false;
                    return sortedFields[index]?.includes(token.sorted);
                });
            });
        });
    }, [currentItems, isServerPaginatedMaterials, itemType, showAlternativesOnly, showAvailableOnly, tableSearch, materialColumnFilters, materialFilterModes, salesRepById, stockLocationsByMaterial, warehousesEnabled]);

    const sortedItems = useMemo(() => {
        if (isServerPaginatedMaterials) return filteredItems;
        if (!sortKey || itemType !== 'material') return filteredItems;
        return [...filteredItems].sort((a, b) => {
            const ma = a as ProductionItem;
            const mb = b as ProductionItem;
            let va: string | number = '';
            let vb: string | number = '';
            if (sortKey === 'salePrice') {
                va = ma.salePrice ?? 0;
                vb = mb.salePrice ?? 0;
                return sortDir === 'asc' ? (va as number) - (vb as number) : (vb as number) - (va as number);
            }
            if (sortKey === 'itemNumber') {
                // sort numerically when possible
                const na = parseFloat(ma.itemNumber || '');
                const nb = parseFloat(mb.itemNumber || '');
                if (!isNaN(na) && !isNaN(nb)) return sortDir === 'asc' ? na - nb : nb - na;
                va = ma.itemNumber || ''; vb = mb.itemNumber || '';
            } else if (sortKey === 'name') { va = ma.name || ''; vb = mb.name || ''; }
            else if (sortKey === 'itemSymbolName') { va = ma.itemSymbolName || ''; vb = mb.itemSymbolName || ''; }
            else if (sortKey === 'globalReferenceNumber') { va = (ma as any).globalReferenceNumber || ''; vb = (mb as any).globalReferenceNumber || ''; }
            else if (sortKey === 'barcode') { va = ma.barcode || ''; vb = mb.barcode || ''; }
            else if (sortKey === 'secondaryBarcode') { va = ma.secondaryBarcode || ''; vb = mb.secondaryBarcode || ''; }
            else if (sortKey === 'additionalDetails') { va = ma.additionalDetails || ''; vb = mb.additionalDetails || ''; }
            const cmp = String(va).localeCompare(String(vb), 'ar', { numeric: true });
            return sortDir === 'asc' ? cmp : -cmp;
        });
    }, [filteredItems, isServerPaginatedMaterials, sortKey, sortDir, itemType]);

    const totalItemsCount = isServerPaginatedMaterials
        ? Number(serverPagination?.totalItems || 0)
        : sortedItems.length;
    const totalPages = isServerPaginatedMaterials
        ? Math.max(1, Number(serverPagination?.totalPages || 1))
        : Math.max(1, Math.ceil(totalItemsCount / pageSize));
    const effectiveCurrentPage = currentPage;
    const paginatedItems = useMemo(() => {
        if (isServerPaginatedMaterials) return currentItems;
        const start = (currentPage - 1) * pageSize;
        return sortedItems.slice(start, start + pageSize);
    }, [currentItems, sortedItems, currentPage, pageSize, isServerPaginatedMaterials]);

    const materialsStats = useMemo(() => {
        if (itemType !== 'material') return null;
        if (isServerPaginatedMaterials) {
            return {
                totalSaleValue: Number(serverPagination?.totalSaleValue || 0),
                withBarcodeCount: Number(serverPagination?.withBarcodeCount || 0),
                withoutBarcodeCount: Math.max(0, totalItemsCount - Number(serverPagination?.withBarcodeCount || 0)),
            };
        }
        const source = sortedItems as ProductionItem[];
        const totalSaleValue = source.reduce((sum, itm) => sum + Number(itm.salePrice || 0), 0);
        const withBarcodeCount = source.filter((itm) => String(itm.barcode || '').trim() !== '').length;
        return {
            totalSaleValue,
            withBarcodeCount,
            withoutBarcodeCount: Math.max(0, source.length - withBarcodeCount),
        };
    }, [itemType, isServerPaginatedMaterials, serverPagination?.totalSaleValue, serverPagination?.withBarcodeCount, totalItemsCount, sortedItems]);

    useEffect(() => {
        if (isServerPaginatedMaterials) return;
        setCurrentPage(1);
    }, [tableSearch, materialColumnFilters, materialFilterModes, showAlternativesOnly, showAvailableOnly, pageSize, itemType, isServerPaginatedMaterials]);

    useEffect(() => {
        if (isServerPaginatedMaterials) return;
        if (currentPage > totalPages) {
            setCurrentPage(totalPages);
        }
    }, [currentPage, totalPages, isServerPaginatedMaterials]);

    const commitTableSearch = () => {
        const nextValue = isServerPaginatedMaterials ? draftTableSearch : tableSearch;
        const normalizedNext = String(nextValue || '').trim();
        const normalizedCurrent = String(tableSearch || '').trim();

        if (normalizedNext === normalizedCurrent) {
            return;
        }

        setTableSearch(nextValue);

        if (isServerPaginatedMaterials) {
            setIsSearchInFlight(true);
            updateMaterialQuery({ page: 1, search: normalizedNext || null });
        }
    };

    const commitMaterialColumnFilter = (key: MaterialColumnFilterKey, value: string) => {
        const trimmedValue = String(value || '').trim();
        setDraftMaterialColumnFilters((prev) => ({ ...prev, [key]: value }));
        if (isServerPaginatedMaterials) {
            const previousValue = String(materialColumnFilters[key] || '').trim();
            if (trimmedValue === previousValue) {
                return;
            }

            setMaterialColumnFilters((prev) => ({ ...prev, [key]: value }));
            setIsSearchInFlight(true);
            setActiveMaterialColumnFilterKey(key);
            updateMaterialQuery({ page: 1, [key]: trimmedValue || null });
            return;
        }
        setMaterialColumnFilters((prev) => {
            if (String(prev[key] || '').trim() === String(value || '').trim()) {
                return prev;
            }
            return { ...prev, [key]: value };
        });
    };

    const getMaterialFilterModeLabel = (mode: MaterialFilterMatchMode) => {
        if (mode === 'startsWith') return t?.startsWithLabel || 'يبدأ بـ';
        if (mode === 'endsWith') return t?.endsWithLabel || 'ينتهي بـ';
        return t?.containsLabel || 'يحتوي';
    };

    const commitMaterialFilterMode = (key: MaterialColumnFilterKey, mode: MaterialFilterMatchMode) => {
        setMaterialFilterModes((prev) => {
            if (prev[key] === mode) return prev;
            return { ...prev, [key]: mode };
        });

        if (!isServerPaginatedMaterials) return;

        const modeParamKey = `${key}Mode`;
        setIsSearchInFlight(true);
        setActiveMaterialColumnFilterKey(key);
        updateMaterialQuery({ page: 1, [modeParamKey]: mode === 'contains' ? null : mode });
    };

    const hasActiveMaterialColumnFilters = itemType === 'material'
        && Object.values(draftMaterialColumnFilters).some((value) => String(value || '').trim() !== '');

    const clearMaterialColumnFilters = () => {
        setDraftMaterialColumnFilters({ ...emptyMaterialColumnFilters });
        setMaterialColumnFilters({ ...emptyMaterialColumnFilters });
        setMaterialFilterModes({ ...emptyMaterialFilterModes });

        if (isServerPaginatedMaterials) {
            setIsSearchInFlight(true);
            setActiveMaterialColumnFilterKey(null);
            updateMaterialQuery({
                page: 1,
                itemNumber: null,
                name: null,
                itemSymbolName: null,
                globalReferenceNumber: null,
                barcode: null,
                secondaryBarcode: null,
                additionalDetails: null,
                salePrice: null,
                location: null,
                itemNumberMode: null,
                nameMode: null,
                itemSymbolNameMode: null,
                globalReferenceNumberMode: null,
                barcodeMode: null,
                secondaryBarcodeMode: null,
                additionalDetailsMode: null,
                salePriceMode: null,
                locationMode: null,
            });
        }
    };

    const renderMaterialColumnFilterInput = (key: MaterialColumnFilterKey, options?: { align?: 'left' | 'right' }) => {
        const value = draftMaterialColumnFilters[key] || '';
        const isActiveLoading = isServerPaginatedMaterials && isSearchInFlight && activeMaterialColumnFilterKey === key;
        const hasAppliedFilter = String(materialColumnFilters[key] || '').trim() !== '';
        const alignmentClass = options?.align === 'right' ? 'text-right' : '';
        const currentMode = materialFilterModes[key] || 'contains';

        return (
            <div className="relative w-full">
                <Input
                    className={`h-8 w-full px-8 ${alignmentClass} ${hasAppliedFilter ? 'border-emerald-500 bg-emerald-50/60 focus-visible:ring-emerald-500' : ''}`.trim()}
                    placeholder={t?.searchLabel || 'بحث'}
                    value={value}
                    onChange={(e) => setDraftMaterialColumnFilters((prev) => ({ ...prev, [key]: e.target.value }))}
                    onBlur={(e) => commitMaterialColumnFilter(key, e.target.value)}
                    onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            commitMaterialColumnFilter(key, (e.currentTarget as HTMLInputElement).value);
                            (e.currentTarget as HTMLInputElement).blur();
                        }
                    }}
                />
                <div className="absolute left-1 top-1/2 -translate-y-1/2">
                    {isActiveLoading ? (
                        <span className="pointer-events-none inline-flex h-6 w-6 items-center justify-center text-muted-foreground" aria-hidden="true">
                            <Loader2 className="h-4 w-4 animate-spin" />
                        </span>
                    ) : !isClientMounted ? (
                        <button
                            type="button"
                            className="inline-flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground"
                            aria-label={t?.matchModeLabel || 'نوع المطابقة'}
                            title={`${t?.matchModeLabel || 'نوع المطابقة'}: ${getMaterialFilterModeLabel(currentMode)}`}
                            disabled
                        >
                            <Filter className="h-3.5 w-3.5" />
                        </button>
                    ) : (
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <button
                                    type="button"
                                    className="inline-flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                                    aria-label={t?.matchModeLabel || 'نوع المطابقة'}
                                    title={`${t?.matchModeLabel || 'نوع المطابقة'}: ${getMaterialFilterModeLabel(currentMode)}`}
                                >
                                    <Filter className="h-3.5 w-3.5" />
                                </button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="start" className="min-w-[140px]">
                                <DropdownMenuItem onClick={() => commitMaterialFilterMode(key, 'contains')}>
                                    {currentMode === 'contains' ? '● ' : ''}{t?.containsLabel || 'يحتوي'}
                                </DropdownMenuItem>
                                <DropdownMenuItem onClick={() => commitMaterialFilterMode(key, 'startsWith')}>
                                    {currentMode === 'startsWith' ? '● ' : ''}{t?.startsWithLabel || 'يبدأ بـ'}
                                </DropdownMenuItem>
                                <DropdownMenuItem onClick={() => commitMaterialFilterMode(key, 'endsWith')}>
                                    {currentMode === 'endsWith' ? '● ' : ''}{t?.endsWithLabel || 'ينتهي بـ'}
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    )}
                </div>
                {value ? (
                    <button
                        type="button"
                        onClick={() => commitMaterialColumnFilter(key, '')}
                        className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none"
                        aria-label={t?.clearSearchLabel || 'مسح البحث'}
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    </button>
                ) : null}
            </div>
        );
    };

    return (
        <>
            <div className="mx-auto w-full max-w-none">
            <Card className="rounded-2xl border bg-card/90 shadow-sm">
                <CardHeader>
                    <div className="rounded-xl border bg-muted/30 p-3 space-y-3">
                        <div className="grid gap-2">
                            <CardTitle>{title}</CardTitle>
                        </div>
                        <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                        <div className="relative sm:max-w-lg w-full">
                            <Input
                                placeholder={t?.advancedSearchPlaceholder || 'بحث متقدم في جميع الأعمدة...'}
                                value={isServerPaginatedMaterials ? draftTableSearch : tableSearch}
                                onChange={(e) => {
                                    if (isServerPaginatedMaterials) {
                                        setDraftTableSearch(e.target.value);
                                        return;
                                    }
                                    setTableSearch(e.target.value);
                                }}
                                onBlur={() => {
                                    if (isServerPaginatedMaterials) {
                                        commitTableSearch();
                                    }
                                }}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        commitTableSearch();
                                        (e.currentTarget as HTMLInputElement).blur();
                                    }
                                }}
                                className="w-full pr-8"
                            />
                            {isServerPaginatedMaterials && isSearchInFlight ? (
                                <span className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground" aria-hidden="true">
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                </span>
                            ) : null}
                            {(isServerPaginatedMaterials ? draftTableSearch : tableSearch) ? (
                                <button
                                    type="button"
                                    onClick={() => {
                                        if (isServerPaginatedMaterials) {
                                            setDraftTableSearch('');
                                            setTableSearch('');
                                            setIsSearchInFlight(true);
                                            updateMaterialQuery({ page: 1, search: null });
                                            return;
                                        }
                                        setTableSearch('');
                                    }}
                                    className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none"
                                    aria-label="مسح البحث"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                                </button>
                            ) : null}
                        </div>
                        <div className="sm:ml-auto flex flex-wrap items-center gap-2">
                            <div className="flex items-center gap-2">
                                <span className="text-xs text-muted-foreground">{t?.pageSizeLabel || 'حجم الصفحة'}</span>
                                {isClientMounted ? (
                                    <Select value={String(pageSize)} onValueChange={(value) => {
                                        const nextPageSize = Number(value) || 25;
                                        setPageSize(nextPageSize);
                                        if (isServerPaginatedMaterials) {
                                            updateMaterialQuery({ page: 1, pageSize: nextPageSize });
                                        }
                                    }}>
                                        <SelectTrigger className="h-8 w-[90px]">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="10">10</SelectItem>
                                            <SelectItem value="25">25</SelectItem>
                                            <SelectItem value="50">50</SelectItem>
                                            <SelectItem value="100">100</SelectItem>
                                        </SelectContent>
                                    </Select>
                                ) : (
                                    <div className="flex h-8 w-[90px] items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground">
                                        <span>{pageSize}</span>
                                        <ChevronDown className="h-4 w-4 opacity-50" />
                                    </div>
                                )}
                            </div>
                            {itemType === 'material' && (
                                <Button size="sm" variant="outline" className="gap-1 me-2" onClick={() => setIsMaterialImportOpen(true)}>
                                    <Upload className="h-3.5 w-3.5" />
                                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">استيراد من Excel</span>
                                </Button>
                            )}
                            {itemType === 'material' && (
                                <Button
                                    size="sm"
                                    variant={dualRowView ? 'secondary' : 'outline'}
                                    className="gap-1 me-2"
                                    onClick={() => setDualRowView((v) => !v)}
                                    title={dualRowView ? 'عرض سطر واحد' : 'عرض سطرين'}
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                                        <line x1="3" y1="6" x2="21" y2="6" />
                                        <line x1="3" y1="12" x2="21" y2="12" />
                                        {dualRowView ? null : <line x1="3" y1="18" x2="21" y2="18" />}
                                    </svg>
                                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">{dualRowView ? 'سطر واحد' : 'سطرين'}</span>
                                </Button>
                            )}
                            {itemType === 'material' && (
                                <Button
                                    size="sm"
                                    variant={showAlternativesOnly ? 'secondary' : 'outline'}
                                    className="gap-1 me-2"
                                    onClick={() => {
                                        if (isServerPaginatedMaterials) {
                                            updateMaterialQuery({ page: 1, hasAlternativesOnly: showAlternativesOnly ? null : 'true' });
                                            return;
                                        }
                                        setShowAlternativesOnly((value) => !value);
                                    }}
                                    title={showAlternativesOnly ? 'عرض كل الأصناف' : 'عرض الأصناف التي لها بدائل فقط'}
                                >
                                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
                                        {showAlternativesOnly ? (t?.allItemsLabel || 'كل الأصناف') : (t?.hasAlternativesOnlyLabel || 'له بدائل فقط')}
                                    </span>
                                </Button>
                            )}
                            {itemType === 'material' && hasActiveMaterialColumnFilters && (
                                <Button
                                    size="sm"
                                    variant="outline"
                                    className="gap-1 me-2"
                                    onClick={clearMaterialColumnFilters}
                                    title={t?.clearColumnFiltersLabel || 'مسح فلاتر الأعمدة'}
                                >
                                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
                                        {t?.clearColumnFiltersLabel || 'مسح فلاتر الأعمدة'}
                                    </span>
                                </Button>
                            )}
                            {itemType === 'material' && (
                                <Button
                                    size="sm"
                                    variant={showWarehouseBalance || showAvailableOnly ? 'secondary' : 'outline'}
                                    className="gap-1 me-2"
                                    onClick={() => {
                                        const nextValue = !(showWarehouseBalance && showAvailableOnly);
                                        if (isServerPaginatedMaterials) {
                                            setShowWarehouseBalance(nextValue);
                                            setShowAvailableOnly(nextValue);
                                            updateMaterialQuery({ page: 1, availableOnly: nextValue ? 'true' : null });
                                            return;
                                        }
                                        setShowWarehouseBalance(nextValue);
                                        setShowAvailableOnly(nextValue);
                                    }}
                                    disabled={!warehousesEnabled}
                                    title={showWarehouseBalance && showAvailableOnly ? 'عرض كل الأصناف وإخفاء الرصيد' : 'إظهار الرصيد وعرض المتوفر فقط'}
                                >
                                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
                                        {showWarehouseBalance && showAvailableOnly ? 'كل الأصناف' : 'إظهار الرصيد + المتوفر فقط'}
                                    </span>
                                </Button>
                            )}
                            <Button size="sm" className="gap-1" onClick={() => {
                                if (itemType === 'material') {
                                    router.push('/admin/data/materials/new');
                                    return;
                                }
                                setInitialValues(undefined);
                                setDialogState({ isOpen: true, item: undefined });
                            }}>
                                <PlusCircle className="h-3.5 w-3.5" />
                                <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">{t.addButton}</span>
                            </Button>
                            {itemType === 'product-shape' && (
                                <Button
                                    size="sm"
                                    variant="outline"
                                    className="gap-1 ms-2"
                                    onClick={() => setIsBulkShapeDialogOpen(true)}
                                >
                                    <PlusCircle className="h-3.5 w-3.5" />
                                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">{t.bulkAddLabel || 'إضافة جماعية'}</span>
                                </Button>
                            )}
                        </div>
                    </div>
                    </div>
                </CardHeader>
                <CardContent>
                    <div className="relative w-full overflow-auto">
                    <Table>
                                                <TableHeader>
                                                        <TableRow>
                                                                {itemType === 'material' && (() => {
                                                                    const SortHead = ({ col, children, className }: { col: MaterialSortKey; children: React.ReactNode; className?: string }) => (
                                                                        <TableHead className={`cursor-pointer select-none${className ? ' ' + className : ''}`} onClick={() => toggleSort(col)}>
                                                                            <span className="inline-flex items-center gap-1">
                                                                                {children}
                                                                                {sortKey === col ? (sortDir === 'asc' ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />) : <ChevronsUpDown className="h-3 w-3 opacity-40" />}
                                                                            </span>
                                                                        </TableHead>
                                                                    );
                                                                    return (
                                                                        <>
                                                                            <SortHead col="itemNumber" className="w-[96px] min-w-[96px]">{t.itemNumberLabel || 'رقم الصنف'}</SortHead>
                                                                            <SortHead col="name" className="w-[180px] min-w-[180px]">{t.itemNameLabel}</SortHead>
                                                                            <SortHead col="itemSymbolName" className="w-[130px] min-w-[130px]">{t.itemSymbolNameLabel || 'اسم رمز الصنف'}</SortHead>
                                                                            <SortHead col="globalReferenceNumber" className="w-[130px] min-w-[130px]">{t.globalReferenceNumberLabel || 'رقم مرجع عالمي'}</SortHead>
                                                                            <SortHead col="barcode" className="w-[150px] min-w-[150px]">{t.barcodeLabel || 'الباركود'}</SortHead>
                                                                            <SortHead col="secondaryBarcode" className="w-[150px] min-w-[150px]">{t.secondaryBarcodeLabel || 'باركود الوحدة الفرعية'}</SortHead>
                                                                            <SortHead col="additionalDetails" className="w-[160px] min-w-[160px]">{t.additionalDetailsLabel || 'تفاصيل اضافيه'}</SortHead>
                                                                            <SortHead col="salePrice" className="text-right w-[105px] min-w-[105px]">{t.salePriceLabel || 'سعر البيع'}</SortHead>
                                                                            {warehousesEnabled && <TableHead className="w-[140px] min-w-[140px]">{t.itemLocationLabel || 'الموقع'}</TableHead>}
                                                                            {showWarehouseBalance && <TableHead className="w-[190px] min-w-[190px]">{t?.warehouseBalanceLabel || 'رصيد المستودعات'}</TableHead>}
                                                                            {storeModuleEnabled && <TableHead className="w-[90px] min-w-[90px] text-center">{t.storeEnabledLabel || 'المتجر'}</TableHead>}
                                                                        </>
                                                                    );
                                                                })()}
                                                                {itemType === 'customer' && (
                                                                    <>
                                                                        <TableHead>{t.customerNumberLabel || 'رقم الزبون'}</TableHead>
                                                                        <TableHead>{t.customerNameLabel || t.itemNameLabel}</TableHead>
                                                                        <TableHead>{t.customerPhoneLabel || 'رقم واتساب'}</TableHead>
                                                                        <TableHead>{t.customerCreditLimitLabel || 'الحد المسموح للدين'}</TableHead>
                                                                        <TableHead>{t.customerAddressLabel || 'العنوان'}</TableHead>
                                                                        <TableHead>{t.customerCategoryLabel || 'تصنيف الزبون'}</TableHead>
                                                                        <TableHead>{t.customerSalesRepLabel || 'مندوب المبيعات'}</TableHead>
                                                                    </>
                                                                )}
                                                                {itemType === 'supplier' && (
                                                                    <>
                                                                        <TableHead>{t.supplierNumberLabel || 'رقم المورد'}</TableHead>
                                                                        <TableHead>{t.supplierNameLabel || 'اسم المورد'}</TableHead>
                                                                        <TableHead>{t.supplierPhoneLabel || 'رقم الهاتف'}</TableHead>
                                                                        <TableHead>{t.supplierAddressLabel || 'العنوان'}</TableHead>
                                                                        <TableHead>{t.supplierPaymentTermsLabel || 'شروط الدفع (أيام)'}</TableHead>
                                                                        <TableHead>{t.supplierTaxNumberLabel || 'الرقم الضريبي'}</TableHead>
                                                                    </>
                                                                )}
                                                                {itemType === 'sales-rep' && (
                                                                    <>
                                                                        <TableHead>{t.salesRepNameLabel || 'اسم المندوب'}</TableHead>
                                                                        <TableHead>{t.salesRepPhoneLabel || 'رقم الهاتف'}</TableHead>
                                                                        <TableHead>{t.salesRepRegionLabel || 'المنطقة'}</TableHead>
                                                                        <TableHead>{t.salesRepCommissionLabel || 'نسبة العمولة'}</TableHead>
                                                                    </>
                                                                )}
                                                                {itemType === 'unit' && (
                                                                    <>
                                                                        <TableHead>{t.unitNumberLabel || 'رقم الوحدة'}</TableHead>
                                                                        <TableHead>{t.unitDescriptionLabel || 'الوصف'}</TableHead>
                                                                        <TableHead>{t.unitShortCodeLabel || 'الاختصار'}</TableHead>
                                                                        <TableHead>{t.notesLabel || 'ملاحظات'}</TableHead>
                                                                    </>
                                                                )}
                                                                {itemType === 'expense' && (
                                                                    <>
                                                                        <TableHead>{t.itemNameLabel}</TableHead>
                                                                        <TableHead>{t.realEstateProjectsTitle || 'المشروع العقاري'}</TableHead>
                                                                        <TableHead>{t.costTypeLabel || 'نوع التحميل'}</TableHead>
                                                                    </>
                                                                )}
                                                                {itemType === 'product-shape' && (
                                                                    <>
                                                                        <TableHead className="w-[130px]">{t.referenceNumberLabel || 'الرقم المرجعي'}</TableHead>
                                                                        <TableHead>{t.productShapeNameLabel || 'اسم الحجم/الشكل'}</TableHead>
                                                                    </>
                                                                )}
                                                                <TableHead className="text-right w-[120px] min-w-[120px]">{tGlobal.actions}</TableHead>
                                                        </TableRow>
                                                        {itemType === 'material' && !dualRowView && (
                                                            <TableRow className="sticky top-12 z-10 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 shadow-sm">
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('itemNumber')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('name')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('itemSymbolName')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('globalReferenceNumber')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('barcode')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('secondaryBarcode')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('additionalDetails')}</TableHead>
                                                                <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('salePrice', { align: 'right' })}</TableHead>
                                                                {warehousesEnabled && (
                                                                    <TableHead className="bg-background/95">{renderMaterialColumnFilterInput('location')}</TableHead>
                                                                )}
                                                                {showWarehouseBalance && <TableHead className="bg-background/95" />}
                                                                <TableHead className="bg-background/95" />
                                                            </TableRow>
                                                        )}
                                                </TableHeader>
                        <TableBody>
                            {totalItemsCount === 0 ? (
                                                                <TableRow><TableCell colSpan={itemType === 'material' ? ((warehousesEnabled ? 10 : 9) + (showWarehouseBalance ? 1 : 0)) : itemType === 'customer' ? 8 : itemType === 'supplier' ? 7 : itemType === 'sales-rep' ? 5 : itemType === 'unit' ? 5 : itemType === 'expense' ? 4 : itemType === 'product-shape' ? 3 : 2} className="h-24 text-center text-muted-foreground">{t.noItemsFound}</TableCell></TableRow>
                            ) : (
                                paginatedItems.map(item => {
                                    const materialItem = item as ProductionItem;
                                    const customerItem = item as Customer;
                                    const supplierItem = item as Supplier;
                                    const salesRepItem = item as SalesRep;
                                    const unitItem = item as ListManagedUnit;
                                    const primaryBarcodes = [materialItem.barcode, ...(materialItem.additionalBarcodes || [])].filter(Boolean).join('، ');
                                    const secondaryBarcodes = Array.isArray((materialItem as any).secondaryUnits)
                                        ? (materialItem as any).secondaryUnits.map((entry: any) => entry?.barcode).filter(Boolean)
                                        : [];
                                    const secondaryBarcodeText = [materialItem.secondaryBarcode, ...secondaryBarcodes]
                                        .filter((code, index, source) => !!code && source.indexOf(code) === index)
                                        .join('، ');
                                    const hasAlternatives = itemType === 'material'
                                        && Array.isArray((materialItem as any).alternativeItemIds)
                                        && ((materialItem as any).alternativeItemIds as string[]).some((entry) => String(entry || '').trim() !== '');
                                    const warehouseTotals = itemType === 'material'
                                        ? getMaterialWarehouseTotals(materialItem)
                                        : [];
                                    const warehouseBalanceSummary = warehouseTotals.length > 0
                                        ? warehouseTotals.map(([name, qty]) => `${name}: ${qty}`).join('، ')
                                        : '-';
                                    const salesRepName = customerItem.salesRepId ? salesRepById.get(customerItem.salesRepId)?.name : undefined;
                                    return (
                                        <TableRow
                                            key={item.id}
                                            className={itemType === 'material' ? 'cursor-context-menu' : undefined}
                                            onContextMenu={itemType === 'material'
                                                ? (event) => handleMaterialRowContextMenu(event, materialItem)
                                                : undefined}
                                        >
                                                                                        {itemType === 'material' && dualRowView ? (
                                                                                            <TableCell colSpan={(warehousesEnabled ? 9 : 8) + (showWarehouseBalance ? 1 : 0)} className="p-0">
                                                                                                <div className="flex flex-col">
                                                                                                    {/* السطر الأول: رقم الصنف + الاسم + السعر */}
                                                                                                    <div className="flex items-center gap-3 px-4 pt-2.5 pb-1">
                                                                                                        <Link
                                                                                                            href={`/admin/data/materials/${encodeURIComponent(String(materialItem.id || ''))}/edit`}
                                                                                                            className="font-mono text-xs shrink-0 text-muted-foreground hover:text-foreground underline-offset-2 hover:underline"
                                                                                                        >
                                                                                                            {materialItem.itemNumber}
                                                                                                        </Link>
                                                                                                        <Link
                                                                                                            href={`/admin/data/materials/${encodeURIComponent(String(materialItem.id || ''))}/edit`}
                                                                                                            className="font-semibold text-sm hover:text-primary underline-offset-2 hover:underline"
                                                                                                        >
                                                                                                            {materialItem.name || '-'}
                                                                                                        </Link>
                                                                                                        {hasAlternatives ? (
                                                                                                            <span className="inline-flex items-center rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold text-emerald-700">
                                                                                                                {t?.hasAlternativesBadge || 'له بدائل'}
                                                                                                            </span>
                                                                                                        ) : null}
                                                                                                        <span className="ms-auto text-sm font-medium">
                                                                                                            {formatCurrency(materialItem.salePrice || 0, currencySymbol)}
                                                                                                        </span>
                                                                                                    </div>
                                                                                                    {/* السطر الثاني: بقية الحقول */}
                                                                                                    <div className="flex flex-wrap items-center gap-x-4 gap-y-0.5 px-4 pb-2 text-xs text-muted-foreground">
                                                                                                        {materialItem.itemSymbolName ? <span>{materialItem.itemSymbolName}</span> : null}
                                                                                                        {primaryBarcodes ? <span>باركود: {primaryBarcodes}</span> : null}
                                                                                                        {secondaryBarcodeText ? <span>باركود ف: {secondaryBarcodeText}</span> : null}
                                                                                                        {((materialItem as any).globalReferenceNumber || '').trim() ? <span>مرجع: {(materialItem as any).globalReferenceNumber}</span> : null}
                                                                                                        {(materialItem.additionalDetails || '').trim() ? <span className="max-w-[300px] truncate">{materialItem.additionalDetails}</span> : null}
                                                                                                        {warehousesEnabled && (
                                                                                                            <span className="flex items-center gap-0.5 ms-1">
                                                                                                                <Button type="button" variant="ghost" size="icon" className="h-6 w-6" onClick={() => setLocationMaterialId(materialItem.id)}><MapPin className="h-3 w-3" /></Button>
                                                                                                                <Button type="button" variant="ghost" size="icon" className="h-6 w-6" onClick={() => openTransferDialog(materialItem)} disabled={isLockPending}><ArrowLeftRight className="h-3 w-3" /></Button>
                                                                                                            </span>
                                                                                                        )}
                                                                                                    </div>
                                                                                                </div>
                                                                                            </TableCell>
                                                                                        ) : null}
                                                                                        {itemType === 'material' && !dualRowView && (
                                                                                            <>
                                                                                                <TableCell className="font-medium whitespace-nowrap">
                                                                                                    <Link
                                                                                                        href={`/admin/data/materials/${encodeURIComponent(String(materialItem.id || ''))}/edit`}
                                                                                                        className="hover:text-primary underline-offset-2 hover:underline"
                                                                                                    >
                                                                                                        {materialItem.itemNumber}
                                                                                                    </Link>
                                                                                                </TableCell>
                                                                                                <TableCell>
                                                                                                    <div className="flex items-center gap-2">
                                                                                                        <Link
                                                                                                            href={`/admin/data/materials/${encodeURIComponent(String(materialItem.id || ''))}/edit`}
                                                                                                            className="text-start hover:text-primary underline-offset-2 hover:underline"
                                                                                                        >
                                                                                                            <OverflowTooltipText value={materialItem.name || '-'} className="block max-w-[180px] truncate" />
                                                                                                        </Link>
                                                                                                        {hasAlternatives ? (
                                                                                                            <span className="inline-flex items-center rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold text-emerald-700">
                                                                                                                {t?.hasAlternativesBadge || 'له بدائل'}
                                                                                                            </span>
                                                                                                        ) : null}
                                                                                                    </div>
                                                                                                </TableCell>
                                                                                                <TableCell>
                                                                                                    <OverflowTooltipText value={materialItem.itemSymbolName || '-'} className="block max-w-[130px] truncate" />
                                                                                                </TableCell>
                                                                                                <TableCell>
                                                                                                    <OverflowTooltipText value={((materialItem as any).globalReferenceNumber || '').trim() || '-'} className="block max-w-[130px] truncate" />
                                                                                                </TableCell>
                                                                                                <TableCell>
                                                                                                    <OverflowTooltipText value={primaryBarcodes || '-'} className="block max-w-[150px] truncate" />
                                                                                                </TableCell>
                                                                                                <TableCell>
                                                                                                    <OverflowTooltipText value={secondaryBarcodeText || '-'} className="block max-w-[150px] truncate" />
                                                                                                </TableCell>
                                                                                                <TableCell>
                                                                                                    <OverflowTooltipText value={(materialItem.additionalDetails || '').trim() || '-'} className="block max-w-[160px] truncate" />
                                                                                                </TableCell>
                                                                                                <TableCell className="text-right whitespace-nowrap">{formatCurrency(materialItem.salePrice || 0, currencySymbol)}</TableCell>
                                                                                                {warehousesEnabled && (
                                                                                                    <TableCell>
                                                                                                        <div className="flex items-center gap-2">
                                                                                                            <Button
                                                                                                                type="button"
                                                                                                                variant="ghost"
                                                                                                                size="icon"
                                                                                                                onClick={() => setLocationMaterialId(materialItem.id)}
                                                                                                                disabled={!warehousesEnabled}
                                                                                                            >
                                                                                                                <MapPin className="h-4 w-4" />
                                                                                                            </Button>
                                                                                                            <Button
                                                                                                                type="button"
                                                                                                                variant="ghost"
                                                                                                                size="icon"
                                                                                                                onClick={() => openTransferDialog(materialItem)}
                                                                                                                disabled={!warehousesEnabled || isLockPending}
                                                                                                            >
                                                                                                                <ArrowLeftRight className="h-4 w-4" />
                                                                                                            </Button>
                                                                                                        </div>
                                                                                                    </TableCell>
                                                                                                )}
                                                                                                {showWarehouseBalance && (
                                                                                                    <TableCell>
                                                                                                        <OverflowTooltipText value={warehouseBalanceSummary} className="block max-w-[190px] truncate" />
                                                                                                    </TableCell>
                                                                                                )}
                                                                                                {storeModuleEnabled && (
                                                                                                    <TableCell className="text-center">
                                                                                                        <Switch
                                                                                                            checked={!!(materialItem as any).storeEnabled}
                                                                                                            onCheckedChange={async (checked) => {
                                                                                                                setCurrentItems((prev) => prev.map((m) => m.id === materialItem.id ? { ...m, storeEnabled: checked } as any : m));
                                                                                                                const result = await handleToggleMaterialStoreEnabled(materialItem.id, checked);
                                                                                                                if ('error' in result && result.error) {
                                                                                                                    setCurrentItems((prev) => prev.map((m) => m.id === materialItem.id ? { ...m, storeEnabled: !checked } as any : m));
                                                                                                                    toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
                                                                                                                }
                                                                                                            }}
                                                                                                        />
                                                                                                    </TableCell>
                                                                                                )}
                                                                                            </>
                                                                                        )}
                                                                                        {itemType === 'customer' && (
                                                                                            <>
                                                                                                <TableCell className="font-medium">{customerItem.customerNumber}</TableCell>
                                                                                                <TableCell className="font-medium">{customerItem.name}</TableCell>
                                                                                                <TableCell>{customerItem.phone || '-'}</TableCell>
                                                                                                <TableCell>{formatCurrency(typeof customerItem.creditLimit === 'number' ? customerItem.creditLimit : 0, currencySymbol)}</TableCell>
                                                                                                <TableCell>{customerItem.address || '-'}</TableCell>
                                                                                                <TableCell>{customerItem.category || '-'}</TableCell>
                                                                                                <TableCell>{salesRepName || '-'}</TableCell>
                                                                                            </>
                                                                                        )}
                                                                                        {itemType === 'supplier' && (
                                                                                            <>
                                                                                                <TableCell className="font-medium">{supplierItem.supplierNumber || '-'}</TableCell>
                                                                                                <TableCell className="font-medium">{supplierItem.name || '-'}</TableCell>
                                                                                                <TableCell>{supplierItem.phone || '-'}</TableCell>
                                                                                                <TableCell>{supplierItem.address || '-'}</TableCell>
                                                                                                <TableCell>{typeof supplierItem.paymentTerms === 'number' ? supplierItem.paymentTerms : '-'}</TableCell>
                                                                                                <TableCell>{supplierItem.taxNumber || '-'}</TableCell>
                                                                                            </>
                                                                                        )}
                                                                                        {itemType === 'sales-rep' && (
                                                                                            <>
                                                                                                <TableCell className="font-medium">{salesRepItem.name}</TableCell>
                                                                                                <TableCell>{salesRepItem.phone || '-'}</TableCell>
                                                                                                <TableCell>{salesRepItem.region || '-'}</TableCell>
                                                                                                <TableCell>{typeof salesRepItem.commissionRate === 'number' ? `${salesRepItem.commissionRate}%` : '-'}</TableCell>
                                                                                            </>
                                                                                        )}
                                                                                        {itemType === 'unit' && (
                                                                                            <>
                                                                                                <TableCell className="font-medium">{unitItem.unitNumber || '-'}</TableCell>
                                                                                                <TableCell>{unitItem.description || '-'}</TableCell>
                                                                                                <TableCell>{String(unitItem.shortCode || '').trim() || '-'}</TableCell>
                                                                                                <TableCell><OverflowTooltipText value={String(unitItem.notes || '').trim() || '-'} className="block max-w-[240px] truncate" /></TableCell>
                                                                                            </>
                                                                                        )}
                                                                                        {itemType === 'expense' && (() => {
                                                                                            const expenseItem = item as ProductionItem;
                                                                                            const linkedProject = realEstateProjectById.get(String(expenseItem.realEstateProjectId || ''));
                                                                                            return (
                                                                                                <>
                                                                                                    <TableCell className="font-medium">{item.name}</TableCell>
                                                                                                    <TableCell>{linkedProject?.name || '-'}</TableCell>
                                                                                                    <TableCell>{getRealEstateCostTypeLabel(String(expenseItem.realEstateCostType || 'general'))}</TableCell>
                                                                                                </>
                                                                                            );
                                                                                        })()}
                                                                                        {itemType === 'product-shape' && (
                                                                                            <>
                                                                                                <TableCell className="font-mono text-sm text-muted-foreground">{(item as ProductionItem).itemNumber || '-'}</TableCell>
                                                                                                <TableCell className="font-medium">{item.name}</TableCell>
                                                                                            </>
                                                                                        )}
                                                                                        <TableCell className="text-right min-w-[120px]">
                                                                                            <div className="flex items-center justify-end gap-1">
                                                                                                <Button
                                                                                                    type="button"
                                                                                                    size="icon"
                                                                                                    variant="ghost"
                                                                                                    onClick={() => setPreviewItem(item)}
                                                                                                    title={t?.previewLabel || 'معاينة'}
                                                                                                >
                                                                                                    <Eye className="h-4 w-4" />
                                                                                                </Button>
                                                                                                {isClientMounted ? (
                                                                                                    <AlertDialog>
                                                                                                        <DropdownMenu>
                                                                                                            <DropdownMenuTrigger asChild>
                                                                                                                <Button aria-haspopup="true" size="icon" variant="ghost" disabled={isDeletePending}><MoreHorizontal className="h-4 w-4" /></Button>
                                                                                                            </DropdownMenuTrigger>
                                                                                                            <DropdownMenuContent align="end">
                                                                                                                {itemType === 'material' && (
                                                                                                                    <DropdownMenuItem onSelect={() => setPreviewItem(item)}>
                                                                                                                        {t?.previewLabel || 'معاينة'}
                                                                                                                    </DropdownMenuItem>
                                                                                                                )}
                                                                                                                <DropdownMenuItem onSelect={() => {
                                                                                                                    if (itemType === 'material') {
                                                                                                                        router.push(`/admin/data/materials/${encodeURIComponent(String(item.id || ''))}/edit`);
                                                                                                                        return;
                                                                                                                    }
                                                                                                                    setDialogState({ isOpen: true, item: item });
                                                                                                                }}>{tGlobal.edit}</DropdownMenuItem>
                                                                                                                {itemType === 'material' && (
                                                                                                                    <DropdownMenuItem onSelect={() => handleDuplicateMaterial(item as ProductionItem)}>
                                                                                                                        {t?.duplicateItemLabel || 'نسخ الصنف'}
                                                                                                                    </DropdownMenuItem>
                                                                                                                )}
                                                                                                                <AlertDialogTrigger asChild>
                                                                                                                    <DropdownMenuItem className="text-red-600">{tGlobal.delete}</DropdownMenuItem>
                                                                                                                </AlertDialogTrigger>
                                                                                                            </DropdownMenuContent>
                                                                                                        </DropdownMenu>
                                                                                                        <AlertDialogContent>
                                                                                                            <AlertDialogHeader>
                                                                                                                <AlertDialogTitle>{t.deleteDialogTitle}</AlertDialogTitle>
                                                                                                                <AlertDialogDescription>{(t.deleteDialogDescription || '').replace('{name}', item.name)}</AlertDialogDescription>
                                                                                                            </AlertDialogHeader>
                                                                                                            <AlertDialogFooter>
                                                                                                                <AlertDialogCancel>{tGlobal.cancel}</AlertDialogCancel>
                                                                                                                <AlertDialogAction onClick={() => onDelete(item.id)} className="bg-destructive hover:bg-destructive/90">{isDeletePending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : tGlobal.delete}</AlertDialogAction>
                                                                                                            </AlertDialogFooter>
                                                                                                        </AlertDialogContent>
                                                                                                    </AlertDialog>
                                                                                                ) : (
                                                                                                    <Button aria-hidden="true" size="icon" variant="ghost" disabled><MoreHorizontal className="h-4 w-4" /></Button>
                                                                                                )}
                                                                                            </div>
                                                                                        </TableCell>
                                            </TableRow>
                                    );
                                })
                            )}
                        </TableBody>
                    </Table>
                    {itemType === 'material' && isClientMounted && (
                        <DropdownMenu
                            open={materialRowContextMenu.open}
                            onOpenChange={(open) => {
                                setMaterialRowContextMenu((prev) => ({ ...prev, open }));
                            }}
                        >
                            <DropdownMenuTrigger asChild>
                                <button
                                    type="button"
                                    aria-hidden="true"
                                    className="fixed h-0 w-0 opacity-0 pointer-events-none"
                                    style={{ left: materialRowContextMenu.x, top: materialRowContextMenu.y }}
                                />
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="start" sideOffset={6}>
                                <DropdownMenuItem
                                    onSelect={() => {
                                        const target = materialRowContextMenu.item;
                                        if (target) {
                                            handleDuplicateMaterial(target);
                                        }
                                        setMaterialRowContextMenu((prev) => ({ ...prev, open: false }));
                                    }}
                                >
                                    {t?.duplicateItemCardLabel || t?.duplicateItemLabel || 'نسخ بطاقة الصنف'}
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    )}
                    </div>
                    <div className="mt-4 flex flex-col gap-3 rounded-xl border bg-muted/20 p-3">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                            <div className="text-sm text-muted-foreground">
                                {(t?.paginationSummary || 'عرض {from}-{to} من أصل {total}')
                                    .replace('{from}', totalItemsCount === 0 ? '0' : String((effectiveCurrentPage - 1) * pageSize + 1))
                                    .replace('{to}', totalItemsCount === 0 ? '0' : String(Math.min(((effectiveCurrentPage - 1) * pageSize) + paginatedItems.length, totalItemsCount)))
                                    .replace('{total}', String(totalItemsCount))}
                            </div>
                            <div className="flex items-center gap-2">
                                <Button type="button" size="sm" variant="outline" onClick={() => {
                                    navigateToPage(effectiveCurrentPage - 1);
                                }} disabled={effectiveCurrentPage <= 1}>
                                    {t?.previousPageLabel || 'السابق'}
                                </Button>
                                <span className="text-sm font-medium">{effectiveCurrentPage} / {totalPages}</span>
                                <div className="flex items-center gap-1">
                                    <Input
                                        type="number"
                                        min={1}
                                        max={totalPages}
                                        value={pageJumpInput}
                                        onChange={(event) => setPageJumpInput(event.target.value)}
                                        onKeyDown={(event) => {
                                            if (event.key !== 'Enter') return;
                                            event.preventDefault();
                                            navigateToPage(Number(pageJumpInput));
                                        }}
                                        className="h-9 w-24"
                                        placeholder={String(effectiveCurrentPage)}
                                        aria-label={t?.goToPageLabel || 'الانتقال إلى صفحة'}
                                    />
                                    <Button
                                        type="button"
                                        size="sm"
                                        variant="outline"
                                        onClick={() => navigateToPage(Number(pageJumpInput))}
                                    >
                                        {t?.goLabel || 'انتقال'}
                                    </Button>
                                </div>
                                <Button type="button" size="sm" variant="outline" onClick={() => {
                                    navigateToPage(effectiveCurrentPage + 1);
                                }} disabled={effectiveCurrentPage >= totalPages}>
                                    {t?.nextPageLabel || 'التالي'}
                                </Button>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-2 text-sm md:grid-cols-4">
                            <div className="rounded-lg border bg-background p-2">
                                <div className="text-xs text-muted-foreground">{t?.statsTotalRows || 'إجمالي النتائج'}</div>
                                <div className="font-semibold">{totalItemsCount}</div>
                            </div>
                            <div className="rounded-lg border bg-background p-2">
                                <div className="text-xs text-muted-foreground">{t?.statsCurrentPageRows || 'عدد صفوف الصفحة الحالية'}</div>
                                <div className="font-semibold">{paginatedItems.length}</div>
                            </div>
                            <div className="rounded-lg border bg-background p-2">
                                <div className="text-xs text-muted-foreground">{itemType === 'material' ? (t?.statsWithBarcode || 'أصناف بباركود') : (t?.statsPagesCount || 'عدد الصفحات')}</div>
                                <div className="font-semibold">{itemType === 'material' ? (materialsStats?.withBarcodeCount || 0) : totalPages}</div>
                            </div>
                            <div className="rounded-lg border bg-background p-2">
                                <div className="text-xs text-muted-foreground">{itemType === 'material' ? (t?.statsTotalSaleValue || 'مجموع أسعار البيع') : (t?.statsFiltersApplied || 'نتائج بعد الفلترة')}</div>
                                <div className="font-semibold">{itemType === 'material' ? formatCurrency(materialsStats?.totalSaleValue || 0, currencySymbol) : totalItemsCount}</div>
                            </div>
                        </div>
                    </div>
                </CardContent>
            </Card>
            </div>

            {itemType === 'material' && (
                <MaterialImportDialog
                    open={isMaterialImportOpen}
                    onOpenChange={setIsMaterialImportOpen}
                    itemGroups={itemGroups || []}
                    currentItems={currentItems as ProductionItem[]}
                    onImported={() => {
                        router.refresh();
                    }}
                />
            )}

                        <Dialog
                            open={dialogState.isOpen}
                            onOpenChange={(open) => {
                                if (!open) {
                                    if (typeof document !== 'undefined') {
                                        (document.activeElement as HTMLElement | null)?.blur();
                                    }
                                    closeDialog();
                                }
                            }}
                        >
                                {dialogState.isOpen && <ItemDialog item={dialogState.item} itemType={itemType} t={t} tGlobal={tGlobal} items={currentItems} categories={categories} itemGroups={itemGroups} salesReps={salesReps} unitDefinitions={unitDefinitions} warehouses={warehouses} productShapeDefinitions={productShapeDefinitions} realEstateProjects={realEstateProjects} chartOfAccounts={chartOfAccounts} initialValues={initialValues} onFinished={closeDialog} onCreated={handleItemCreated} currencySymbol={currencySymbol} />}
            </Dialog>
            <Dialog
                open={!!locationMaterialId}
                onOpenChange={(open) => {
                    if (!open) {
                        setLocationMaterialId(null);
                    }
                }}
            >
                <DialogContent className="max-w-xl">
                    <DialogHeader>
                        <DialogTitle>{t?.locationDialogTitle ?? 'مواقع الصنف على الأرفف'}</DialogTitle>
                        <DialogDescription>
                            {(t?.locationDialogDescription || 'توزيع الرصيد حسب المستودع والرف للصنف: {name}.')
                                .replace('{name}', locationMaterial?.name || '')}
                        </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-3">
                        {locationEntries.length === 0 ? (
                            <p className="text-sm text-muted-foreground">
                                {t?.noStockLocations ?? 'لا توجد مواقع متاحة لهذا الصنف.'}
                            </p>
                        ) : (
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>{t?.warehouseLabel ?? 'المستودع'}</TableHead>
                                        <TableHead>{t?.shelfLabel ?? 'الرف'}</TableHead>
                                        <TableHead className="text-right">{t?.quantityLabel ?? 'الكمية'}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {locationEntries.map((entry) => (
                                        <TableRow key={`${entry.warehouseId}-${entry.shelfId}`}>
                                            <TableCell>{entry.warehouseName}</TableCell>
                                            <TableCell>{entry.shelfName}</TableCell>
                                            <TableCell className="text-right font-mono">{entry.quantity}</TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        )}
                    </div>
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={() => setLocationMaterialId(null)}>
                            {tGlobal?.cancel ?? 'إغلاق'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
            <Dialog
                open={!!previewItem}
                onOpenChange={(open) => {
                    if (!open) {
                        setPreviewItem(null);
                    }
                }}
            >
                <DialogContent className="max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>{t?.previewLabel || 'معاينة'}</DialogTitle>
                        <DialogDescription>{t?.previewDescription || 'عرض سريع لبيانات السجل.'}</DialogDescription>
                    </DialogHeader>
                    {previewItem && itemType === 'material' && (
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                            <div><span className="font-medium">{t.itemNumberLabel || 'رقم الصنف'}:</span> {(previewItem as ProductionItem).itemNumber || '-'}</div>
                            <div><span className="font-medium">{t.itemNameLabel || 'الاسم'}:</span> {(previewItem as ProductionItem).name || '-'}</div>
                            <div><span className="font-medium">{t.itemSymbolNameLabel || 'اسم رمز الصنف'}:</span> {(previewItem as ProductionItem).itemSymbolName || '-'}</div>
                            <div><span className="font-medium">{t.globalReferenceNumberLabel || 'رقم مرجع عالمي'}:</span> {((previewItem as any).globalReferenceNumber || '').trim() || '-'}</div>
                            <div><span className="font-medium">{t.salePriceLabel || 'سعر البيع'}:</span> {formatCurrency((previewItem as ProductionItem).salePrice || 0, currencySymbol)}</div>
                            <div className="md:col-span-2"><span className="font-medium">{t.barcodeLabel || 'الباركود'}:</span> {[((previewItem as ProductionItem).barcode || ''), ...((previewItem as ProductionItem).additionalBarcodes || [])].filter(Boolean).join('، ') || '-'}</div>
                            <div className="md:col-span-2"><span className="font-medium">{t.secondaryBarcodeLabel || 'باركود الوحدة الفرعية'}:</span> {((previewItem as ProductionItem).secondaryBarcode || '') || '-'}</div>
                            <div className="md:col-span-2"><span className="font-medium">{t.additionalDetailsLabel || 'تفاصيل اضافيه'}:</span> {((previewItem as ProductionItem).additionalDetails || '').trim() || '-'}</div>
                        </div>
                    )}
                    {previewItem && itemType === 'expense' && (() => {
                        const expenseItem = previewItem as ProductionItem;
                        const linkedProject = realEstateProjectById.get(String(expenseItem.realEstateProjectId || ''));
                        const linkedUnit = (linkedProject?.units || []).find((unit) => String(unit.id || '') === String(expenseItem.realEstateUnitId || ''));
                        return (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                                <div><span className="font-medium">{t.itemNameLabel || 'الاسم'}:</span> {expenseItem.name || '-'}</div>
                                <div><span className="font-medium">{t.realEstateProjectsTitle || 'المشروع العقاري'}:</span> {linkedProject?.name || '-'}</div>
                                <div><span className="font-medium">{t.costTypeLabel || 'نوع التحميل'}:</span> {getRealEstateCostTypeLabel(String(expenseItem.realEstateCostType || 'general'))}</div>
                                <div><span className="font-medium">{t.unitNameLabel || 'الوحدة'}:</span> {linkedUnit?.name || linkedUnit?.unitCode || '-'}</div>
                            </div>
                        );
                    })()}
                    {previewItem && itemType !== 'material' && itemType !== 'expense' && (
                        <div className="text-sm">
                            <p><span className="font-medium">{t.itemNameLabel || 'الاسم'}:</span> {previewItem.name || '-'}</p>
                        </div>
                    )}
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={() => setPreviewItem(null)}>
                            {tGlobal?.cancel ?? 'إغلاق'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
            <Dialog
                open={transferDialogOpen}
                onOpenChange={(open) => {
                    if (!open) {
                        closeTransferDialog();
                    }
                }}
            >
                <DialogContent className="max-w-xl">
                    <DialogHeader>
                        <DialogTitle>{t?.transferDialogTitle ?? 'ارسالية داخلية'}</DialogTitle>
                        <DialogDescription>
                            {(t?.transferDialogDescription || 'نقل الصنف بين الأرفف: {name}.')
                                .replace('{name}', transferMaterial?.name || '')}
                        </DialogDescription>
                    </DialogHeader>
                    {!warehousesEnabled ? (
                        <p className="text-sm text-muted-foreground">
                            {t?.warehouseDisabled ?? 'المخازن غير مفعلة في الإعدادات.'}
                        </p>
                    ) : transferLocations.length === 0 ? (
                        <p className="text-sm text-muted-foreground">
                            {t?.noStockLocations ?? 'لا يوجد رصيد مسجل لهذا الصنف على الأرفف.'}
                        </p>
                    ) : (
                        <div className="grid grid-cols-1 gap-4">
                            <div className="space-y-2">
                                <label className="text-sm font-medium">
                                    {t?.fromLocationLabel ?? 'اختر موقع الصنف المراد النقل منه'}
                                </label>
                                <div className="rounded-md border">
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead>{t?.warehouseLabel ?? 'المستودع'}</TableHead>
                                                <TableHead>{t?.shelfLabel ?? 'الرف'}</TableHead>
                                                <TableHead className="text-right">{t?.quantityLabel ?? 'الكمية'}</TableHead>
                                                <TableHead className="w-[70px]"></TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {transferLocations.map((entry) => (
                                                <TableRow key={`${entry.warehouseId}-${entry.shelfId}`}>
                                                    <TableCell>{entry.warehouseName}</TableCell>
                                                    <TableCell>{entry.shelfName}</TableCell>
                                                    <TableCell className="text-right font-mono">{entry.quantity}</TableCell>
                                                    <TableCell className="text-right">
                                                        <Button
                                                            type="button"
                                                            size="sm"
                                                            variant={
                                                                transferState.fromWarehouseId === entry.warehouseId && transferState.fromShelfId === entry.shelfId
                                                                    ? 'default'
                                                                    : 'outline'
                                                            }
                                                            disabled={entry.quantity <= 0}
                                                            onClick={() => {
                                                                setTransferState((prev) => {
                                                                    const shouldClamp = prev.quantity && Number(prev.quantity) > entry.quantity;
                                                                    return {
                                                                        ...prev,
                                                                        fromWarehouseId: entry.warehouseId,
                                                                        fromShelfId: entry.shelfId,
                                                                        quantity: shouldClamp ? String(entry.quantity) : prev.quantity,
                                                                    };
                                                                });
                                                            }}
                                                        >
                                                            {transferState.fromWarehouseId === entry.warehouseId && transferState.fromShelfId === entry.shelfId
                                                                ? (t?.selectedLabel ?? 'تم الاختيار')
                                                                : (t?.selectLabel ?? 'اختيار')}
                                                        </Button>
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                        </TableBody>
                                    </Table>
                                </div>
                            </div>
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                <div className="space-y-2">
                                    <label className="text-sm font-medium">
                                        {t?.toWarehouseLabel ?? 'إلى المستودع'}
                                    </label>
                                    <Select
                                        value={transferState.toWarehouseId}
                                        onValueChange={(value) => setTransferState((prev) => ({ ...prev, toWarehouseId: value, toShelfId: '' }))}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder={t?.selectWarehouse ?? 'اختر المستودع'} />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {warehouses.map((wh) => (
                                                <SelectItem key={wh.id} value={wh.id}>{wh.name}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="space-y-2">
                                    <label className="text-sm font-medium">
                                        {t?.toShelfLabel ?? 'إلى الرف'}
                                    </label>
                                    <Select
                                        value={transferState.toShelfId}
                                        onValueChange={(value) => setTransferState((prev) => ({ ...prev, toShelfId: value }))}
                                        disabled={!transferState.toWarehouseId || toShelves.length === 0}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder={t?.selectShelf ?? 'اختر الرف'} />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {toShelves.map((shelf) => (
                                                <SelectItem key={shelf.id} value={shelf.id}>{shelf.name}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                <div className="space-y-2">
                                    <label className="text-sm font-medium">
                                        {t?.quantityLabel ?? 'الكمية'}
                                    </label>
                                    <Input
                                        type="number"
                                        min="0"
                                        step="0.01"
                                        max={selectedAvailableQty || undefined}
                                        value={transferState.quantity}
                                        onChange={(event) => {
                                            const raw = event.target.value;
                                            const numeric = Number(raw);
                                            if (!Number.isFinite(numeric)) {
                                                setTransferState((prev) => ({ ...prev, quantity: raw }));
                                                return;
                                            }
                                            const clamped = selectedAvailableQty > 0 ? Math.min(numeric, selectedAvailableQty) : numeric;
                                            setTransferState((prev) => ({ ...prev, quantity: raw === '' ? '' : String(clamped) }));
                                        }}
                                        disabled={!selectedTransferLocation}
                                    />
                                    {selectedTransferLocation && (
                                        <p className="text-xs text-muted-foreground">
                                            {(t?.availableQuantity ?? 'المتاح في الموقع المحدد: {qty}').replace('{qty}', String(selectedAvailableQty))}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <label className="text-sm font-medium">
                                        {t?.dateLabel ?? 'التاريخ'}
                                    </label>
                                    <Input
                                        type="date"
                                        value={transferState.date}
                                        onChange={(event) => setTransferState((prev) => ({ ...prev, date: event.target.value }))}
                                    />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="text-sm font-medium">
                                    {t?.noteLabel ?? 'ملاحظة'}
                                </label>
                                <Input
                                    value={transferState.note}
                                    onChange={(event) => setTransferState((prev) => ({ ...prev, note: event.target.value }))}
                                />
                            </div>
                        </div>
                    )}
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={closeTransferDialog}>
                            {tGlobal?.cancel ?? 'إلغاء'}
                        </Button>
                        <Button type="button" onClick={onSubmitTransfer} disabled={isTransferPending || !warehousesEnabled}>
                            {isTransferPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            {t?.transferSubmitLabel ?? 'تنفيذ النقل'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

                {/* ─── Bulk add product shapes dialog (ListManager) ─────────── */}
                <Dialog open={isBulkShapeDialogOpen} onOpenChange={(open) => { if (!open) { setIsBulkShapeDialogOpen(false); setBulkShapeText(''); } }}>
                    <DialogContent className="max-w-lg">
                        <DialogHeader>
                            <DialogTitle>{t.bulkAddShapesTitle || 'إضافة أشكال جماعية'}</DialogTitle>
                            <DialogDescription>{t.bulkAddShapesHint || 'أدخل اسم كل شكل في سطر منفصل. سيتم تجاوز الأسماء المكررة تلقائياً.'}</DialogDescription>
                        </DialogHeader>
                        <div className="space-y-2">
                            <Label>{t.bulkAddShapesLabel || 'الأسماء (سطر لكل اسم)'}</Label>
                            <textarea
                                className="min-h-[160px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-y"
                                value={bulkShapeText}
                                onChange={(e) => setBulkShapeText(e.target.value)}
                                placeholder={'كبير\nصغير\nمتوسط\nخاص...'}
                                disabled={isBulkShapeSaving}
                                dir="rtl"
                            />
                        </div>
                        <DialogFooter>
                            <Button type="button" variant="outline" disabled={isBulkShapeSaving} onClick={() => { setIsBulkShapeDialogOpen(false); setBulkShapeText(''); }}>
                                {tGlobal.cancel || 'إلغاء'}
                            </Button>
                            <Button type="button" disabled={isBulkShapeSaving || !bulkShapeText.trim()} onClick={() => { void handleBulkShapeAdd(); }}>
                                {isBulkShapeSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                {t.bulkAddConfirm || 'إضافة الجميع'}
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
        </>
    );
}
