'use client';

import { useEffect, useMemo, useState, useTransition } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import * as z from 'zod';
import { Building2, Calculator, CalendarIcon, Loader2, PencilLine, PlusCircle, Trash2 } from 'lucide-react';

import AddCustomerDialog from '@/components/admin/add-customer-dialog';
import { PartySelector } from '@/components/invoice-shared';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Form } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { handleDeleteRealEstateProject, handlePostRealEstateCostEntry, handleSaveRealEstateProject } from '@/lib/actions';
import { formatCurrency } from '@/lib/currency-formatter';
import { formatDateDDMMYYYY } from '@/lib/utils';
import { useToast } from '@/hooks/use-toast';
import type { Customer, JournalEntry, ProductionItem, PurchaseOrder, RealEstateAccountingSetup, RealEstateProject } from '@/lib/types';

const projectFormSchema = z.object({
  id: z.string().optional().default(''),
  name: z.string().min(1, 'اسم المشروع مطلوب.'),
  code: z.string().optional().default(''),
  location: z.string().optional().default(''),
  startDate: z.string().optional().default(''),
  targetCompletionDate: z.string().optional().default(''),
  floorCount: z.coerce.number().min(0).default(0),
  designSummary: z.string().optional().default(''),
  floorDetails: z.array(z.object({
    id: z.string().optional().default(''),
    floorLabel: z.string().optional().default(''),
    usageType: z.string().optional().default(''),
    description: z.string().optional().default(''),
    unitCount: z.coerce.number().min(0).default(0),
    unitArea: z.coerce.number().min(0).default(0),
    estimatedUnitSaleValue: z.coerce.number().min(0).default(0),
    unitDetails: z.array(z.object({
      id: z.string().optional().default(''),
      unitLabel: z.string().optional().default(''),
      area: z.coerce.number().min(0).default(0),
      estimatedSaleValue: z.coerce.number().min(0).default(0),
      notes: z.string().optional().default(''),
    })).default([]),
    notes: z.string().optional().default(''),
  })).default([]),
  status: z.enum(['draft', 'active', 'completed']).optional().default('draft'),
  notes: z.string().optional().default(''),
  units: z.array(z.object({
    id: z.string().optional().default(''),
    unitCode: z.string().optional().default(''),
    name: z.string().optional().default(''),
    floor: z.string().optional().default(''),
    area: z.coerce.number().min(0).default(0),
    saleValue: z.coerce.number().min(0).default(0),
    actualSaleValue: z.coerce.number().min(0).default(0),
    directCost: z.coerce.number().min(0).default(0),
    directCostEntries: z.array(z.object({
      id: z.string().optional().default(''),
      phase: z.string().optional().default(''),
      title: z.string().optional().default(''),
      amount: z.coerce.number().min(0).default(0),
      date: z.string().optional().default(''),
      notes: z.string().optional().default(''),
    })).default([]),
    buyerCustomerId: z.string().optional().default(''),
    buyerName: z.string().optional().default(''),
    contractDate: z.string().optional().default(''),
    handoverDate: z.string().optional().default(''),
    collectedAmount: z.coerce.number().min(0).default(0),
    lastCollectionDate: z.string().optional().default(''),
    installments: z.array(z.object({
      id: z.string().optional().default(''),
      title: z.string().optional().default(''),
      dueDate: z.string().optional().default(''),
      amount: z.coerce.number().min(0).default(0),
      paidAmount: z.coerce.number().min(0).default(0),
      status: z.enum(['pending', 'partially-paid', 'paid', 'overdue']).optional().default('pending'),
      notes: z.string().optional().default(''),
    })).default([]),
    status: z.enum(['planned', 'available', 'reserved', 'sold']).optional().default('planned'),
    notes: z.string().optional().default(''),
  })).default([]),
  sharedCosts: z.array(z.object({
    id: z.string().optional().default(''),
    title: z.string().optional().default(''),
    category: z.string().optional().default(''),
    amount: z.coerce.number().min(0).default(0),
    allocationMethod: z.enum(['area', 'sale-value', 'manual-share']).optional().default('area'),
    notes: z.string().optional().default(''),
    unitAllocations: z.array(z.object({
      unitId: z.string().min(1),
      percentage: z.coerce.number().min(0).max(100).default(0),
    })).default([]),
  })).default([]),
  sharedCostAllocationMethod: z.enum(['area', 'sale-value', 'manual-share']).optional().default('area'),
  sharedCostUnitAllocations: z.array(z.object({
    unitId: z.string().min(1),
    percentage: z.coerce.number().min(0).max(100).default(0),
  })).default([]),
});

type ProjectFormValues = z.infer<typeof projectFormSchema>;

type RealEstateCostingManagerProps = {
  initialProjects?: RealEstateProject[];
  materials?: ProductionItem[];
  expenses?: ProductionItem[];
  journalEntries?: JournalEntry[];
  accountingSetup?: RealEstateAccountingSetup;
  customers?: Customer[];
  purchaseOrders?: PurchaseOrder[];
  t: any;
  tGlobal: any;
  currencySymbol?: string;
};

type MainRealEstateTab = 'project-setup' | 'units' | 'installments' | 'shared-costs' | 'summary';

const getTodayValue = () => {
  const now = new Date();
  const local = new Date(now.getTime() - now.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 10);
};

const ENGLISH_INPUT_CLASSNAME = 'text-left font-mono tracking-[0.02em] [direction:ltr]';

const normalizeDigitsToEnglish = (value: string) => value
  .replace(/[٠-٩]/g, (digit) => String('٠١٢٣٤٥٦٧٨٩'.indexOf(digit)))
  .replace(/[۰-۹]/g, (digit) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(digit)));

const sanitizeIntegerValue = (value: string) => normalizeDigitsToEnglish(value).replace(/[^0-9]/g, '');

const sanitizeDecimalValue = (value: string) => {
  const normalized = normalizeDigitsToEnglish(value)
    .replace(/[٫٬،]/g, '.')
    .replace(/[^0-9.]/g, '');

  const [integerPart = '', ...decimalParts] = normalized.split('.');
  const decimalPart = decimalParts.join('').slice(0, 2);
  return decimalPart ? `${integerPart}.${decimalPart}` : integerPart;
};

const formatDecimalInputValue = (value: string) => {
  const sanitized = sanitizeDecimalValue(value);
  if (!sanitized) return '';

  const parsed = Number(sanitized);
  return Number.isFinite(parsed) ? parsed.toFixed(2) : sanitized;
};

const sanitizeDateValue = (value: string) => {
  const digits = normalizeDigitsToEnglish(value).replace(/[^0-9]/g, '').slice(0, 8);
  if (digits.length <= 4) return digits;
  if (digits.length <= 6) return `${digits.slice(0, 4)}-${digits.slice(4)}`;
  return `${digits.slice(0, 4)}-${digits.slice(4, 6)}-${digits.slice(6)}`;
};

const parseDateInputValue = (value?: string) => {
  const normalized = String(value || '').trim();
  if (!/^\d{4}-\d{2}-\d{2}$/.test(normalized)) return undefined;
  const parsed = new Date(`${normalized}T00:00:00`);
  return Number.isNaN(parsed.getTime()) ? undefined : parsed;
};

const toDateInputValue = (date: Date) => {
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 10);
};

const handleEnglishIntegerInput = (event: React.FormEvent<HTMLInputElement>) => {
  event.currentTarget.value = sanitizeIntegerValue(event.currentTarget.value);
};

const handleEnglishDecimalInput = (event: React.FormEvent<HTMLInputElement>) => {
  event.currentTarget.value = sanitizeDecimalValue(event.currentTarget.value);
};

const handleEnglishDecimalBlur = (event: React.FocusEvent<HTMLInputElement>) => {
  event.currentTarget.value = formatDecimalInputValue(event.currentTarget.value);
};

const handleEnglishDateInput = (event: React.FormEvent<HTMLInputElement>) => {
  event.currentTarget.value = sanitizeDateValue(event.currentTarget.value);
};

const handleSelectInputContent = (event: React.FocusEvent<HTMLInputElement>) => {
  event.currentTarget.select();
};

function DateInputWithPicker({
  value,
  onChange,
  placeholder = 'YYYY-MM-DD',
}: {
  value?: string;
  onChange: (value: string) => void;
  placeholder?: string;
}) {
  return (
    <div className="relative">
      <Input
        type="text"
        inputMode="numeric"
        maxLength={10}
        lang="en"
        dir="ltr"
        value={String(value || '')}
        className={`${ENGLISH_INPUT_CLASSNAME} pe-10`}
        placeholder={placeholder}
        onInput={handleEnglishDateInput}
        onFocus={handleSelectInputContent}
        onChange={(event) => onChange(sanitizeDateValue(event.target.value))}
      />
      <Popover>
        <PopoverTrigger asChild>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="absolute end-1 top-1 h-8 w-8 rounded-md text-muted-foreground hover:text-foreground"
          >
            <CalendarIcon className="h-4 w-4" />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="end">
          <Calendar
            mode="single"
            selected={parseDateInputValue(String(value || ''))}
            onSelect={(date) => date && onChange(toDateInputValue(date))}
            initialFocus
          />
        </PopoverContent>
      </Popover>
    </div>
  );
}

const createEmptyInstallment = () => ({
  id: `reinst-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
  title: '',
  dueDate: '',
  amount: 0,
  paidAmount: 0,
  status: 'pending' as const,
  notes: '',
});

const createEmptyDirectCostEntry = () => ({
  id: `redce-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
  phase: '',
  title: '',
  amount: 0,
  date: getTodayValue(),
  notes: '',
});

const createEmptyUnit = () => ({
  id: `reu-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
  unitCode: '',
  name: '',
  floor: '',
  area: 0,
  saleValue: 0,
  actualSaleValue: 0,
  directCost: 0,
  directCostEntries: [] as Array<ReturnType<typeof createEmptyDirectCostEntry>>,
  buyerCustomerId: '',
  buyerName: '',
  contractDate: '',
  handoverDate: '',
  collectedAmount: 0,
  lastCollectionDate: '',
  installments: [] as Array<ReturnType<typeof createEmptyInstallment>>,
  status: 'available' as const,
  notes: '',
});

const createEmptySharedCost = () => ({
  id: `resc-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
  title: '',
  category: '',
  amount: 0,
  allocationMethod: 'area' as const,
  notes: '',
  unitAllocations: [] as Array<{ unitId: string; percentage: number }>,
});

const createEmptyFloorUnitDetail = (estimatedSaleValue = 0) => ({
  id: `refunit-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
  unitLabel: '',
  area: 0,
  estimatedSaleValue,
  notes: '',
});

const createEmptyFloorDetail = (index?: number) => ({
  id: `refloor-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
  floorLabel: typeof index === 'number' ? `الطابق ${index + 1}` : '',
  usageType: '',
  description: '',
  unitCount: 0,
  unitArea: 0,
  estimatedUnitSaleValue: 0,
  unitDetails: [] as Array<ReturnType<typeof createEmptyFloorUnitDetail>>,
  notes: '',
});

const buildUnitsFromFloorDetails = (
  floorDetails: ProjectFormValues['floorDetails'] = [],
  existingUnits: ProjectFormValues['units'] = [],
): ProjectFormValues['units'] => {
  const existingById = new Map(existingUnits.map((unit) => [String(unit?.id || '').trim(), unit]));
  const existingByKey = new Map(
    existingUnits.map((unit) => [
      `${String(unit?.floor || '').trim()}__${String(unit?.name || unit?.unitCode || '').trim().toLowerCase()}`,
      unit,
    ]),
  );

  const derivedUnits = floorDetails.flatMap((floor, floorIndex) => {
    const floorLabel = String(floor?.floorLabel || `الطابق ${floorIndex + 1}`).trim();
    const rawUnitDetails = Array.isArray(floor?.unitDetails) ? floor.unitDetails : [];
    const fallbackUnitCount = rawUnitDetails.length > 0 ? rawUnitDetails.length : Math.max(0, Number(floor?.unitCount || 0));
    const fallbackArea = Math.max(0, Number(floor?.unitArea || 0));
    const fallbackSaleValue = Math.max(0, Number((floor as any)?.estimatedUnitSaleValue || 0));
    const unitDetails = rawUnitDetails.length > 0
      ? rawUnitDetails
      : Array.from({ length: fallbackUnitCount }, (_, detailIndex) => ({
          id: `${String(floor?.id || `floor-${floorIndex + 1}`)}-unit-${detailIndex + 1}`,
          unitLabel: '',
          area: fallbackArea,
          estimatedSaleValue: fallbackSaleValue,
          notes: '',
        }));

    return unitDetails.reduce<ProjectFormValues['units']>((acc, detail, detailIndex) => {
      const unitLabel = String(detail?.unitLabel || '').trim();
      const unitNotes = String(detail?.notes || '').trim();
      const area = Math.max(0, Number(detail?.area || 0));
      const estimatedSaleValue = Math.max(0, Number(detail?.estimatedSaleValue || 0));
      if (!unitLabel && !unitNotes && area <= 0 && estimatedSaleValue <= 0) {
        return acc;
      }

      const resolvedId = String(detail?.id || `${String(floor?.id || `floor-${floorIndex + 1}`)}-unit-${detailIndex + 1}`).trim();
      const resolvedName = unitLabel || `وحدة ${detailIndex + 1}`;
      const matchedUnit = existingById.get(resolvedId)
        || existingByKey.get(`${floorLabel}__${resolvedName.toLowerCase()}`);

      acc.push({
        id: resolvedId,
        unitCode: String(matchedUnit?.unitCode || `F${floorIndex + 1}-U${detailIndex + 1}`).trim(),
        name: resolvedName,
        floor: floorLabel || undefined,
        area,
        saleValue: estimatedSaleValue > 0 ? estimatedSaleValue : Math.max(0, Number(matchedUnit?.saleValue || 0)),
        actualSaleValue: Math.max(0, Number(matchedUnit?.actualSaleValue || 0)),
        directCost: Math.max(0, Number(matchedUnit?.directCost || 0)),
        directCostEntries: Array.isArray(matchedUnit?.directCostEntries) ? matchedUnit.directCostEntries : [],
        buyerCustomerId: String(matchedUnit?.buyerCustomerId || ''),
        buyerName: String(matchedUnit?.buyerName || ''),
        contractDate: String(matchedUnit?.contractDate || ''),
        handoverDate: String(matchedUnit?.handoverDate || ''),
        collectedAmount: Math.max(0, Number(matchedUnit?.collectedAmount || 0)),
        lastCollectionDate: String(matchedUnit?.lastCollectionDate || ''),
        installments: Array.isArray(matchedUnit?.installments) ? matchedUnit.installments : [],
        status: matchedUnit?.status || 'available',
        notes: unitNotes || String(matchedUnit?.notes || ''),
      });

      return acc;
    }, []);
  });

  return derivedUnits.length > 0 ? derivedUnits : existingUnits;
};

const hasMeaningfulUnitData = (unit?: Partial<ProjectFormValues['units'][number]> | null) => Boolean(
  String(unit?.unitCode || '').trim()
  || String(unit?.name || '').trim()
  || String(unit?.floor || '').trim()
  || String(unit?.buyerName || '').trim()
  || String(unit?.contractDate || '').trim()
  || String(unit?.handoverDate || '').trim()
  || Number(unit?.area || 0) > 0
  || Number(unit?.saleValue || 0) > 0
  || Number(unit?.actualSaleValue || 0) > 0
  || Number(unit?.directCost || 0) > 0
  || Number(unit?.collectedAmount || 0) > 0
  || (Array.isArray(unit?.installments) && unit.installments.length > 0)
  || (Array.isArray(unit?.directCostEntries) && unit.directCostEntries.length > 0)
  || (String(unit?.status || '').trim() && !['planned', 'available'].includes(String(unit?.status || '').trim())),
);

const buildEmptyProject = (): ProjectFormValues => ({
  id: '',
  name: '',
  code: '',
  location: '',
  startDate: getTodayValue(),
  targetCompletionDate: '',
  floorCount: 0,
  designSummary: '',
  floorDetails: [],
  status: 'draft',
  notes: '',
  units: [],
  sharedCosts: [createEmptySharedCost()],
  sharedCostAllocationMethod: 'area',
  sharedCostUnitAllocations: [],
});

const normalizeComparisonText = (value: string) => normalizeDigitsToEnglish(String(value || '').trim().toLowerCase());

function calculateProjectMetrics(
  units: ProjectFormValues['units'] = [],
  sharedCosts: ProjectFormValues['sharedCosts'] = [],
  options: {
    purchaseOrders?: PurchaseOrder[];
    projectId?: string;
    projectName?: string;
    projectSharedAllocationMethod?: 'area' | 'sale-value' | 'manual-share';
    projectSharedUnitAllocations?: Array<{ unitId?: string; percentage?: number }>;
  } = {},
) {
  const normalizedUnits = (units || [])
    .map((unit, index) => {
      const directCostEntries = Array.isArray(unit?.directCostEntries)
        ? unit.directCostEntries
            .map((entry, entryIndex) => ({
              id: String(entry?.id || `${String(unit?.id || `unit-${index + 1}`)}-dc-${entryIndex + 1}`),
              phase: String(entry?.phase || '').trim(),
              title: String(entry?.title || '').trim(),
              amount: Math.max(0, Number(entry?.amount || 0)),
              date: String(entry?.date || '').trim(),
              notes: String(entry?.notes || '').trim(),
            }))
            .filter((entry) => entry.phase || entry.title || entry.amount > 0 || entry.date || entry.notes)
        : [];

      const directCost = directCostEntries.length > 0
        ? directCostEntries.reduce((sum, entry) => sum + entry.amount, 0)
        : Math.max(0, Number(unit?.directCost || 0));

      return {
        id: String(unit?.id || `unit-${index + 1}`),
        unitCode: String(unit?.unitCode || '').trim(),
        name: String(unit?.name || '').trim(),
        floor: String(unit?.floor || '').trim(),
        notes: String(unit?.notes || '').trim(),
        area: Math.max(0, Number(unit?.area || 0)),
        saleValue: Math.max(0, Number(unit?.saleValue || 0)),
        actualSaleValue: Math.max(0, Number(unit?.actualSaleValue || 0)),
        directCost,
        directCostEntries,
        buyerName: String(unit?.buyerName || '').trim(),
        contractDate: String(unit?.contractDate || '').trim(),
        handoverDate: String(unit?.handoverDate || '').trim(),
        collectedAmount: Math.max(0, Number(unit?.collectedAmount || 0)),
        lastCollectionDate: String(unit?.lastCollectionDate || '').trim(),
        installments: Array.isArray(unit?.installments)
          ? unit.installments.map((installment, installmentIndex) => ({
              id: String(installment?.id || `${String(unit?.id || `unit-${index + 1}`)}-inst-${installmentIndex + 1}`),
              title: String(installment?.title || '').trim(),
              dueDate: String(installment?.dueDate || '').trim(),
              amount: Math.max(0, Number(installment?.amount || 0)),
              paidAmount: Math.max(0, Number(installment?.paidAmount || 0)),
              status: String(installment?.status || 'pending'),
              notes: String(installment?.notes || '').trim(),
            }))
          : [],
        status: String(unit?.status || 'planned'),
      };
    })
    .filter((unit) => unit.name || unit.unitCode || unit.area > 0 || unit.saleValue > 0 || unit.actualSaleValue > 0 || unit.directCost > 0 || unit.directCostEntries.length > 0 || unit.collectedAmount > 0 || unit.buyerName);

  const normalizedSharedCosts = (sharedCosts || [])
    .map((entry, index) => ({
      id: String(entry?.id || `shared-${index + 1}`),
      title: String(entry?.title || '').trim(),
      category: String(entry?.category || '').trim(),
      amount: Math.max(0, Number(entry?.amount || 0)),
      allocationMethod: String(entry?.allocationMethod || 'area') as 'area' | 'sale-value' | 'manual-share',
      notes: String(entry?.notes || '').trim(),
      unitAllocations: Array.isArray(entry?.unitAllocations)
        ? entry.unitAllocations.map((allocation) => ({
            unitId: String(allocation?.unitId || '').trim(),
            percentage: Math.max(0, Number(allocation?.percentage || 0)),
          }))
        : [],
    }))
    .filter((entry) => entry.title || entry.amount > 0);

  const normalizedProjectId = String(options.projectId || '').trim();
  const normalizedProjectName = normalizeComparisonText(String(options.projectName || ''));
  const matchesProjectRef = (projectId?: string, projectName?: string) => {
    const candidateId = String(projectId || '').trim();
    const candidateName = normalizeComparisonText(String(projectName || ''));
    return Boolean(
      (normalizedProjectId && candidateId && candidateId === normalizedProjectId)
      || (normalizedProjectName && candidateName && candidateName === normalizedProjectName)
    );
  };

  const normalizedProjectSharedAllocationMethod = String(options.projectSharedAllocationMethod || 'area') as 'area' | 'sale-value' | 'manual-share';
  const normalizedProjectSharedUnitAllocations = Array.isArray(options.projectSharedUnitAllocations)
    ? options.projectSharedUnitAllocations.map((allocation) => ({
        unitId: String(allocation?.unitId || '').trim(),
        percentage: Math.max(0, Number(allocation?.percentage || 0)),
      })).filter((allocation) => allocation.unitId)
    : [];

  const linkedPurchaseEntries = (options.purchaseOrders || [])
    .filter((order) => order && order.status !== 'cancelled' && (order.postingStatus || 'saved') !== 'draft')
    .flatMap((order) => {
      const normalizedSubTotal = Math.max(0, Number(order.subTotal || 0));
      const normalizedGrandTotal = Math.max(0, Number(order.grandTotal || 0));
      const resolveAllocatedAmount = (rawLineAmount: number) => {
        if (normalizedSubTotal > 0 && normalizedGrandTotal > 0) {
          return Number(((normalizedGrandTotal * Math.max(0, rawLineAmount || 0)) / normalizedSubTotal).toFixed(2));
        }
        return Math.max(0, Number(rawLineAmount || normalizedGrandTotal || 0));
      };

      const perLineEntries = (order.items || []).flatMap((item, itemIndex) => {
        if (!matchesProjectRef(item.realEstateProjectId, item.realEstateProjectName)) {
          return [];
        }

        const amount = resolveAllocatedAmount(Number(item.total || 0));
        if (amount <= 0) {
          return [];
        }

        return [{
          orderId: String(order.id || `po-${itemIndex + 1}`),
          orderNumber: String(order.orderNumber || `PO-${itemIndex + 1}`),
          supplierName: String(order.supplierName || '-'),
          date: String(order.date || ''),
          postingStatus: String(order.postingStatus || 'saved'),
          scope: String(item.realEstateScope || 'project') as 'project' | 'floor' | 'part',
          floorLabel: String(item.realEstateFloorLabel || '').trim(),
          partLabel: String(item.realEstatePartLabel || '').trim(),
          allocationMethod: String(item.realEstateAllocationMethod || order.realEstateAllocationMethod || normalizedProjectSharedAllocationMethod || 'area') as 'area' | 'sale-value' | 'manual-share',
          amount,
          sourceLabel: String(item.name || `سطر ${itemIndex + 1}`).trim() || `سطر ${itemIndex + 1}`,
        }];
      });

      if (perLineEntries.length > 0) {
        return perLineEntries;
      }

      if (!matchesProjectRef(order.realEstateProjectId, order.realEstateProjectName)) {
        return [];
      }

      const orderAmount = Math.max(0, normalizedGrandTotal || normalizedSubTotal);
      if (orderAmount <= 0) {
        return [];
      }

      return [{
        orderId: String(order.id || order.orderNumber || `po-${Date.now()}`),
        orderNumber: String(order.orderNumber || '-'),
        supplierName: String(order.supplierName || '-'),
        date: String(order.date || ''),
        postingStatus: String(order.postingStatus || 'saved'),
        scope: String(order.realEstateScope || 'project') as 'project' | 'floor' | 'part',
        floorLabel: String(order.realEstateFloorLabel || '').trim(),
        partLabel: String(order.realEstatePartLabel || '').trim(),
        allocationMethod: String(order.realEstateAllocationMethod || normalizedProjectSharedAllocationMethod || 'area') as 'area' | 'sale-value' | 'manual-share',
        amount: orderAmount,
        sourceLabel: String(order.supplierInvoiceNumber || order.orderNumber || 'فاتورة مشتريات').trim(),
      }];
    })
    .sort((left, right) => String(right.date || '').localeCompare(String(left.date || '')));

  const totalArea = normalizedUnits.reduce((sum, unit) => sum + unit.area, 0);
  const totalSaleValue = normalizedUnits.reduce((sum, unit) => sum + unit.saleValue, 0);
  const totalManualDirectCost = normalizedUnits.reduce((sum, unit) => sum + unit.directCost, 0);
  const totalManualSharedCost = normalizedSharedCosts.reduce((sum, entry) => sum + entry.amount, 0);
  const linkedPurchaseProjectCost = linkedPurchaseEntries
    .filter((entry) => entry.scope === 'project')
    .reduce((sum, entry) => sum + entry.amount, 0);
  const linkedPurchaseDirectCost = linkedPurchaseEntries
    .filter((entry) => entry.scope === 'floor' || entry.scope === 'part')
    .reduce((sum, entry) => sum + entry.amount, 0);
  const totalLinkedPurchaseCost = linkedPurchaseProjectCost + linkedPurchaseDirectCost;
  const totalDirectCost = totalManualDirectCost + linkedPurchaseDirectCost;
  const totalSharedCost = totalManualSharedCost + linkedPurchaseProjectCost;
  const totalContractedRevenue = normalizedUnits.reduce((sum, unit) => sum + Math.max(0, unit.actualSaleValue > 0 ? unit.actualSaleValue : (unit.status === 'sold' ? unit.saleValue : 0)), 0);
  const totalCollectedAmount = normalizedUnits.reduce((sum, unit) => sum + Math.max(0, unit.collectedAmount || 0), 0);
  const totalOutstandingAmount = Math.max(0, totalContractedRevenue - totalCollectedAmount);
  const soldUnitsCount = normalizedUnits.filter((unit) => unit.status === 'sold').length;
  const totalScheduledInstallments = normalizedUnits.reduce(
    (sum, unit) => sum + unit.installments.reduce((innerSum, installment) => innerSum + Math.max(0, installment.amount || 0), 0),
    0,
  );
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const collectionRate = totalContractedRevenue > 0 ? (totalCollectedAmount / totalContractedRevenue) * 100 : 0;

  const projectPurchaseManualAllocationTotal = normalizedProjectSharedUnitAllocations.reduce((sum, allocation) => sum + allocation.percentage, 0);
  const projectPurchaseUsesManualShare = normalizedProjectSharedAllocationMethod === 'manual-share'
    || linkedPurchaseEntries.some((entry) => entry.scope === 'project' && entry.allocationMethod === 'manual-share');

  const manualAllocationWarnings = [
    ...normalizedSharedCosts
      .filter((entry) => entry.allocationMethod === 'manual-share')
      .map((entry) => {
        const totalPercentage = entry.unitAllocations.reduce((sum, allocation) => sum + allocation.percentage, 0);
        return {
          title: entry.title || 'تكلفة مشتركة',
          totalPercentage,
        };
      })
      .filter((entry) => Math.abs(entry.totalPercentage - 100) > 0.01),
    ...(projectPurchaseUsesManualShare && Math.abs(projectPurchaseManualAllocationTotal - 100) > 0.01
      ? [{
          title: 'توزيع مشتريات المبنى كاملًا',
          totalPercentage: projectPurchaseManualAllocationTotal,
        }]
      : []),
  ];

  const distributeAmountAcrossUnits = (amount: number, targetUnits: typeof normalizedUnits, currentUnitId: string) => {
    if (amount <= 0 || targetUnits.length === 0 || !targetUnits.some((entry) => entry.id === currentUnitId)) {
      return 0;
    }

    const totalTargetArea = targetUnits.reduce((sum, entry) => sum + entry.area, 0);
    if (totalTargetArea > 0) {
      const targetUnit = targetUnits.find((entry) => entry.id === currentUnitId);
      return amount * Math.max(0, Number(targetUnit?.area || 0)) / totalTargetArea;
    }

    return amount / targetUnits.length;
  };

  const distributeSharedAmountToUnit = (
    amount: number,
    allocationMethod: 'area' | 'sale-value' | 'manual-share',
    unit: typeof normalizedUnits[number],
  ) => {
    if (amount <= 0) {
      return 0;
    }

    if (allocationMethod === 'sale-value') {
      return totalSaleValue > 0 ? (amount * unit.saleValue) / totalSaleValue : 0;
    }

    if (allocationMethod === 'manual-share') {
      const manualShare = normalizedProjectSharedUnitAllocations.find((allocation) => allocation.unitId === unit.id);
      if (manualShare) {
        return (amount * Math.max(0, Number(manualShare.percentage || 0))) / 100;
      }
    }

    if (totalArea > 0) {
      return (amount * unit.area) / totalArea;
    }

    return normalizedUnits.length > 0 ? amount / normalizedUnits.length : 0;
  };

  const unitSummaries = normalizedUnits.map((unit) => {
    const manualSharedAllocation = normalizedSharedCosts.reduce((sum, cost) => {
      if (cost.amount <= 0) return sum;
      if (cost.allocationMethod === 'area') {
        return sum + (totalArea > 0 ? (cost.amount * unit.area) / totalArea : 0);
      }
      if (cost.allocationMethod === 'sale-value') {
        return sum + (totalSaleValue > 0 ? (cost.amount * unit.saleValue) / totalSaleValue : 0);
      }

      const manualShare = cost.unitAllocations.find((allocation) => allocation.unitId === unit.id);
      return sum + ((cost.amount * Math.max(0, Number(manualShare?.percentage || 0))) / 100);
    }, 0);

    const linkedSharedAllocation = linkedPurchaseEntries.reduce((sum, entry) => {
      if (entry.scope !== 'project' || entry.amount <= 0) {
        return sum;
      }

      return sum + distributeSharedAmountToUnit(entry.amount, entry.allocationMethod || normalizedProjectSharedAllocationMethod, unit);
    }, 0);
    const resolvedLinkedDirectCost = linkedPurchaseEntries.reduce((sum, entry) => {
      if (entry.scope === 'project' || entry.amount <= 0) {
        return sum;
      }

      const normalizedEntryFloor = normalizeComparisonText(entry.floorLabel || '');
      const unitsOnSameFloor = normalizedEntryFloor
        ? normalizedUnits.filter((candidate) => normalizeComparisonText(candidate.floor || '') === normalizedEntryFloor)
        : [];

      let targetUnits = unitsOnSameFloor.length > 0 ? unitsOnSameFloor : normalizedUnits;
      if (entry.scope === 'part') {
        const normalizedPart = normalizeComparisonText(entry.partLabel || '');
        if (normalizedPart) {
          const partMatchedUnits = targetUnits.filter((candidate) => normalizeComparisonText(`${candidate.name} ${candidate.unitCode} ${candidate.notes}`).includes(normalizedPart));
          if (partMatchedUnits.length > 0) {
            targetUnits = partMatchedUnits;
          }
        }
      }

      return sum + distributeAmountAcrossUnits(entry.amount, targetUnits, unit.id);
    }, 0);

    const allocatedSharedCost = manualSharedAllocation + linkedSharedAllocation;
    const directCost = unit.directCost + resolvedLinkedDirectCost;
    const paidByInstallments = unit.installments.reduce((sum, installment) => sum + Math.max(0, installment.paidAmount || 0), 0);
    const effectiveCollectedAmount = Math.max(unit.collectedAmount, paidByInstallments);
    const normalizedInstallments = unit.installments.map((installment) => {
      const remaining = Math.max(0, Number(installment.amount || 0) - Number(installment.paidAmount || 0));
      const dueDate = installment.dueDate ? new Date(installment.dueDate) : null;
      if (dueDate) dueDate.setHours(0, 0, 0, 0);
      const derivedStatus = remaining <= 0
        ? 'paid'
        : dueDate && dueDate < today
          ? 'overdue'
          : Number(installment.paidAmount || 0) > 0
            ? 'partially-paid'
            : String(installment.status || 'pending');
      return {
        ...installment,
        remaining,
        status: derivedStatus,
      };
    });
    const totalCost = directCost + allocatedSharedCost;
    const revenueValue = unit.actualSaleValue > 0 ? unit.actualSaleValue : unit.saleValue;
    const margin = revenueValue - totalCost;
    const costPerSqm = unit.area > 0 ? totalCost / unit.area : 0;
    const outstandingAmount = Math.max(0, revenueValue - effectiveCollectedAmount);
    const unitCollectionRate = revenueValue > 0 ? (effectiveCollectedAmount / revenueValue) * 100 : 0;
    const overdueInstallments = normalizedInstallments.filter((installment) => installment.status === 'overdue');
    const nextDueInstallment = normalizedInstallments
      .filter((installment) => installment.remaining > 0 && installment.dueDate)
      .sort((left, right) => String(left.dueDate || '').localeCompare(String(right.dueDate || '')))[0];

    return {
      ...unit,
      installments: normalizedInstallments,
      manualDirectCost: unit.directCost,
      linkedPurchaseDirectCost: resolvedLinkedDirectCost,
      linkedPurchaseSharedCost: linkedSharedAllocation,
      directCost,
      allocatedSharedCost,
      totalCost,
      revenueValue,
      margin,
      costPerSqm,
      collectedAmount: effectiveCollectedAmount,
      outstandingAmount,
      collectionRate: unitCollectionRate,
      overdueInstallments,
      nextDueInstallment,
    };
  });

  const dueAlerts = unitSummaries.flatMap((unit) =>
    unit.installments
      .filter((installment) => installment.remaining > 0 && installment.dueDate)
      .map((installment) => ({
        unitName: unit.name || unit.unitCode || '-',
        buyerName: unit.buyerName || '-',
        dueDate: installment.dueDate,
        amount: installment.amount,
        remaining: installment.remaining,
        status: installment.status,
        title: installment.title || 'قسط',
      }))
  ).sort((left, right) => String(left.dueDate || '').localeCompare(String(right.dueDate || '')));

  return {
    totalArea,
    totalSaleValue,
    totalManualDirectCost,
    totalManualSharedCost,
    totalLinkedPurchaseCost,
    linkedPurchaseProjectCost,
    linkedPurchaseDirectCost,
    linkedPurchaseEntries,
    totalDirectCost,
    totalSharedCost,
    totalContractedRevenue,
    totalCollectedAmount,
    totalOutstandingAmount,
    soldUnitsCount,
    totalScheduledInstallments,
    overdueInstallmentsCount: dueAlerts.filter((alert) => alert.status === 'overdue').length,
    collectionRate,
    dueAlerts,
    totalProjectCost: totalDirectCost + totalSharedCost,
    projectMargin: totalSaleValue - (totalDirectCost + totalSharedCost),
    unitSummaries,
    manualAllocationWarnings,
  };
}

export default function RealEstateCostingManager({
  initialProjects = [],
  materials = [],
  expenses = [],
  journalEntries = [],
  accountingSetup,
  customers = [],
  purchaseOrders = [],
  t,
  tGlobal,
  currencySymbol = '$',
}: RealEstateCostingManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [projects, setProjects] = useState<RealEstateProject[]>(initialProjects);
  const [journalEntryList, setJournalEntryList] = useState<JournalEntry[]>(journalEntries);
  const [selectedProjectId, setSelectedProjectId] = useState<string>(initialProjects[0]?.id || 'new');
  const [postingDate, setPostingDate] = useState(getTodayValue());
  const [postingItemId, setPostingItemId] = useState('');
  const [postingAmount, setPostingAmount] = useState('');
  const [postingPaymentSource, setPostingPaymentSource] = useState<'cash' | 'bank' | 'payable'>('cash');
  const [postingNote, setPostingNote] = useState('');
  const [activeTab, setActiveTab] = useState<MainRealEstateTab>('project-setup');
  const [isUnitDialogOpen, setIsUnitDialogOpen] = useState(false);
  const [pendingNewUnitIndex, setPendingNewUnitIndex] = useState<number | null>(null);
  const [activeUnitIndex, setActiveUnitIndex] = useState<number | null>(null);
  const [focusedContractUnitIndex, setFocusedContractUnitIndex] = useState<number | null>(null);
  const [customerList, setCustomerList] = useState<Customer[]>(customers);
  const [showAddCustomerDialog, setShowAddCustomerDialog] = useState(false);
  const [buyerTargetUnitIndex, setBuyerTargetUnitIndex] = useState<number | null>(null);
  const [expandedFloorIndex, setExpandedFloorIndex] = useState<number | null>(0);

  const form = useForm<ProjectFormValues>({
    resolver: zodResolver(projectFormSchema),
    defaultValues: initialProjects[0]
      ? {
          ...initialProjects[0],
          floorCount: Number(initialProjects[0].floorCount || initialProjects[0].floorDetails?.length || 0),
          designSummary: String(initialProjects[0].designSummary || ''),
          floorDetails: initialProjects[0].floorDetails?.length ? initialProjects[0].floorDetails : [],
          units: initialProjects[0].units?.length ? initialProjects[0].units : [],
          sharedCosts: initialProjects[0].sharedCosts?.length ? initialProjects[0].sharedCosts : [createEmptySharedCost()],
          sharedCostAllocationMethod: initialProjects[0].sharedCostAllocationMethod || 'area',
          sharedCostUnitAllocations: initialProjects[0].sharedCostUnitAllocations || [],
        }
      : buildEmptyProject(),
  });

  const { fields: unitFields, append: appendUnit, remove: removeUnit } = useFieldArray({
    control: form.control,
    name: 'units',
  });

  const { fields: sharedCostFields, append: appendSharedCost, remove: removeSharedCost } = useFieldArray({
    control: form.control,
    name: 'sharedCosts',
  });

  const { fields: floorDetailFields, append: appendFloorDetail, remove: removeFloorDetail } = useFieldArray({
    control: form.control,
    name: 'floorDetails',
  });

  const watchedUnits = useWatch({ control: form.control, name: 'units' }) || [];
  const watchedSharedCosts = useWatch({ control: form.control, name: 'sharedCosts' }) || [];
  const watchedProjectSharedAllocationMethod = useWatch({ control: form.control, name: 'sharedCostAllocationMethod' }) || 'area';
  const watchedProjectSharedUnitAllocations = useWatch({ control: form.control, name: 'sharedCostUnitAllocations' }) || [];
  const watchedFloorDetails = useWatch({ control: form.control, name: 'floorDetails' }) || [];
  const watchedFloorCount = useWatch({ control: form.control, name: 'floorCount' }) || 0;

  const liveMetrics = useMemo(
    () => calculateProjectMetrics(watchedUnits, watchedSharedCosts, {
      purchaseOrders,
      projectId: String(form.watch('id') || selectedProjectId || '').trim(),
      projectName: String(form.watch('name') || '').trim(),
      projectSharedAllocationMethod: watchedProjectSharedAllocationMethod,
      projectSharedUnitAllocations: watchedProjectSharedUnitAllocations,
    }),
    [watchedUnits, watchedSharedCosts, watchedProjectSharedAllocationMethod, watchedProjectSharedUnitAllocations, purchaseOrders, form, selectedProjectId],
  );

  const selectedProject = useMemo(
    () => projects.find((project) => String(project.id || '') === String(selectedProjectId || '')),
    [projects, selectedProjectId],
  );

  const activeAccountingSetup = selectedProject?.accounting || accountingSetup;
  const activeUnit = activeUnitIndex !== null ? watchedUnits[activeUnitIndex] : null;
  const activeUnitDirectCostEntries = Array.isArray(activeUnit?.directCostEntries) ? activeUnit.directCostEntries : [];
  const activeUnitLabel = activeUnit
    ? String(activeUnit?.name || activeUnit?.unitCode || `Unit ${(activeUnitIndex ?? 0) + 1}`)
    : '';

  const buyerCustomerOptions = useMemo(() => (
    customerList
      .map((customer) => ({
        selectorId: `customer:${customer.id}`,
        originalId: String(customer.id || ''),
        label: String(customer.name || '').trim(),
        phone: String(customer.phone || '').trim(),
        address: String(customer.address || '').trim(),
      }))
      .filter((entry) => entry.originalId && entry.label)
      .sort((left, right) => left.label.localeCompare(right.label, 'ar'))
  ), [customerList]);

  const resolveBuyerCustomerValue = (customerId?: string) => {
    const normalizedId = String(customerId || '').trim();
    if (!normalizedId) return '';
    const matchedCustomer = buyerCustomerOptions.find((entry) => entry.originalId === normalizedId);
    return matchedCustomer?.selectorId || '';
  };

  const handleBuyerCustomerChange = (unitIndex: number, selectorValue: string) => {
    const selectedCustomer = buyerCustomerOptions.find((entry) => entry.selectorId === selectorValue);
    if (!selectedCustomer) return;

    form.setValue(`units.${unitIndex}.buyerCustomerId`, selectedCustomer.originalId, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
    form.setValue(`units.${unitIndex}.buyerName`, selectedCustomer.label, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const linkedCatalogItems = useMemo(() => {
    const projectId = String(selectedProject?.id || '').trim();
    if (!projectId) return [] as Array<{
      id: string;
      itemType: 'material' | 'expense';
      name: string;
      itemNumber?: string;
      unitName?: string;
      costType: string;
      purchasePrice?: number;
    }>;

    const unitNameById = new Map(
      (selectedProject?.units || []).map((unit) => [String(unit.id || '').trim(), String(unit.name || unit.unitCode || '').trim()]),
    );

    const collect = (entries: ProductionItem[], itemType: 'material' | 'expense') => entries
      .filter((entry) => String(entry.realEstateProjectId || '').trim() === projectId)
      .map((entry) => ({
        id: String(entry.id || ''),
        itemType,
        name: String(entry.name || ''),
        itemNumber: String(entry.itemNumber || ''),
        unitName: unitNameById.get(String(entry.realEstateUnitId || '').trim()) || undefined,
        costType: String(entry.realEstateCostType || 'general'),
        purchasePrice: typeof entry.purchasePrice === 'number' ? entry.purchasePrice : undefined,
      }));

    return [...collect(materials, 'material'), ...collect(expenses, 'expense')]
      .sort((left, right) => left.name.localeCompare(right.name));
  }, [selectedProject, materials, expenses]);

  const projectJournalEntries = useMemo(() => {
    const relevantCodes = new Set([
      String(activeAccountingSetup?.projectAccountCode || '').trim(),
      String(activeAccountingSetup?.directCostAccountCode || '').trim(),
      String(activeAccountingSetup?.sharedCostAccountCode || '').trim(),
    ].filter(Boolean));

    if (!selectedProject || relevantCodes.size === 0) return [] as Array<JournalEntry & { relevantDebit: number; relevantCredit: number }>;

    return journalEntryList
      .map((entry) => {
        const relevantLines = (entry.lines || []).filter((line) => relevantCodes.has(String(line.accountCode || '').trim()));
        if (relevantLines.length === 0) return null;
        return {
          ...entry,
          relevantDebit: relevantLines.reduce((sum, line) => sum + Number(line.debit || 0), 0),
          relevantCredit: relevantLines.reduce((sum, line) => sum + Number(line.credit || 0), 0),
        };
      })
      .filter((entry): entry is JournalEntry & { relevantDebit: number; relevantCredit: number } => !!entry)
      .sort((left, right) => String(right.date || '').localeCompare(String(left.date || '')))
      .slice(0, 12);
  }, [activeAccountingSetup, journalEntryList, selectedProject]);

  useEffect(() => {
    setFocusedContractUnitIndex(null);

    if (!selectedProject || selectedProjectId === 'new') {
      form.reset(buildEmptyProject());
      return;
    }

    form.reset({
      ...selectedProject,
      floorCount: Number(selectedProject.floorCount || selectedProject.floorDetails?.length || 0),
      designSummary: String(selectedProject.designSummary || ''),
      floorDetails: selectedProject.floorDetails?.length ? selectedProject.floorDetails : [],
      units: selectedProject.units?.length ? selectedProject.units : [],
      sharedCosts: selectedProject.sharedCosts?.length ? selectedProject.sharedCosts : [createEmptySharedCost()],
      sharedCostAllocationMethod: selectedProject.sharedCostAllocationMethod || 'area',
      sharedCostUnitAllocations: selectedProject.sharedCostUnitAllocations || [],
    });
  }, [selectedProject, selectedProjectId, form]);

  useEffect(() => {
    setPostingDate(getTodayValue());
    setPostingAmount('');
    setPostingNote('');
    setPostingPaymentSource('cash');
    setPostingItemId((prev) => linkedCatalogItems.some((entry) => entry.id === prev) ? prev : (linkedCatalogItems[0]?.id || ''));
  }, [selectedProjectId, linkedCatalogItems]);

  useEffect(() => {
    watchedUnits.forEach((unit, index) => {
      const directCostEntries = Array.isArray(unit?.directCostEntries) ? unit.directCostEntries : [];
      if (directCostEntries.length === 0) return;

      const computedTotal = directCostEntries.reduce((sum, entry) => sum + Math.max(0, Number(entry?.amount || 0)), 0);
      const currentValue = Math.max(0, Number(form.getValues(`units.${index}.directCost`) || 0));

      if (Math.abs(currentValue - computedTotal) > 0.0001) {
        form.setValue(`units.${index}.directCost`, computedTotal, {
          shouldDirty: true,
          shouldTouch: false,
          shouldValidate: false,
        });
      }
    });
  }, [watchedUnits, form]);

  useEffect(() => {
    watchedFloorDetails.forEach((floor, index) => {
      const currentUsage = String(floor?.usageType || '').trim();
      const unitDetails = Array.isArray(floor?.unitDetails) ? floor.unitDetails : [];
      const meaningfulUnitDetails = unitDetails.filter((entry) => String(entry?.unitLabel || '').trim() || Number(entry?.area || 0) > 0 || Number(entry?.estimatedSaleValue || 0) > 0 || String(entry?.notes || '').trim());

      const currentLabel = String(form.getValues(`floorDetails.${index}.floorLabel`) || '').trim();
      if (!currentLabel) {
        form.setValue(`floorDetails.${index}.floorLabel`, `الطابق ${index + 1}`, {
          shouldDirty: true,
          shouldTouch: false,
          shouldValidate: false,
        });
      }

      if (currentUsage !== 'apartments' || meaningfulUnitDetails.length === 0) {
        return;
      }

      const computedCount = meaningfulUnitDetails.length;
      const computedAverageArea = Number((meaningfulUnitDetails.reduce((sum, entry) => sum + Math.max(0, Number(entry?.area || 0)), 0) / computedCount).toFixed(2));
      const currentCount = Math.max(0, Number(form.getValues(`floorDetails.${index}.unitCount`) || 0));
      const currentArea = Math.max(0, Number(form.getValues(`floorDetails.${index}.unitArea`) || 0));

      if (currentCount !== computedCount) {
        form.setValue(`floorDetails.${index}.unitCount`, computedCount, {
          shouldDirty: true,
          shouldTouch: false,
          shouldValidate: false,
        });
      }

      if (Math.abs(currentArea - computedAverageArea) > 0.0001) {
        form.setValue(`floorDetails.${index}.unitArea`, computedAverageArea, {
          shouldDirty: true,
          shouldTouch: false,
          shouldValidate: false,
        });
      }
    });

    const currentUnits = form.getValues('units') || [];
    const nextUnits = buildUnitsFromFloorDetails(watchedFloorDetails, currentUnits);
    if (JSON.stringify(currentUnits) !== JSON.stringify(nextUnits)) {
      form.setValue('units', nextUnits as any, {
        shouldDirty: true,
        shouldTouch: false,
        shouldValidate: false,
      });
    }
  }, [watchedFloorDetails, form]);

  useEffect(() => {
    if (floorDetailFields.length === 0) {
      setExpandedFloorIndex(null);
      return;
    }

    setExpandedFloorIndex((current) => {
      if (current === null) {
        return 0;
      }

      return current >= floorDetailFields.length ? floorDetailFields.length - 1 : current;
    });
  }, [floorDetailFields.length]);

  const syncFloorCardsToCount = (requestedCount?: number) => {
    const desiredFloorCount = Math.max(0, Number((requestedCount ?? form.getValues('floorCount')) || 0));
    const currentFloorDetails = [...(form.getValues('floorDetails') || [])];
    const currentFloorCount = currentFloorDetails.length;

    if (desiredFloorCount <= 0) {
      if (currentFloorCount === 0) {
        form.setValue('floorDetails', [] as any, {
          shouldDirty: true,
          shouldTouch: true,
          shouldValidate: false,
        });
        setExpandedFloorIndex(null);
      } else {
        form.setValue('floorCount', currentFloorCount, {
          shouldDirty: true,
          shouldTouch: true,
          shouldValidate: false,
        });
      }
      return;
    }

    if (desiredFloorCount < currentFloorCount) {
      form.setValue('floorCount', currentFloorCount, {
        shouldDirty: true,
        shouldTouch: true,
        shouldValidate: false,
      });
      return;
    }

    const nextFloorDetails = [...currentFloorDetails];
    for (let index = nextFloorDetails.length; index < desiredFloorCount; index += 1) {
      nextFloorDetails.push(createEmptyFloorDetail(index));
    }

    nextFloorDetails.forEach((floor, index) => {
      if (!String(floor?.floorLabel || '').trim()) {
        nextFloorDetails[index] = {
          ...floor,
          floorLabel: `الطابق ${index + 1}`,
        };
      }
    });

    form.setValue('floorDetails', nextFloorDetails as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
    setExpandedFloorIndex(desiredFloorCount > currentFloorCount ? desiredFloorCount - 1 : expandedFloorIndex);
  };

  useEffect(() => {
    const requestedFloorCount = Math.max(0, Number(watchedFloorCount || 0));
    if (requestedFloorCount > floorDetailFields.length) {
      syncFloorCardsToCount(requestedFloorCount);
    }
  }, [watchedFloorCount, floorDetailFields.length]);

  const updateManualShare = (costIndex: number, unitId: string, value: string) => {
    const currentAllocations = [...(form.getValues(`sharedCosts.${costIndex}.unitAllocations`) || [])];
    const parsedValue = Math.max(0, Number(value || 0));
    const existingIndex = currentAllocations.findIndex((entry) => String(entry.unitId || '') === String(unitId || ''));

    if (existingIndex >= 0) {
      currentAllocations[existingIndex] = { ...currentAllocations[existingIndex], unitId, percentage: parsedValue };
    } else {
      currentAllocations.push({ unitId, percentage: parsedValue });
    }

    form.setValue(`sharedCosts.${costIndex}.unitAllocations`, currentAllocations as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const updateProjectSharedAllocation = (unitId: string, value: string) => {
    const currentAllocations = [...(form.getValues('sharedCostUnitAllocations') || [])];
    const parsedValue = Math.max(0, Number(value || 0));
    const existingIndex = currentAllocations.findIndex((entry) => String(entry.unitId || '') === String(unitId || ''));

    if (existingIndex >= 0) {
      currentAllocations[existingIndex] = { ...currentAllocations[existingIndex], unitId, percentage: parsedValue };
    } else {
      currentAllocations.push({ unitId, percentage: parsedValue });
    }

    form.setValue('sharedCostUnitAllocations', currentAllocations as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const handleUnitDialogChange = (open: boolean) => {
    setIsUnitDialogOpen(open);

    if (!open) {
      if (pendingNewUnitIndex !== null) {
        const pendingUnit = form.getValues(`units.${pendingNewUnitIndex}` as const);
        if (!hasMeaningfulUnitData(pendingUnit)) {
          removeUnit(pendingNewUnitIndex);
        }
      }
      setPendingNewUnitIndex(null);
      setActiveUnitIndex(null);
    }
  };

  const openUnitDialogForAdd = () => {
    const nextIndex = unitFields.length;
    appendUnit(createEmptyUnit());
    setPendingNewUnitIndex(nextIndex);
    setActiveUnitIndex(nextIndex);
    setIsUnitDialogOpen(true);
  };

  const openUnitDialog = (unitIndex: number) => {
    setPendingNewUnitIndex((current) => (current === unitIndex ? current : null));
    setActiveUnitIndex(unitIndex);
    setIsUnitDialogOpen(true);
  };

  const deleteUnitAndCloseDialog = (unitIndex: number) => {
    removeUnit(unitIndex);
    setPendingNewUnitIndex(null);
    setActiveUnitIndex(null);
    setIsUnitDialogOpen(false);
  };

  const redirectSoldUnitToContracts = (unitIndex: number, closeDialog = true) => {
    setFocusedContractUnitIndex(unitIndex);
    setActiveTab('installments');
    if (closeDialog) {
      handleUnitDialogChange(false);
    }
    toast({
      title: tGlobal?.success ?? 'تم',
      description: t?.soldUnitRedirectHint ?? 'تم تحديد الوحدة كمباعة. أكمل الآن بيانات العقد والتحصيل في التبويب المخصص.',
    });
  };

  const handleSaveUnitDialog = () => {
    const currentIndex = activeUnitIndex;
    if (currentIndex === null) {
      handleUnitDialogChange(false);
      return;
    }

    const selectedStatus = String(form.getValues(`units.${currentIndex}.status`) || 'available');
    if (selectedStatus === 'sold') {
      redirectSoldUnitToContracts(currentIndex, true);
      return;
    }

    handleUnitDialogChange(false);
  };

  const addDirectCostEntryToUnit = (unitIndex: number) => {
    const currentEntries = [...(form.getValues(`units.${unitIndex}.directCostEntries`) || [])];
    currentEntries.push(createEmptyDirectCostEntry());
    form.setValue(`units.${unitIndex}.directCostEntries`, currentEntries as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const removeDirectCostEntryFromUnit = (unitIndex: number, entryIndex: number) => {
    const currentEntries = [...(form.getValues(`units.${unitIndex}.directCostEntries`) || [])];
    currentEntries.splice(entryIndex, 1);
    form.setValue(`units.${unitIndex}.directCostEntries`, currentEntries as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const addInstallmentToUnit = (unitIndex: number) => {
    const currentInstallments = [...(form.getValues(`units.${unitIndex}.installments`) || [])];
    currentInstallments.push(createEmptyInstallment());
    form.setValue(`units.${unitIndex}.installments`, currentInstallments as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const removeInstallmentFromUnit = (unitIndex: number, installmentIndex: number) => {
    const currentInstallments = [...(form.getValues(`units.${unitIndex}.installments`) || [])];
    currentInstallments.splice(installmentIndex, 1);
    form.setValue(`units.${unitIndex}.installments`, currentInstallments as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const addFloorUnitDetailToFloor = (floorIndex: number) => {
    const currentDetails = [...(form.getValues(`floorDetails.${floorIndex}.unitDetails`) || [])];
    const floorDefaultSaleValue = Math.max(0, Number(form.getValues(`floorDetails.${floorIndex}.estimatedUnitSaleValue`) || 0));
    currentDetails.push(createEmptyFloorUnitDetail(floorDefaultSaleValue));
    form.setValue(`floorDetails.${floorIndex}.unitDetails`, currentDetails as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const removeFloorUnitDetailFromFloor = (floorIndex: number, unitDetailIndex: number) => {
    const currentDetails = [...(form.getValues(`floorDetails.${floorIndex}.unitDetails`) || [])];
    currentDetails.splice(unitDetailIndex, 1);
    form.setValue(`floorDetails.${floorIndex}.unitDetails`, currentDetails as any, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: false,
    });
  };

  const onSubmit = (values: ProjectFormValues) => {
    startTransition(async () => {
      const result = await handleSaveRealEstateProject(values);
      if (!result || 'error' in result) {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: (result as any)?.error || (t?.realEstateSaveError ?? 'تعذر حفظ المشروع العقاري.'),
          variant: 'destructive',
        });
        return;
      }

      const savedProject = (result as any).project as RealEstateProject;
      setProjects((prev) => [savedProject, ...prev.filter((entry) => entry.id !== savedProject.id)]);
      setSelectedProjectId(savedProject.id);
      setActiveTab('project-setup');
      form.reset({
        ...savedProject,
        floorCount: Number(savedProject.floorCount || savedProject.floorDetails?.length || 0),
        designSummary: String(savedProject.designSummary || ''),
        floorDetails: savedProject.floorDetails?.length ? savedProject.floorDetails : [],
        units: savedProject.units?.length ? savedProject.units : [],
        sharedCosts: savedProject.sharedCosts?.length ? savedProject.sharedCosts : [createEmptySharedCost()],
      });

      toast({
        title: tGlobal?.success ?? 'تم',
        description: t?.realEstateSaveSuccess ?? 'تم حفظ المشروع العقاري بنجاح.',
      });
    });
  };

  const handlePostAccountingEntry = () => {
    const projectId = String(selectedProject?.id || '').trim();
    if (!projectId) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.selectProjectFirstError ?? 'اختر مشروعاً أولاً قبل ترحيل القيد.',
        variant: 'destructive',
      });
      return;
    }

    const amountValue = Number(postingAmount || 0);
    if (!postingItemId || !Number.isFinite(amountValue) || amountValue <= 0) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.realEstatePostingValidationError ?? 'اختر البند وأدخل مبلغاً صحيحاً قبل الترحيل.',
        variant: 'destructive',
      });
      return;
    }

    startTransition(async () => {
      const result = await handlePostRealEstateCostEntry({
        projectId,
        itemId: postingItemId,
        date: postingDate,
        amount: amountValue,
        paymentSource: postingPaymentSource,
        note: postingNote,
      });

      if (!result || 'error' in result) {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: (result as any)?.error || (t?.realEstatePostingError ?? 'تعذر ترحيل القيد المحاسبي للمشروع.'),
          variant: 'destructive',
        });
        return;
      }

      const newEntry = (result as any).entry as JournalEntry;
      setJournalEntryList((prev) => [newEntry, ...prev.filter((entry) => entry.id !== newEntry.id)]);
      setPostingAmount('');
      setPostingNote('');
      toast({
        title: tGlobal?.success ?? 'تم',
        description: t?.realEstatePostingSuccess ?? 'تم ترحيل القيد المحاسبي للمشروع بنجاح.',
      });
    });
  };

  const handleDeleteCurrent = () => {
    const currentId = String(form.getValues('id') || '').trim();
    if (!currentId) {
      form.reset(buildEmptyProject());
      setSelectedProjectId('new');
      setActiveTab('project-setup');
      return;
    }

    startTransition(async () => {
      const result = await handleDeleteRealEstateProject(currentId);
      if (!result || 'error' in result) {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: (result as any)?.error || (t?.realEstateDeleteError ?? 'تعذر حذف المشروع.'),
          variant: 'destructive',
        });
        return;
      }

      const remainingProjects = projects.filter((entry) => entry.id !== currentId);
      setProjects(remainingProjects);
      setSelectedProjectId(remainingProjects[0]?.id || 'new');
      setActiveTab('project-setup');
      form.reset(remainingProjects[0]
        ? {
            ...remainingProjects[0],
            floorCount: Number(remainingProjects[0].floorCount || remainingProjects[0].floorDetails?.length || 0),
            designSummary: String(remainingProjects[0].designSummary || ''),
            floorDetails: remainingProjects[0].floorDetails?.length ? remainingProjects[0].floorDetails : [],
            units: remainingProjects[0].units?.length ? remainingProjects[0].units : [],
            sharedCosts: remainingProjects[0].sharedCosts?.length ? remainingProjects[0].sharedCosts : [createEmptySharedCost()],
          }
        : buildEmptyProject());

      toast({
        title: tGlobal?.success ?? 'تم',
        description: t?.realEstateDeleteSuccess ?? 'تم حذف المشروع بنجاح.',
      });
    });
  };

  return (
    <div className="space-y-6">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <div className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Building2 className="h-5 w-5" />
                  {t?.realEstateProjectsTitle ?? 'المشاريع العقارية'}
                </CardTitle>
                <CardDescription>
                  {t?.realEstateProjectsDescription ?? 'اختر المشروع أولاً، ثم أكمل بياناته ووحداته وتكاليفه من التبويبات الفرعية الخاصة به.'}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button
                  type="button"
                  className="w-full justify-start"
                  onClick={() => {
                    form.reset(buildEmptyProject());
                    setSelectedProjectId('new');
                    setActiveTab('project-setup');
                  }}
                >
                  <PlusCircle className="me-2 h-4 w-4" />
                  {t?.newRealEstateProjectButton ?? 'مشروع عقاري جديد'}
                </Button>

                <div>
                  {projects.length === 0 ? (
                    <div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                      {t?.noRealEstateProjects ?? 'لا توجد مشاريع عقارية محفوظة بعد.'}
                    </div>
                  ) : (
                    <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                      {projects.map((project) => {
                        const metrics = calculateProjectMetrics(project.units || [], project.sharedCosts || [], {
                          purchaseOrders,
                          projectId: String(project.id || '').trim(),
                          projectName: String(project.name || '').trim(),
                          projectSharedAllocationMethod: project.sharedCostAllocationMethod || 'area',
                          projectSharedUnitAllocations: project.sharedCostUnitAllocations || [],
                        });
                        const isSelected = selectedProjectId === project.id;
                        return (
                          <button
                            key={project.id}
                            type="button"
                            onClick={() => {
                              setSelectedProjectId(project.id);
                              setActiveTab('project-setup');
                            }}
                            className={`group rounded-xl border p-4 text-start shadow-sm transition-all ${isSelected ? 'border-primary bg-primary/5 ring-1 ring-primary/30' : 'bg-card hover:border-primary/40 hover:bg-muted/30'}`}
                          >
                            <div className="flex items-start justify-between gap-3">
                              <div className="min-w-0">
                                <div className="truncate text-base font-semibold">{project.name}</div>
                                <div className="mt-1 text-xs text-muted-foreground">{project.code || '—'}</div>
                              </div>
                              <span className={`rounded-full px-2.5 py-1 text-[11px] font-medium ${isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted text-foreground'}`}>
                                {project.status === 'completed' ? (t?.completedStatusLabel ?? 'مكتمل') : project.status === 'active' ? (t?.activeStatusLabel ?? 'نشط') : (t?.draftStatusLabel ?? 'مسودة')}
                              </span>
                            </div>

                            <div className="mt-3 rounded-lg bg-muted/40 p-3 text-xs text-muted-foreground space-y-2">
                              <div>{project.location || (t?.locationLabel ?? 'الموقع')}</div>
                              <div className="grid grid-cols-3 gap-2">
                                <div>
                                  <div className="text-[10px]">{t?.unitsCountLabel ?? 'الوحدات'}</div>
                                  <div className="font-semibold text-foreground">{(project.units || []).length}</div>
                                </div>
                                <div>
                                  <div className="text-[10px]">{t?.floorCountLabel ?? 'الطوابق'}</div>
                                  <div className="font-semibold text-foreground">{Number(project.floorCount || project.floorDetails?.length || 0)}</div>
                                </div>
                                <div>
                                  <div className="text-[10px]">{t?.totalCostLabel ?? 'إجمالي التكلفة'}</div>
                                  <div className="font-semibold text-foreground">{formatCurrency(metrics.totalProjectCost, currencySymbol)}</div>
                                </div>
                              </div>
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            <div className="rounded-xl border bg-muted/20 p-3 text-sm">
              <div className="font-medium">{t?.currentProjectLabel ?? 'المشروع الحالي'}</div>
              <div className="mt-1 text-muted-foreground">
                {selectedProject?.name || form.watch('name') || (t?.newRealEstateProjectButton ?? 'مشروع عقاري جديد')} • {selectedProject?.code || form.watch('code') || '—'} • {Number(form.watch('floorCount') || selectedProject?.floorCount || selectedProject?.floorDetails?.length || 0)} {t?.floorCountLabel ?? 'طوابق'}
              </div>
            </div>

            <Tabs
              value={activeTab}
              onValueChange={(value) => setActiveTab(value as MainRealEstateTab)}
              className="space-y-4"
            >
              <div className="overflow-x-auto">
                <TabsList className="h-auto flex-wrap justify-start gap-1">
                  <TabsTrigger value="project-setup" className="text-xs sm:text-sm">{t?.projectInfoTitle ?? 'بيانات المشروع'}</TabsTrigger>
                  <TabsTrigger value="shared-costs" className="text-xs sm:text-sm">{t?.sharedCostsTitle ?? 'التكاليف المشتركة'}</TabsTrigger>
                  <TabsTrigger value="installments" className="text-xs sm:text-sm">{t?.contractsCollectionsTitle ?? 'العقود والتحصيل'}</TabsTrigger>
                  <TabsTrigger value="summary" className="text-xs sm:text-sm">{t?.summaryAndAccountingTitle ?? 'الملخص والمحاسبة'}</TabsTrigger>
                </TabsList>
              </div>

              <TabsContent value="project-setup">
          <Card>
            <CardHeader>
              <CardTitle>{form.watch('name') || (t?.projectInfoTitle ?? 'بيانات المشروع')}</CardTitle>
              <CardDescription>
                {t?.projectSetupDescription ?? 'ابدأ بتسجيل بيانات المشروع الأساسية، ثم أدخل الطوابق والوحدات من التفاصيل الهندسية للمبنى، وبعدها أكمل العقود والتكاليف.'}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-xl border bg-muted/20 p-4 space-y-4">
                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                  <div className="space-y-2 rounded-lg border bg-background p-3">
                    <Label>{t?.projectNameLabel ?? 'اسم المشروع'}</Label>
                    <Input {...form.register('name')} placeholder={t?.projectNamePlaceholder ?? 'عمارة الندى السكنية'} />
                  </div>
                  <div className="space-y-2 rounded-lg border bg-background p-3">
                    <Label>{t?.projectCodeLabel ?? 'رمز المشروع'}</Label>
                    <Input {...form.register('code')} placeholder={t?.projectCodePlaceholder ?? 'REA-001'} />
                  </div>
                  <div className="space-y-2 rounded-lg border bg-background p-3">
                    <Label>{t?.locationLabel ?? 'الموقع'}</Label>
                    <Input {...form.register('location')} placeholder={t?.locationPlaceholder ?? 'الرياض / حي الياسمين'} />
                  </div>
                  <div className="space-y-2 rounded-lg border bg-background p-3">
                    <Label>{t?.projectStatusLabel ?? 'الحالة'}</Label>
                    <select
                      {...form.register('status')}
                      className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
                    >
                      <option value="draft">{t?.draftStatusLabel ?? 'مسودة'}</option>
                      <option value="active">{t?.activeStatusLabel ?? 'نشط'}</option>
                      <option value="completed">{t?.completedStatusLabel ?? 'مكتمل'}</option>
                    </select>
                  </div>
                </div>

                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                  <div className="space-y-2 rounded-lg border bg-background p-3">
                    <Label>{t?.startDateLabel ?? 'تاريخ البداية'}</Label>
                    <DateInputWithPicker
                      value={String(form.watch('startDate') || '')}
                      onChange={(value) => form.setValue('startDate', value, { shouldDirty: true, shouldTouch: true, shouldValidate: false })}
                    />
                  </div>
                  <div className="space-y-2 rounded-lg border bg-background p-3">
                    <Label>{t?.targetCompletionDateLabel ?? 'تاريخ الإنجاز المتوقع'}</Label>
                    <DateInputWithPicker
                      value={String(form.watch('targetCompletionDate') || '')}
                      onChange={(value) => form.setValue('targetCompletionDate', value, { shouldDirty: true, shouldTouch: true, shouldValidate: false })}
                    />
                  </div>
                </div>

                <div className="space-y-2 rounded-lg border bg-background p-3">
                  <Label>{t?.notesLabel ?? 'ملاحظات'}</Label>
                  <Textarea {...form.register('notes')} placeholder={t?.realEstateNotesPlaceholder ?? 'ملاحظات المشروع، مرحلة التنفيذ، أو معلومات التمويل.'} />
                </div>

                <div className="space-y-3 rounded-xl border bg-background/80 p-3">
                  <div>
                    <p className="font-medium">{t?.engineeringDetailsTitle ?? 'التفاصيل الهندسية للمبنى'}</p>
                    <p className="text-xs text-muted-foreground">
                      {t?.engineeringDetailsDescription ?? 'سجّل عدد الطوابق ووظيفة كل طابق مثل مستودع، مواقف، شقق، مع عدد الوحدات ومساحاتها.'}
                    </p>
                  </div>

                  <div className="grid gap-4 md:grid-cols-[320px_minmax(0,1fr)]">
                    <div className="space-y-2 rounded-lg border bg-background p-3">
                      <Label>{t?.floorCountLabel ?? 'عدد الطوابق'}</Label>
                      <div className="flex flex-col gap-2 sm:flex-row">
                        <Input
                          type="text"
                          inputMode="numeric"
                          lang="en"
                          dir="ltr"
                          className={`sm:flex-1 ${ENGLISH_INPUT_CLASSNAME} bg-muted/60 cursor-not-allowed`}
                          placeholder="0"
                          value={String(Math.max(0, Number(watchedFloorCount || 0)))}
                          readOnly
                          onFocus={handleSelectInputContent}
                        />
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          className="sm:min-w-[130px]"
                          onClick={() => {
                            const currentCount = Math.max(0, (form.getValues('floorDetails') || []).length);
                            const nextCount = currentCount + 1;
                            form.setValue('floorCount', nextCount, {
                              shouldDirty: true,
                              shouldTouch: true,
                              shouldValidate: false,
                            });
                            syncFloorCardsToCount(nextCount);
                          }}
                        >
                          <PlusCircle className="me-2 h-4 w-4" />
                          {t?.addFloorDetailButton ?? 'إضافة طابق'}
                        </Button>
                      </div>
                      <p className="text-[11px] text-muted-foreground">
                        {t?.floorCountHelperText ?? 'هذا الحقل يعرض العدد الحالي فقط. استخدم زر إضافة طابق للزيادة، وعند حذف بطاقة طابق يتحدث العدد تلقائيًا.'}
                      </p>
                    </div>
                    <div className="space-y-2 rounded-lg border bg-background p-3">
                      <Label>{t?.designSummaryLabel ?? 'ملخص التصميم الهندسي'}</Label>
                      <Textarea
                        {...form.register('designSummary')}
                        placeholder={t?.designSummaryPlaceholder ?? 'مثال: مبنى سكني تجاري، الدور الأرضي مواقف وخدمات، والأدوار العليا شقق سكنية.'}
                      />
                    </div>
                  </div>

                  {floorDetailFields.length === 0 ? (
                    <div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                      {t?.noFloorDetailsYet ?? 'لم تتم إضافة تفاصيل الطوابق بعد.'}
                    </div>
                  ) : (
                    <div className="grid gap-3">
                      {floorDetailFields.map((field, index) => {
                        const currentFloorUsage = String(watchedFloorDetails[index]?.usageType || '').trim();
                        const currentFloorUnitDetails = Array.isArray(watchedFloorDetails[index]?.unitDetails)
                          ? watchedFloorDetails[index]?.unitDetails || []
                          : [];
                        const floorTitle = String(watchedFloorDetails[index]?.floorLabel || `الطابق ${index + 1}`);
                        const unitCountSummary = Math.max(0, Number(watchedFloorDetails[index]?.unitCount || 0));
                        const unitAreaSummary = Math.max(0, Number(watchedFloorDetails[index]?.unitArea || 0));
                        const isFloorExpanded = expandedFloorIndex === index;
                        const usageSummaryLabel = ({
                          warehouse: t?.warehouseLabel ?? 'مستودع',
                          parking: t?.parkingLabel ?? 'موقف سيارات',
                          apartments: t?.apartmentsLabel ?? 'شقق',
                          commercial: t?.commercialLabel ?? 'تجاري',
                          services: t?.servicesLabel ?? 'خدمات',
                          mixed: t?.mixedUseLabel ?? 'متعدد الاستخدام',
                          other: t?.otherLabel ?? 'أخرى',
                        } as Record<string, string>)[currentFloorUsage] || (t?.selectFloorUsagePlaceholder ?? 'اختر الاستخدام');

                        return (
                        <div key={field.id} className="rounded-2xl border bg-card p-3 shadow-sm space-y-3">
                          <div className="flex flex-wrap items-start justify-between gap-3">
                            <div className="space-y-2">
                              <div>
                                <div className="text-sm font-semibold">{floorTitle}</div>
                                <div className="text-xs text-muted-foreground">{t?.floorDetailsRowLabel ?? 'تفصيل الطابق'} {index + 1}</div>
                              </div>
                              <div className="flex flex-wrap gap-2 text-[11px]">
                                <span className="rounded-full bg-muted px-2.5 py-1 font-medium text-foreground/80">{usageSummaryLabel}</span>
                                <span className="rounded-full border bg-background px-2.5 py-1 text-muted-foreground">
                                  {(t?.unitsPerFloorLabel ?? 'عدد الوحدات/الشقق')}: {unitCountSummary}
                                </span>
                                <span className="rounded-full border bg-background px-2.5 py-1 text-muted-foreground">
                                  {(currentFloorUsage === 'apartments' ? (t?.averageUnitAreaLabel ?? 'متوسط مساحة الشقة') : (t?.unitAreaLabel ?? 'مساحة الوحدة'))}: {unitAreaSummary.toFixed(2)} م²
                                </span>
                              </div>
                            </div>
                            <div className="flex flex-wrap items-center gap-2">
                              <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={() => setExpandedFloorIndex((current) => (current === index ? null : index))}
                              >
                                <PencilLine className="me-2 h-4 w-4" />
                                {isFloorExpanded ? (t?.hideFloorDetailsButton ?? 'إخفاء التفاصيل') : (t?.editFloorDetailsButton ?? 'إدخال التفاصيل')}
                              </Button>
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                onClick={() => {
                                  removeFloorDetail(index);
                                  const nextCount = Math.max(0, floorDetailFields.length - 1);
                                  form.setValue('floorCount', nextCount, { shouldDirty: true, shouldTouch: true, shouldValidate: false });
                                  setExpandedFloorIndex((current) => {
                                    if (nextCount <= 0) return null;
                                    if (current === null) return 0;
                                    if (current === index) return Math.max(0, index - 1);
                                    return current > index ? current - 1 : current;
                                  });
                                }}
                                disabled={floorDetailFields.length === 1}
                                title={t?.removeFloorButton ?? 'حذف الطابق'}
                              >
                                <Trash2 className="h-4 w-4 text-destructive" />
                              </Button>
                            </div>
                          </div>

                          {isFloorExpanded && (
                            <div className="space-y-4 border-t pt-3">
                              <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-6">
                                <div className="space-y-1 rounded-lg border bg-background p-2.5">
                                  <Label className="text-xs text-muted-foreground">{t?.floorLabel ?? 'الطابق'}</Label>
                                  <Input {...form.register(`floorDetails.${index}.floorLabel` as const)} placeholder={t?.floorLabelPlaceholder ?? 'الطابق الأول'} />
                                </div>
                                <div className="space-y-1 rounded-lg border bg-background p-2.5">
                                  <Label className="text-xs text-muted-foreground">{t?.floorUsageLabel ?? 'الاستخدام'}</Label>
                                  <select
                                    {...form.register(`floorDetails.${index}.usageType` as const)}
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
                                  >
                                    <option value="">{t?.selectFloorUsagePlaceholder ?? 'اختر الاستخدام'}</option>
                                    <option value="warehouse">{t?.warehouseLabel ?? 'مستودع'}</option>
                                    <option value="parking">{t?.parkingLabel ?? 'موقف سيارات'}</option>
                                    <option value="apartments">{t?.apartmentsLabel ?? 'شقق'}</option>
                                    <option value="commercial">{t?.commercialLabel ?? 'تجاري'}</option>
                                    <option value="services">{t?.servicesLabel ?? 'خدمات'}</option>
                                    <option value="mixed">{t?.mixedUseLabel ?? 'متعدد الاستخدام'}</option>
                                    <option value="other">{t?.otherLabel ?? 'أخرى'}</option>
                                  </select>
                                </div>
                                <div className="space-y-1 rounded-lg border bg-background p-2.5">
                                  <Label className="text-xs text-muted-foreground">{t?.unitsPerFloorLabel ?? 'عدد الوحدات/الشقق'}</Label>
                                  <Input
                                    type="text"
                                    inputMode="numeric"
                                    lang="en"
                                    dir="ltr"
                                    className={currentFloorUsage === 'apartments' ? `${ENGLISH_INPUT_CLASSNAME} bg-muted/60 cursor-not-allowed` : ENGLISH_INPUT_CLASSNAME}
                                    placeholder="0"
                                    {...form.register(`floorDetails.${index}.unitCount` as const)}
                                    readOnly={currentFloorUsage === 'apartments'}
                                    onInput={handleEnglishIntegerInput}
                                    onFocus={handleSelectInputContent}
                                  />
                                </div>
                                <div className="space-y-1 rounded-lg border bg-background p-2.5">
                                  <Label className="text-xs text-muted-foreground">{currentFloorUsage === 'apartments' ? (t?.averageUnitAreaLabel ?? 'متوسط مساحة الشقة') : (t?.unitAreaLabel ?? 'مساحة الوحدة')}</Label>
                                  <Input
                                    type="text"
                                    inputMode="decimal"
                                    lang="en"
                                    dir="ltr"
                                    className={currentFloorUsage === 'apartments' ? `${ENGLISH_INPUT_CLASSNAME} bg-muted/60 cursor-not-allowed` : ENGLISH_INPUT_CLASSNAME}
                                    placeholder="0.00"
                                    {...form.register(`floorDetails.${index}.unitArea` as const)}
                                    readOnly={currentFloorUsage === 'apartments'}
                                    onInput={handleEnglishDecimalInput}
                                    onBlur={handleEnglishDecimalBlur}
                                    onFocus={handleSelectInputContent}
                                  />
                                </div>
                                <div className="space-y-1 rounded-lg border bg-background p-2.5">
                                  <Label className="text-xs text-muted-foreground">
                                    {currentFloorUsage === 'apartments'
                                      ? (t?.estimatedUnitSaleValueLabel ?? 'القيمة البيعية التقديرية للوحدة')
                                      : (t?.saleValueLabel ?? 'القيمة البيعية التقديرية')}
                                  </Label>
                                  <Input
                                    type="text"
                                    inputMode="decimal"
                                    lang="en"
                                    dir="ltr"
                                    className={ENGLISH_INPUT_CLASSNAME}
                                    placeholder="0.00"
                                    {...form.register(`floorDetails.${index}.estimatedUnitSaleValue` as const)}
                                    onInput={handleEnglishDecimalInput}
                                    onBlur={handleEnglishDecimalBlur}
                                    onFocus={handleSelectInputContent}
                                  />
                                  <p className="text-[10px] text-muted-foreground">
                                    {currentFloorUsage === 'apartments'
                                      ? (t?.estimatedUnitSaleValueHint ?? 'قيمة افتراضية تُستخدم للشقق الجديدة ويمكن تعديلها لاحقًا داخل بطاقات الشقق أدناه.')
                                      : (t?.saleValueFieldHint ?? 'تُستخدم هذه القيمة عند اختيار التوزيع حسب القيمة البيعية.')}
                                  </p>
                                </div>
                                <div className="space-y-1 rounded-lg border bg-background p-2.5 xl:col-span-2">
                                  <Label className="text-xs text-muted-foreground">{t?.floorContentLabel ?? 'تفاصيل المحتوى'}</Label>
                                  <Input {...form.register(`floorDetails.${index}.description` as const)} placeholder={t?.floorContentPlaceholder ?? 'مثال: 4 شقق، مستودع رئيسي، أو مواقف سيارات'} />
                                </div>
                                <div className="space-y-1 rounded-lg border bg-background p-2.5 xl:col-span-3">
                                  <Label className="text-xs text-muted-foreground">{t?.engineeringNotesLabel ?? 'ملاحظات هندسية'}</Label>
                                  <Textarea {...form.register(`floorDetails.${index}.notes` as const)} placeholder={t?.engineeringNotesPlaceholder ?? 'أي ملاحظات إضافية عن هذا الطابق أو توزيع الوحدات'} />
                                </div>
                              </div>

                              {currentFloorUsage === 'apartments' && (
                                <div className="space-y-3 rounded-xl border bg-background p-3">
                                  <div className="flex flex-wrap items-start justify-between gap-2">
                                    <div>
                                      <p className="font-medium">{t?.apartmentDetailsTitle ?? 'تفصيل الشقق داخل الطابق'}</p>
                                      <p className="text-xs text-muted-foreground">
                                        {t?.apartmentDetailsDescription ?? 'أدخل كل شقة ومساحتها وقيمتها البيعية التقديرية بشكل مستقل، وسيتم احتساب العدد ومتوسط المساحة تلقائيًا واستخدام هذه البيانات في التوزيع.'}
                                      </p>
                                    </div>
                                    <Button type="button" variant="outline" size="sm" onClick={() => addFloorUnitDetailToFloor(index)}>
                                      <PlusCircle className="me-2 h-4 w-4" />
                                      {t?.addApartmentDetailButton ?? 'إضافة شقة'}
                                    </Button>
                                  </div>

                                  {currentFloorUnitDetails.length === 0 ? (
                                    <div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                                      {t?.noApartmentDetailsYet ?? 'لم تتم إضافة الشقق لهذا الطابق بعد.'}
                                    </div>
                                  ) : (
                                    <div className="grid gap-3 md:grid-cols-2">
                                      {currentFloorUnitDetails.map((unitDetail, unitDetailIndex) => {
                                        const unitCardTitle = String(unitDetail?.unitLabel || `${t?.apartmentsLabel ?? 'شقة'} ${unitDetailIndex + 1}`);

                                        return (
                                          <div key={String(unitDetail?.id || `${field.id}-${unitDetailIndex}`)} className="rounded-xl border bg-muted/10 p-3 shadow-sm space-y-3">
                                            <div className="flex items-start justify-between gap-2 border-b pb-2">
                                              <div>
                                                <p className="text-sm font-semibold">{unitCardTitle}</p>
                                                <p className="text-[11px] text-muted-foreground">{t?.apartmentDetailCardHint ?? 'أدخل بيانات هذه الشقة بشكل واضح.'}</p>
                                              </div>
                                              <Button
                                                type="button"
                                                variant="ghost"
                                                size="icon"
                                                onClick={() => removeFloorUnitDetailFromFloor(index, unitDetailIndex)}
                                                title={t?.removeApartmentDetailButton ?? 'حذف الشقة'}
                                              >
                                                <Trash2 className="h-4 w-4 text-destructive" />
                                              </Button>
                                            </div>

                                            <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                                              <div className="space-y-1">
                                                <Label className="text-xs text-muted-foreground">{t?.apartmentLabelField ?? 'اسم/رقم الشقة'}</Label>
                                                <Input
                                                  {...form.register(`floorDetails.${index}.unitDetails.${unitDetailIndex}.unitLabel` as const)}
                                                  placeholder={t?.apartmentLabelPlaceholder ?? 'شقة 1'}
                                                />
                                              </div>
                                              <div className="space-y-1">
                                                <Label className="text-xs text-muted-foreground">{t?.areaSqmLabel ?? 'المساحة (م²)'}</Label>
                                                <Input
                                                  type="text"
                                                  inputMode="decimal"
                                                  lang="en"
                                                  dir="ltr"
                                                  className={ENGLISH_INPUT_CLASSNAME}
                                                  placeholder="0.00"
                                                  {...form.register(`floorDetails.${index}.unitDetails.${unitDetailIndex}.area` as const)}
                                                  onInput={handleEnglishDecimalInput}
                                                  onBlur={handleEnglishDecimalBlur}
                                                  onFocus={handleSelectInputContent}
                                                />
                                                <p className="text-[10px] text-muted-foreground">{t?.areaFieldHint ?? 'تُستخدم هذه القيمة عند اختيار التوزيع حسب المساحة.'}</p>
                                              </div>
                                              <div className="space-y-1">
                                                <Label className="text-xs text-muted-foreground">{t?.saleValueLabel ?? 'القيمة البيعية التقديرية'}</Label>
                                                <Input
                                                  type="text"
                                                  inputMode="decimal"
                                                  lang="en"
                                                  dir="ltr"
                                                  className={ENGLISH_INPUT_CLASSNAME}
                                                  placeholder="0.00"
                                                  {...form.register(`floorDetails.${index}.unitDetails.${unitDetailIndex}.estimatedSaleValue` as const)}
                                                  onInput={handleEnglishDecimalInput}
                                                  onBlur={handleEnglishDecimalBlur}
                                                  onFocus={handleSelectInputContent}
                                                />
                                                <p className="text-[10px] text-muted-foreground">{t?.saleValueFieldHint ?? 'تُستخدم هذه القيمة عند اختيار التوزيع حسب القيمة البيعية.'}</p>
                                              </div>
                                              <div className="space-y-1 sm:col-span-2 xl:col-span-3">
                                                <Label className="text-xs text-muted-foreground">{t?.apartmentNotesLabel ?? 'الوصف والملاحظات'}</Label>
                                                <Input
                                                  {...form.register(`floorDetails.${index}.unitDetails.${unitDetailIndex}.notes` as const)}
                                                  placeholder={t?.apartmentNotesPlaceholder ?? 'ملاحظات مثل: أمامية، خلفية، أو دوبلكس'}
                                                />
                                              </div>
                                            </div>
                                          </div>
                                        );
                                      })}
                                    </div>
                                  )}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      );
                      })}
                    </div>
                  )}
                </div>
              </div>

              <div className="flex flex-wrap gap-2 border-t pt-2">
                <Button type="submit" disabled={isPending}>
                  {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                  {t?.saveProjectButton ?? 'حفظ المشروع'}
                </Button>
                <Button type="button" variant="outline" disabled={isPending} onClick={handleDeleteCurrent}>
                  {t?.deleteProjectButton ?? 'حذف المشروع'}
                </Button>
              </div>
            </CardContent>
          </Card>
            </TabsContent>

            <TabsContent value="units">
          <Card>
            <CardHeader>
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <CardTitle>{t?.unitDefinitionTitle ?? 'تعريف الوحدات'}</CardTitle>
                  <CardDescription>
                    {t?.realEstateUnitsDescription ?? 'في هذه الخطوة يتم تعريف الوحدات الأساسية فقط: الرمز، الاسم، الطابق، المساحة، القيمة التقديرية، والتكلفة المباشرة.'}
                  </CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button type="button" variant="outline" size="sm" onClick={openUnitDialogForAdd}>
                    <PlusCircle className="me-2 h-4 w-4" />
                    {t?.addUnitButton ?? 'إضافة وحدة'}
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {liveMetrics.unitSummaries.length === 0 ? (
                <div className="rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground">
                  {t?.noRealEstateUnitsYet ?? 'لا توجد وحدات مضافة بعد. استخدم زر إضافة وحدة لفتح نافذة الإدخال.'}
                </div>
              ) : (
                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                  {liveMetrics.unitSummaries.map((unit, index) => {
                    const statusLabel = unit.status === 'sold'
                      ? (t?.soldStatusLabel ?? 'مباع')
                      : unit.status === 'reserved'
                        ? (t?.reservedStatusLabel ?? 'محجوز')
                        : unit.status === 'available'
                          ? (t?.availableStatusLabel ?? 'متاح')
                          : (t?.plannedStatusLabel ?? 'مخطط');

                    return (
                      <div key={String(unit.id)} className="rounded-2xl border bg-card p-4 shadow-sm space-y-4">
                        <div className="flex items-start justify-between gap-3">
                          <div className="min-w-0">
                            <div className="truncate text-base font-semibold">{unit.name || unit.unitCode || (t?.unnamedUnitLabel ?? 'وحدة بدون اسم')}</div>
                            <div className="mt-1 text-xs text-muted-foreground">{unit.unitCode || '—'} • {t?.floorLabel ?? 'الطابق'}: {unit.floor || '—'}</div>
                          </div>
                          <span className="rounded-full bg-muted px-2.5 py-1 text-xs font-medium text-foreground">
                            {statusLabel}
                          </span>
                        </div>

                        <div className="grid grid-cols-2 gap-2 text-sm">
                          <div className="rounded-lg bg-muted/40 p-2.5">
                            <div className="text-[11px] text-muted-foreground">{t?.areaLabel ?? 'المساحة m²'}</div>
                            <div className="font-mono font-semibold">{Number(unit.area || 0).toFixed(2)}</div>
                          </div>
                          <div className="rounded-lg bg-muted/40 p-2.5">
                            <div className="text-[11px] text-muted-foreground">{t?.saleValueLabel ?? 'القيمة التقديرية'}</div>
                            <div className="font-mono font-semibold">{formatCurrency(unit.saleValue || 0, currencySymbol)}</div>
                          </div>
                          <div className="rounded-lg bg-muted/40 p-2.5">
                            <div className="text-[11px] text-muted-foreground">{t?.directCostLabel ?? 'التكلفة المباشرة'}</div>
                            <div className="font-mono font-semibold">{formatCurrency(unit.directCost || 0, currencySymbol)}</div>
                          </div>
                          <div className="rounded-lg bg-muted/40 p-2.5">
                            <div className="text-[11px] text-muted-foreground">{t?.actualSaleValueLabel ?? 'قيمة العقد'}</div>
                            <div className="font-mono font-semibold">{formatCurrency(unit.actualSaleValue || unit.saleValue || 0, currencySymbol)}</div>
                          </div>
                        </div>

                        <div className="space-y-1 text-xs text-muted-foreground">
                          <div>{t?.buyerNameLabel ?? 'المشتري'}: <span className="text-foreground">{unit.buyerName || '—'}</span></div>
                          <div>{t?.collectedAmountLabel ?? 'المحصل'}: <span className="font-mono text-foreground">{formatCurrency(unit.collectedAmount || 0, currencySymbol)}</span></div>
                          <div>
                            {unit.directCostEntries?.length
                              ? `${t?.directCostItemsLabel ?? 'بنود التكلفة المباشرة'}: ${unit.directCostEntries.length}`
                              : (t?.stagedDirectCostHint ?? 'يمكن تسجيل التكلفة المباشرة على مراحل من نافذة إدارة الوحدات')}
                          </div>
                        </div>

                        <div className="flex justify-end">
                          <Button type="button" variant="ghost" size="sm" onClick={() => openUnitDialog(index)}>
                            <PencilLine className="me-2 h-4 w-4" />
                            {t?.editUnitButton ?? 'تعديل الوحدة'}
                          </Button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              <Dialog open={isUnitDialogOpen} onOpenChange={handleUnitDialogChange}>
                <DialogContent className="max-w-[95vw] lg:max-w-4xl max-h-[90vh] overflow-y-auto">
                  <DialogHeader>
                    <DialogTitle>{t?.unitDefinitionTitle ?? 'تعريف الوحدات العقارية'}</DialogTitle>
                    <DialogDescription>
                      {t?.unitsDialogDescription ?? 'أدخل بيانات كل وحدة بشكل مستقل، ثم ستظهر الوحدات كبطاقات تفصيلية في الصفحة.'}
                    </DialogDescription>
                  </DialogHeader>

                  {activeUnit && activeUnitIndex !== null ? (
                    <div className="space-y-4">
                      <div className="flex flex-wrap items-center justify-between gap-2 rounded-xl border bg-muted/20 p-3">
                        <div>
                          <div className="font-medium">{activeUnitLabel}</div>
                          <div className="text-xs text-muted-foreground">
                            {(t?.unitDialogCounter ?? 'الوحدة')} {activeUnitIndex + 1} / {unitFields.length}
                          </div>
                        </div>
                        <div className="flex flex-wrap gap-2">
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => setActiveUnitIndex((current) => current !== null ? Math.max(0, current - 1) : 0)}
                            disabled={activeUnitIndex === 0}
                          >
                            {t?.previousLabel ?? 'السابق'}
                          </Button>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => setActiveUnitIndex((current) => current !== null ? Math.min(unitFields.length - 1, current + 1) : 0)}
                            disabled={activeUnitIndex >= unitFields.length - 1}
                          >
                            {t?.nextLabel ?? 'التالي'}
                          </Button>
                          <Button type="button" variant="outline" size="sm" onClick={openUnitDialogForAdd}>
                            <PlusCircle className="me-2 h-4 w-4" />
                            {t?.addAnotherUnitButton ?? 'إضافة وحدة أخرى'}
                          </Button>
                        </div>
                      </div>

                      <div className="rounded-xl border bg-muted/20 p-3 space-y-3">
                        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                          <div className="space-y-2 rounded-lg border bg-background p-3">
                            <Label>{t?.unitCodeLabel ?? 'رمز الوحدة'}</Label>
                            <Input {...form.register(`units.${activeUnitIndex}.unitCode` as const)} placeholder="A-101" />
                          </div>
                          <div className="space-y-2 rounded-lg border bg-background p-3 xl:col-span-2">
                            <Label>{t?.unitNameLabel ?? 'اسم الوحدة'}</Label>
                            <Input {...form.register(`units.${activeUnitIndex}.name` as const)} placeholder={t?.unitNamePlaceholder ?? 'شقة 101'} />
                          </div>
                          <div className="space-y-2 rounded-lg border bg-background p-3">
                            <Label>{t?.statusLabel ?? 'الحالة'}</Label>
                            <select
                              value={String(activeUnit?.status || 'available')}
                              onChange={(event) => {
                                const nextStatus = event.target.value as ProjectFormValues['units'][number]['status'];
                                form.setValue(`units.${activeUnitIndex}.status`, nextStatus, {
                                  shouldDirty: true,
                                  shouldTouch: true,
                                  shouldValidate: false,
                                });

                                if (nextStatus === 'sold') {
                                  redirectSoldUnitToContracts(activeUnitIndex, true);
                                }
                              }}
                              className="w-full min-w-[130px] h-10 rounded-md border border-input bg-background px-2.5 py-2 text-sm focus:ring-2 focus:ring-ring"
                            >
                              <option value="planned">{t?.plannedStatusLabel ?? 'مخطط'}</option>
                              <option value="available">{t?.availableStatusLabel ?? 'متاح'}</option>
                              <option value="reserved">{t?.reservedStatusLabel ?? 'محجوز'}</option>
                              <option value="sold">{t?.soldStatusLabel ?? 'مباع'}</option>
                            </select>
                          </div>
                        </div>

                        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                          <div className="space-y-2 rounded-lg border bg-background p-3">
                            <Label>{t?.floorLabel ?? 'الطابق'}</Label>
                            <Input {...form.register(`units.${activeUnitIndex}.floor` as const)} placeholder="1" />
                          </div>
                          <div className="space-y-2 rounded-lg border bg-background p-3">
                            <Label>{t?.areaLabel ?? 'المساحة m²'}</Label>
                            <Input
                              type="text"
                              inputMode="decimal"
                              lang="en"
                              dir="ltr"
                              className={ENGLISH_INPUT_CLASSNAME}
                              placeholder="0.00"
                              {...form.register(`units.${activeUnitIndex}.area` as const)}
                              onInput={handleEnglishDecimalInput}
                              onBlur={handleEnglishDecimalBlur}
                              onFocus={handleSelectInputContent}
                            />
                          </div>
                          <div className="space-y-2 rounded-lg border bg-background p-3">
                            <Label>{t?.saleValueLabel ?? 'القيمة التقديرية'}</Label>
                            <Input
                              type="text"
                              inputMode="decimal"
                              lang="en"
                              dir="ltr"
                              className={ENGLISH_INPUT_CLASSNAME}
                              placeholder="0.00"
                              {...form.register(`units.${activeUnitIndex}.saleValue` as const)}
                              onInput={handleEnglishDecimalInput}
                              onBlur={handleEnglishDecimalBlur}
                              onFocus={handleSelectInputContent}
                            />
                          </div>
                          <div className="space-y-2 rounded-lg border bg-background p-3">
                            <Label>{t?.directCostLabel ?? 'التكلفة المباشرة'}</Label>
                            <Input
                              type="text"
                              inputMode="decimal"
                              lang="en"
                              dir="ltr"
                              {...form.register(`units.${activeUnitIndex}.directCost` as const)}
                              readOnly
                              className={`${ENGLISH_INPUT_CLASSNAME} bg-muted/60 cursor-not-allowed`}
                              placeholder="0.00"
                              title={t?.directCostAutoCalculatedHint ?? 'هذا الحقل يُحسب تلقائيًا من تفاصيل بنود التكلفة المباشرة بالأسفل.'}
                            />
                          </div>
                        </div>

                        <div className="space-y-2 rounded-lg border bg-background p-3">
                          <Label>{t?.notesLabel ?? 'ملاحظات'}</Label>
                          <Textarea {...form.register(`units.${activeUnitIndex}.notes` as const)} placeholder={t?.notesPlaceholder ?? 'ملاحظات إضافية عن الوحدة'} />
                        </div>
                      </div>

                      {activeUnit?.status === 'sold' && (
                        <div className="rounded-xl border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
                          <div className="font-medium">{t?.soldStatusLabel ?? 'مباع'}</div>
                          <div className="mt-1">
                            {t?.soldUnitPrompt ?? 'عند حفظ هذه الوحدة كمباعة سيتم تحويلك مباشرة إلى تبويب العقود والتحصيل لاستكمال بيانات البيع.'}
                          </div>
                        </div>
                      )}

                      <div className="space-y-3 rounded-xl border bg-muted/20 p-3">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                          <div>
                            <p className="font-medium">{t?.directCostBreakdownTitle ?? 'تفصيل التكلفة المباشرة على مراحل'}</p>
                            <p className="text-xs text-muted-foreground">
                              {t?.directCostBreakdownDescription ?? 'سجّل بنود التكلفة المباشرة لهذه الوحدة فقط، وسيتم جمعها تلقائيًا في الإجمالي.'}
                            </p>
                          </div>
                          <Button type="button" variant="outline" size="sm" onClick={() => addDirectCostEntryToUnit(activeUnitIndex)}>
                            <PlusCircle className="me-2 h-4 w-4" />
                            {t?.addDirectCostEntryButton ?? 'إضافة بند مباشر'}
                          </Button>
                        </div>

                        {activeUnitDirectCostEntries.length === 0 ? (
                          <div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                            {t?.noDirectCostEntries ?? 'لا توجد بنود مباشرة لهذه الوحدة بعد. يمكنك تسجيلها حسب المراحل أو الأجزاء.'}
                          </div>
                        ) : (
                          <div className="grid gap-2">
                            {activeUnitDirectCostEntries.map((entry, entryIndex) => (
                              <div
                                key={String(entry?.id || `${activeUnitIndex}-${entryIndex}`)}
                                className="grid gap-2 md:grid-cols-[120px_1fr_120px_130px_1.4fr_auto] items-start rounded-xl border bg-background p-2"
                              >
                                <div className="rounded-lg border bg-background p-1.5">
                                  <Input
                                    {...form.register(`units.${activeUnitIndex}.directCostEntries.${entryIndex}.phase` as const)}
                                    placeholder={t?.phaseLabel ?? 'المرحلة'}
                                  />
                                </div>
                                <div className="rounded-lg border bg-background p-1.5">
                                  <Input
                                    {...form.register(`units.${activeUnitIndex}.directCostEntries.${entryIndex}.title` as const)}
                                    placeholder={t?.costItemLabel ?? 'البند'}
                                  />
                                </div>
                                <div className="rounded-lg border bg-background p-1.5">
                                  <Input
                                    type="text"
                                    inputMode="decimal"
                                    lang="en"
                                    dir="ltr"
                                    className={ENGLISH_INPUT_CLASSNAME}
                                    placeholder="0.00"
                                    {...form.register(`units.${activeUnitIndex}.directCostEntries.${entryIndex}.amount` as const)}
                                    onInput={handleEnglishDecimalInput}
                                    onBlur={handleEnglishDecimalBlur}
                                    onFocus={handleSelectInputContent}
                                  />
                                </div>
                                <div className="rounded-lg border bg-background p-1.5">
                                  <DateInputWithPicker
                                    value={String(activeUnitDirectCostEntries[entryIndex]?.date || '')}
                                    onChange={(value) => form.setValue(`units.${activeUnitIndex}.directCostEntries.${entryIndex}.date`, value, { shouldDirty: true, shouldTouch: true, shouldValidate: false })}
                                  />
                                </div>
                                <div className="rounded-lg border bg-background p-1.5">
                                  <Input
                                    {...form.register(`units.${activeUnitIndex}.directCostEntries.${entryIndex}.notes` as const)}
                                    placeholder={t?.notesPlaceholder ?? 'ملاحظات'}
                                  />
                                </div>
                                <div className="flex items-center justify-center">
                                  <Button type="button" variant="ghost" size="icon" onClick={() => removeDirectCostEntryFromUnit(activeUnitIndex, entryIndex)}>
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  ) : (
                    <div className="rounded-md border border-dashed p-4 text-sm text-muted-foreground">
                      {t?.noActiveUnitSelected ?? 'اختر وحدة من البطاقات أو أضف وحدة جديدة للبدء.'}
                    </div>
                  )}

                  <DialogFooter>
                    {activeUnitIndex !== null && (
                      <Button type="button" variant="destructive" onClick={() => deleteUnitAndCloseDialog(activeUnitIndex)}>
                        {t?.deleteUnitButton ?? 'حذف الوحدة'}
                      </Button>
                    )}
                    <Button type="button" variant="outline" onClick={handleSaveUnitDialog}>
                      {activeUnit?.status === 'sold'
                        ? (t?.saveAndContinueToContractsButton ?? 'حفظ ومتابعة البيع')
                        : (t?.saveUnitButton ?? 'حفظ')}
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </CardContent>
          </Card>
            </TabsContent>

            <TabsContent value="installments">
          <Card>
            <CardHeader>
              <CardTitle>{t?.contractsCollectionsTitle ?? 'العقود والتحصيل'}</CardTitle>
              <CardDescription>
                {t?.installmentTrackingDescription ?? 'بعد تعريف الوحدات والتكاليف، أدخل هنا بيانات العقد، قيمة البيع الفعلية، المبلغ المحصل، وجدول الأقساط لكل وحدة.'}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {watchedUnits.length === 0 ? (
                <div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                  {t?.noUnitsForInstallments ?? 'أضف الوحدات أولاً من قسم التفاصيل الهندسية للمبنى، ثم أكمل العقود والتحصيل هنا.'}
                </div>
              ) : (
                watchedUnits.map((unit, unitIndex) => {
                  const installmentRows = Array.isArray(unit?.installments) ? unit.installments : [];
                  const contractValue = Math.max(0, Number(unit?.actualSaleValue || unit?.saleValue || 0));
                  const plannedCollected = installmentRows.reduce((sum, installment) => sum + Math.max(0, Number(installment?.paidAmount || 0)), 0);
                  const effectiveCollected = Math.max(Math.max(0, Number(unit?.collectedAmount || 0)), plannedCollected);
                  const outstanding = Math.max(0, contractValue - effectiveCollected);
                  const unitLabel = String(unit?.name || unit?.unitCode || `Unit ${unitIndex + 1}`);
                  const unitStatusLabel = unit?.status === 'sold'
                    ? (t?.soldStatusLabel ?? 'مباع')
                    : unit?.status === 'reserved'
                      ? (t?.reservedStatusLabel ?? 'محجوز')
                      : unit?.status === 'available'
                        ? (t?.availableStatusLabel ?? 'متاح')
                        : (t?.plannedStatusLabel ?? 'مخطط');
                  const unitStatusClassName = unit?.status === 'sold'
                    ? 'bg-emerald-100 text-emerald-700'
                    : unit?.status === 'reserved'
                      ? 'bg-amber-100 text-amber-700'
                      : unit?.status === 'available'
                        ? 'bg-sky-100 text-sky-700'
                        : 'bg-slate-100 text-slate-700';
                  const missingSaleFields = [
                    !String(unit?.buyerName || '').trim() ? (t?.buyerNameLabel ?? 'المشتري') : null,
                    !String(unit?.contractDate || '').trim() ? (t?.contractDateLabel ?? 'تاريخ العقد') : null,
                    Number(unit?.actualSaleValue || 0) <= 0 ? (t?.actualSaleValueLabel ?? 'قيمة العقد') : null,
                  ].filter(Boolean);

                  return (
                    <div
                      key={String(unit?.id || `schedule-${unitIndex}`)}
                      className={`rounded-2xl border bg-card p-4 shadow-sm space-y-4 ${focusedContractUnitIndex === unitIndex ? 'border-primary bg-primary/5 ring-1 ring-primary/20' : ''}`}
                    >
                      <div className="flex flex-wrap items-start justify-between gap-3">
                        <div className="space-y-2">
                          <div className="flex flex-wrap items-center gap-2">
                            <div className="text-base font-semibold">{unitLabel}</div>
                            <span className={`rounded-full px-2.5 py-1 text-[11px] font-medium ${unitStatusClassName}`}>
                              {unitStatusLabel}
                            </span>
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {unit?.buyerName || (t?.buyerNotAssignedLabel ?? 'بدون مشتري محدد')}
                          </div>
                        </div>
                        <Button type="button" variant="outline" size="sm" className="rounded-lg" onClick={() => addInstallmentToUnit(unitIndex)}>
                          <PlusCircle className="me-2 h-4 w-4" />
                          {t?.addInstallmentButton ?? 'إضافة قسط'}
                        </Button>
                      </div>

                      <div className="grid gap-2 md:grid-cols-3">
                        <div className="rounded-xl border bg-muted/30 p-3">
                          <div className="text-[11px] text-muted-foreground">{t?.actualSaleValueLabel ?? 'قيمة العقد'}</div>
                          <div className="mt-1 text-base font-semibold font-mono text-left" dir="ltr">{formatCurrency(contractValue, currencySymbol)}</div>
                        </div>
                        <div className="rounded-xl border bg-emerald-50 p-3">
                          <div className="text-[11px] text-emerald-700">{t?.collectedAmountLabel ?? 'المحصل'}</div>
                          <div className="mt-1 text-base font-semibold font-mono text-left text-emerald-700" dir="ltr">{formatCurrency(effectiveCollected, currencySymbol)}</div>
                        </div>
                        <div className="rounded-xl border bg-amber-50 p-3">
                          <div className="text-[11px] text-amber-700">{t?.outstandingBalanceLabel ?? 'المتبقي للتحصيل'}</div>
                          <div className="mt-1 text-base font-semibold font-mono text-left text-amber-700" dir="ltr">{formatCurrency(outstanding, currencySymbol)}</div>
                        </div>
                      </div>

                      {(focusedContractUnitIndex === unitIndex || (unit?.status === 'sold' && missingSaleFields.length > 0)) && (
                        <div className="rounded-xl border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
                          <div className="font-medium">{t?.contractDataRequiredTitle ?? 'بيانات البيع المطلوبة'}</div>
                          <div className="mt-1">
                            {missingSaleFields.length > 0
                              ? `${t?.completeSaleFieldsHint ?? 'أكمل الآن الحقول التالية:'} ${missingSaleFields.join('، ')}`
                              : (t?.contractDataReadyHint ?? 'هذه الوحدة جاهزة لإدخال الأقساط والتحصيل.')}
                          </div>
                        </div>
                      )}

                      <div className="rounded-2xl border bg-muted/20 p-4">
                        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
                          <div className="space-y-1 rounded-xl border bg-background p-3 xl:col-span-2">
                            <Label className="text-xs text-muted-foreground">{t?.buyerNameLabel ?? 'المشتري'}</Label>
                            <PartySelector
                              value={resolveBuyerCustomerValue(String(unit?.buyerCustomerId || ''))}
                              placeholder={t?.buyerSelectorPlaceholder ?? 'اختر العميل'}
                              searchPlaceholder={t?.searchCustomerPlaceholder ?? 'ابحث عن عميل...'}
                              emptyLabel={t?.noCustomersFound ?? 'لا يوجد عملاء مطابقون'}
                              buttonClassName="h-10 rounded-lg justify-between text-sm"
                              options={buyerCustomerOptions.map((entry) => ({
                                id: entry.selectorId,
                                label: entry.label,
                                description: t?.customerLabel ?? 'عميل',
                                searchableText: `${entry.label} ${entry.phone} ${entry.address}`,
                              }))}
                              onValueChange={(value) => handleBuyerCustomerChange(unitIndex, value)}
                              footerAction={
                                <Button
                                  type="button"
                                  variant="outline"
                                  className="w-full h-10"
                                  onClick={() => {
                                    setBuyerTargetUnitIndex(unitIndex);
                                    setShowAddCustomerDialog(true);
                                  }}
                                >
                                  {t?.addCustomerButton ?? 'إضافة عميل جديد'}
                                </Button>
                              }
                            />
                            <input type="hidden" {...form.register(`units.${unitIndex}.buyerName` as const)} />
                            <input type="hidden" {...form.register(`units.${unitIndex}.buyerCustomerId` as const)} />
                            {(() => {
                              const selectedBuyer = buyerCustomerOptions.find((entry) => entry.originalId === String(unit?.buyerCustomerId || '').trim());
                              if (!selectedBuyer) {
                                return (
                                  <div className="text-[11px] text-muted-foreground">
                                    {t?.buyerLinkHint ?? 'اختر العميل من إدارة العملاء أو أضفه مباشرة من الزر أدناه.'}
                                  </div>
                                );
                              }

                              return (
                                <div className="text-[11px] text-muted-foreground">
                                  {t?.customerLabel ?? 'عميل'}
                                  {selectedBuyer.phone ? ` • ${selectedBuyer.phone}` : ''}
                                  {selectedBuyer.address ? ` • ${selectedBuyer.address}` : ''}
                                </div>
                              );
                            })()}
                          </div>
                          <div className="space-y-1 rounded-xl border bg-background p-3">
                            <Label className="text-xs text-muted-foreground">{t?.contractDateLabel ?? 'تاريخ العقد'}</Label>
                            <DateInputWithPicker
                              value={String(unit?.contractDate || '')}
                              onChange={(value) => form.setValue(`units.${unitIndex}.contractDate`, value, { shouldDirty: true, shouldTouch: true, shouldValidate: false })}
                            />
                          </div>
                          <div className="space-y-1 rounded-xl border bg-background p-3">
                            <Label className="text-xs text-muted-foreground">{t?.handoverDateLabel ?? 'تاريخ التسليم'}</Label>
                            <DateInputWithPicker
                              value={String(unit?.handoverDate || '')}
                              onChange={(value) => form.setValue(`units.${unitIndex}.handoverDate`, value, { shouldDirty: true, shouldTouch: true, shouldValidate: false })}
                            />
                          </div>
                          <div className="space-y-1 rounded-xl border bg-background p-3">
                            <Label className="text-xs text-muted-foreground">{t?.actualSaleValueLabel ?? 'قيمة العقد'}</Label>
                            <Input
                              type="text"
                              inputMode="decimal"
                              lang="en"
                              dir="ltr"
                              className={ENGLISH_INPUT_CLASSNAME}
                              placeholder="0.00"
                              {...form.register(`units.${unitIndex}.actualSaleValue` as const)}
                              onInput={handleEnglishDecimalInput}
                              onBlur={handleEnglishDecimalBlur}
                              onFocus={handleSelectInputContent}
                            />
                          </div>
                          <div className="space-y-1 rounded-xl border bg-background p-3 xl:col-start-5">
                            <Label className="text-xs text-muted-foreground">{t?.collectedAmountLabel ?? 'المحصل'}</Label>
                            <Input
                              type="text"
                              inputMode="decimal"
                              lang="en"
                              dir="ltr"
                              className={ENGLISH_INPUT_CLASSNAME}
                              placeholder="0.00"
                              {...form.register(`units.${unitIndex}.collectedAmount` as const)}
                              onInput={handleEnglishDecimalInput}
                              onBlur={handleEnglishDecimalBlur}
                              onFocus={handleSelectInputContent}
                            />
                          </div>
                        </div>
                      </div>

                      {installmentRows.length === 0 ? (
                        <div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                          {t?.noInstallmentsForUnit ?? 'لا توجد أقساط مجدولة لهذه الوحدة بعد.'}
                        </div>
                      ) : (
                        <div className="grid gap-2">
                          {installmentRows.map((installment, installmentIndex) => (
                            <div
                              key={String(installment?.id || `${unitIndex}-${installmentIndex}`)}
                              className="grid gap-2 md:grid-cols-[1.1fr_130px_110px_110px_130px_1.4fr_auto] items-start rounded-xl border bg-muted/20 p-2"
                            >
                              <div className="rounded-lg border bg-background p-1.5">
                                <Input {...form.register(`units.${unitIndex}.installments.${installmentIndex}.title` as const)} placeholder={t?.installmentTitlePlaceholder ?? 'الدفعة الأولى'} />
                              </div>
                              <div className="rounded-lg border bg-background p-1.5">
                                <DateInputWithPicker
                                  value={String(installment?.dueDate || '')}
                                  onChange={(value) => form.setValue(`units.${unitIndex}.installments.${installmentIndex}.dueDate`, value, { shouldDirty: true, shouldTouch: true, shouldValidate: false })}
                                />
                              </div>
                              <div className="rounded-lg border bg-background p-1.5">
                                <Input
                                  type="text"
                                  inputMode="decimal"
                                  lang="en"
                                  dir="ltr"
                                  className={ENGLISH_INPUT_CLASSNAME}
                                  placeholder="0.00"
                                  {...form.register(`units.${unitIndex}.installments.${installmentIndex}.amount` as const)}
                                  onInput={handleEnglishDecimalInput}
                                  onBlur={handleEnglishDecimalBlur}
                                  onFocus={handleSelectInputContent}
                                />
                              </div>
                              <div className="rounded-lg border bg-background p-1.5">
                                <Input
                                  type="text"
                                  inputMode="decimal"
                                  lang="en"
                                  dir="ltr"
                                  className={ENGLISH_INPUT_CLASSNAME}
                                  placeholder="0.00"
                                  {...form.register(`units.${unitIndex}.installments.${installmentIndex}.paidAmount` as const)}
                                  onInput={handleEnglishDecimalInput}
                                  onBlur={handleEnglishDecimalBlur}
                                  onFocus={handleSelectInputContent}
                                />
                              </div>
                              <div className="rounded-lg border bg-background p-1.5">
                                <select
                                  {...form.register(`units.${unitIndex}.installments.${installmentIndex}.status` as const)}
                                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
                                >
                                  <option value="pending">{t?.pendingStatusLabel ?? 'مجدول'}</option>
                                  <option value="partially-paid">{t?.partialPaymentStatusLabel ?? 'مدفوع جزئياً'}</option>
                                  <option value="paid">{t?.paidStatusLabel ?? 'مدفوع'}</option>
                                  <option value="overdue">{t?.overdueStatusLabel ?? 'متأخر'}</option>
                                </select>
                              </div>
                              <div className="rounded-lg border bg-background p-1.5">
                                <Input {...form.register(`units.${unitIndex}.installments.${installmentIndex}.notes` as const)} placeholder={t?.notesPlaceholder ?? 'ملاحظات'} />
                              </div>
                              <div className="flex items-center justify-center">
                                <Button type="button" variant="ghost" size="icon" onClick={() => removeInstallmentFromUnit(unitIndex, installmentIndex)}>
                                  <Trash2 className="h-4 w-4 text-destructive" />
                                </Button>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}

                      <div className="text-xs text-muted-foreground">
                        {(t?.outstandingBalanceLabel ?? 'المتبقي للتحصيل')}: {formatCurrency(outstanding, currencySymbol)}
                      </div>
                    </div>
                  );
                })
              )}
            </CardContent>
          </Card>
            </TabsContent>

            <TabsContent value="shared-costs">
          <Card>
            <CardHeader>
              <CardTitle>{t?.sharedCostsTitle ?? 'التكاليف المشتركة'}</CardTitle>
              <CardDescription>
                {t?.sharedCostsDescription ?? 'اربط البنود العامة من فواتير المشتريات بالمشروع أو بالطوابق، واستخدم هذا القسم لمراجعة طريقة توزيعها على الوحدات.'}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="rounded-xl border bg-amber-50/60 p-3">
                <div className="space-y-3">
                  <div>
                    <p className="font-medium">{t?.sharedPurchaseAllocationTitle ?? 'إعداد توزيع مشتريات المبنى كاملًا'}</p>
                    <p className="text-xs text-muted-foreground">
                      {t?.sharedPurchaseAllocationDescription ?? 'عند ربط فاتورة المشتريات بخيار "المبنى كاملًا" فإنها تُعامل كمصروف مشترك، ويتم توزيعها هنا حسب الطريقة الافتراضية للمشروع.'}
                    </p>
                  </div>

                  <div className="grid gap-3 lg:grid-cols-[220px_1fr]">
                    <div className="rounded-lg border bg-background p-2">
                      <Label className="mb-1 block text-xs text-muted-foreground">{t?.allocationMethodLabel ?? 'أساس التوزيع'}</Label>
                      <select
                        {...form.register('sharedCostAllocationMethod')}
                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
                      >
                        <option value="area">{t?.allocateByAreaLabel ?? 'حسب المساحة'}</option>
                        <option value="sale-value">{t?.allocateBySaleValueLabel ?? 'حسب القيمة البيعية'}</option>
                        <option value="manual-share">{t?.allocateByManualShareLabel ?? 'حسب النسبة اليدوية'}</option>
                      </select>
                    </div>

                    <div className="rounded-lg border bg-background p-2">
                      {watchedProjectSharedAllocationMethod === 'manual-share' ? (
                        watchedUnits.length === 0 ? (
                          <div className="text-xs text-muted-foreground">{t?.addUnitsFirstHint ?? 'أضف الوحدات أولاً لإدخال نسب التوزيع.'}</div>
                        ) : (
                          <div className="grid gap-2">
                            {watchedUnits.map((unit, unitIndex) => {
                              const unitId = String(unit?.id || `unit-${unitIndex + 1}`);
                              const currentValue = Number(
                                watchedProjectSharedUnitAllocations.find((entry) => String(entry.unitId || '') === unitId)?.percentage || 0,
                              );
                              return (
                                <div key={`project-shared-${unitId}`} className="grid grid-cols-[1fr_90px] items-center gap-2">
                                  <span className="text-xs text-muted-foreground">{String(unit?.name || unit?.unitCode || `Unit ${unitIndex + 1}`)}</span>
                                  <Input
                                    type="text"
                                    inputMode="decimal"
                                    lang="en"
                                    dir="ltr"
                                    className={ENGLISH_INPUT_CLASSNAME}
                                    placeholder="0.00"
                                    value={currentValue === 0 ? '' : String(currentValue)}
                                    onInput={handleEnglishDecimalInput}
                                    onFocus={handleSelectInputContent}
                                    onBlur={(event) => {
                                      handleEnglishDecimalBlur(event);
                                      updateProjectSharedAllocation(unitId, event.currentTarget.value);
                                    }}
                                    onChange={(event) => updateProjectSharedAllocation(unitId, sanitizeDecimalValue(event.target.value))}
                                  />
                                </div>
                              );
                            })}
                          </div>
                        )
                      ) : (
                        <span className="text-xs text-muted-foreground">
                          {watchedProjectSharedAllocationMethod === 'sale-value'
                            ? (t?.saleValueDistributionHint ?? 'سيتم توزيع مشتريات المبنى كاملًا تلقائيًا حسب القيمة البيعية التقديرية لكل وحدة، لذا أكمل هذا الحقل داخل التفاصيل الهندسية للمشروع.')
                            : (t?.areaDistributionHint ?? 'سيتم توزيع مشتريات المبنى كاملًا تلقائيًا حسب مساحة كل وحدة، اعتمادًا على حقل المساحة (م²) داخل التفاصيل الهندسية للمشروع.')}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              <div className="flex justify-end">
                <Button type="button" variant="outline" size="sm" onClick={() => appendSharedCost(createEmptySharedCost())}>
                  <PlusCircle className="me-2 h-4 w-4" />
                  {t?.addSharedCostButton ?? 'إضافة تكلفة مشتركة'}
                </Button>
              </div>

              <div className="rounded-xl border bg-muted/20 p-3">
                <div className="rounded-md border overflow-hidden bg-background">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t?.costItemLabel ?? 'البند'}</TableHead>
                      <TableHead>{t?.categoryLabel ?? 'الفئة'}</TableHead>
                      <TableHead>{t?.amountLabel ?? 'المبلغ'}</TableHead>
                      <TableHead>{t?.allocationMethodLabel ?? 'أساس التوزيع'}</TableHead>
                      <TableHead>{t?.allocationDetailsLabel ?? 'تفاصيل التوزيع'}</TableHead>
                      <TableHead>{t?.notesLabel ?? 'ملاحظات'}</TableHead>
                      <TableHead className="w-[60px]" />
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sharedCostFields.map((field, index) => {
                      const currentMethod = String(watchedSharedCosts[index]?.allocationMethod || 'area');
                      const currentAllocations = Array.isArray(watchedSharedCosts[index]?.unitAllocations)
                        ? watchedSharedCosts[index]?.unitAllocations || []
                        : [];

                      return (
                        <TableRow key={field.id}>
                          <TableCell><div className="rounded-lg border bg-background p-1.5"><Input {...form.register(`sharedCosts.${index}.title` as const)} placeholder={t?.sharedCostTitlePlaceholder ?? 'المصعد'} /></div></TableCell>
                          <TableCell><div className="rounded-lg border bg-background p-1.5"><Input {...form.register(`sharedCosts.${index}.category` as const)} placeholder={t?.categoryPlaceholder ?? 'الخدمات المشتركة'} /></div></TableCell>
                          <TableCell><div className="rounded-lg border bg-background p-1.5"><Input type="text" inputMode="decimal" lang="en" dir="ltr" className={ENGLISH_INPUT_CLASSNAME} placeholder="0.00" {...form.register(`sharedCosts.${index}.amount` as const)} onInput={handleEnglishDecimalInput} onBlur={handleEnglishDecimalBlur} onFocus={handleSelectInputContent} /></div></TableCell>
                          <TableCell>
                            <div className="rounded-lg border bg-background p-1.5">
                            <select
                              {...form.register(`sharedCosts.${index}.allocationMethod` as const)}
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
                            >
                              <option value="area">{t?.allocateByAreaLabel ?? 'حسب المساحة'}</option>
                              <option value="sale-value">{t?.allocateBySaleValueLabel ?? 'حسب القيمة البيعية'}</option>
                              <option value="manual-share">{t?.allocateByManualShareLabel ?? 'حسب النسبة اليدوية'}</option>
                            </select>
                            </div>
                          </TableCell>
                          <TableCell className="min-w-[240px]">
                            {currentMethod === 'manual-share' ? (
                              <div className="grid gap-2">
                                {watchedUnits.length === 0 ? (
                                  <div className="text-xs text-muted-foreground">{t?.addUnitsFirstHint ?? 'أضف الوحدات أولاً لإدخال نسب التوزيع.'}</div>
                                ) : (
                                  watchedUnits.map((unit, unitIndex) => {
                                    const unitId = String(unit?.id || `unit-${unitIndex + 1}`);
                                    const currentValue = Number(
                                      currentAllocations.find((entry) => String(entry.unitId || '') === unitId)?.percentage || 0,
                                    );
                                    return (
                                      <div key={`${field.id}-${unitId}`} className="grid grid-cols-[1fr_90px] items-center gap-2">
                                        <span className="text-xs text-muted-foreground">{String(unit?.name || unit?.unitCode || `Unit ${unitIndex + 1}`)}</span>
                                        <Input
                                          type="text"
                                          inputMode="decimal"
                                          lang="en"
                                          dir="ltr"
                                          className={ENGLISH_INPUT_CLASSNAME}
                                          placeholder="0.00"
                                          value={currentValue === 0 ? '' : String(currentValue)}
                                          onInput={handleEnglishDecimalInput}
                                          onFocus={handleSelectInputContent}
                                          onBlur={(event) => {
                                            handleEnglishDecimalBlur(event);
                                            updateManualShare(index, unitId, event.currentTarget.value);
                                          }}
                                          onChange={(event) => updateManualShare(index, unitId, sanitizeDecimalValue(event.target.value))}
                                        />
                                      </div>
                                    );
                                  })
                                )}
                              </div>
                            ) : (
                              <span className="text-xs text-muted-foreground">
                                {currentMethod === 'sale-value'
                                  ? (t?.saleValueDistributionHint ?? 'سيتم التوزيع تلقائياً حسب القيمة البيعية لكل وحدة.')
                                  : (t?.areaDistributionHint ?? 'سيتم التوزيع تلقائياً حسب مساحة كل وحدة.')}
                              </span>
                            )}
                          </TableCell>
                          <TableCell><div className="rounded-lg border bg-background p-1.5"><Input {...form.register(`sharedCosts.${index}.notes` as const)} placeholder={t?.notesPlaceholder ?? 'ملاحظات'} /></div></TableCell>
                          <TableCell>
                            <Button type="button" variant="ghost" size="icon" onClick={() => removeSharedCost(index)} disabled={sharedCostFields.length === 1}>
                              <Trash2 className="h-4 w-4 text-destructive" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
                </div>
              </div>
            </CardContent>
          </Card>
            </TabsContent>

            <TabsContent value="summary">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Calculator className="h-5 w-5" />
                {t?.allocationSummaryTitle ?? 'ملخص التوزيع والتكلفة النهائية'}
              </CardTitle>
              <CardDescription>
                {t?.allocationSummaryDescription ?? 'التكلفة النهائية لكل شقة = التكاليف المرتبطة بها من المشتريات + حصتها من التكاليف المشتركة.'}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Tabs defaultValue="analysis" className="space-y-4">
                <div className="overflow-x-auto">
                  <TabsList className="h-auto flex-wrap justify-start">
                    <TabsTrigger value="analysis" className="text-xs sm:text-sm">{t?.allocationSummaryTitle ?? 'تحليل التكلفة'}</TabsTrigger>
                    <TabsTrigger value="accounting" className="text-xs sm:text-sm">{t?.accountingLinkTitle ?? 'المحاسبة'}</TabsTrigger>
                    <TabsTrigger value="links" className="text-xs sm:text-sm">{t?.linkedCatalogItemsTitle ?? 'العناصر المرتبطة'}</TabsTrigger>
                  </TabsList>
                </div>

                <TabsContent value="analysis" className="space-y-4">
              <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.totalAreaLabel ?? 'إجمالي المساحة'}</div>
                  <div className="mt-1 text-lg font-semibold">{liveMetrics.totalArea.toFixed(2)} m²</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.totalDirectCostLabel ?? 'إجمالي التكاليف المباشرة'}</div>
                  <div className="mt-1 text-lg font-semibold">{formatCurrency(liveMetrics.totalDirectCost, currencySymbol)}</div>
                  <div className="mt-1 text-[11px] text-muted-foreground">{t?.linkedDirectPurchaseCostHint ?? 'يشمل المشتريات المرتبطة بالطوابق والأجزاء.'}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.totalSharedCostLabel ?? 'إجمالي التكاليف المشتركة'}</div>
                  <div className="mt-1 text-lg font-semibold">{formatCurrency(liveMetrics.totalSharedCost, currencySymbol)}</div>
                  <div className="mt-1 text-[11px] text-muted-foreground">{t?.linkedSharedPurchaseCostHint ?? 'يشمل المشتريات المرتبطة بالمبنى كاملًا.'}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.linkedPurchaseCostsLabel ?? 'إجمالي المشتريات المرتبطة'}</div>
                  <div className="mt-1 text-lg font-semibold text-sky-700">{formatCurrency(liveMetrics.totalLinkedPurchaseCost, currencySymbol)}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.projectMarginLabel ?? 'هامش المشروع المتوقع'}</div>
                  <div className={`mt-1 text-lg font-semibold ${liveMetrics.projectMargin >= 0 ? 'text-emerald-600' : 'text-destructive'}`}>
                    {formatCurrency(liveMetrics.projectMargin, currencySymbol)}
                  </div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.soldUnitsCountLabel ?? 'الوحدات المباعة'}</div>
                  <div className="mt-1 text-lg font-semibold">{liveMetrics.soldUnitsCount}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.contractedRevenueLabel ?? 'إجمالي العقود'}</div>
                  <div className="mt-1 text-lg font-semibold">{formatCurrency(liveMetrics.totalContractedRevenue, currencySymbol)}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.collectedAmountLabel ?? 'إجمالي المحصل'}</div>
                  <div className="mt-1 text-lg font-semibold text-emerald-600">{formatCurrency(liveMetrics.totalCollectedAmount, currencySymbol)}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.outstandingBalanceLabel ?? 'المتبقي للتحصيل'}</div>
                  <div className="mt-1 text-lg font-semibold text-amber-600">{formatCurrency(liveMetrics.totalOutstandingAmount, currencySymbol)}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.collectionRateLabel ?? 'نسبة التحصيل'}</div>
                  <div className="mt-1 text-lg font-semibold">{liveMetrics.collectionRate.toFixed(1)}%</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.scheduledInstallmentsLabel ?? 'إجمالي الأقساط المجدولة'}</div>
                  <div className="mt-1 text-lg font-semibold">{formatCurrency(liveMetrics.totalScheduledInstallments, currencySymbol)}</div>
                </div>
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="text-muted-foreground">{t?.overdueInstallmentsLabel ?? 'الأقساط المتأخرة'}</div>
                  <div className={`mt-1 text-lg font-semibold ${liveMetrics.overdueInstallmentsCount > 0 ? 'text-destructive' : ''}`}>{liveMetrics.overdueInstallmentsCount}</div>
                </div>
              </div>

              {liveMetrics.manualAllocationWarnings.length > 0 && (
                <div className="rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
                  {liveMetrics.manualAllocationWarnings.map((warning) => (
                    <div key={warning.title}>
                      {warning.title}: {t?.manualAllocationWarning ?? 'مجموع نسب التوزيع الحالية لا يساوي 100%'} ({warning.totalPercentage.toFixed(2)}%)
                    </div>
                  ))}
                </div>
              )}

              {liveMetrics.linkedPurchaseEntries.length > 0 && (
                <div className="space-y-3 rounded-md border bg-background p-3">
                  <div className="flex flex-wrap items-start justify-between gap-2">
                    <div>
                      <p className="font-medium">{t?.linkedPurchaseCostsTitle ?? 'المشتريات المرتبطة بالمشروع'}</p>
                      <p className="text-xs text-muted-foreground">
                        {t?.linkedPurchaseCostsDescription ?? 'هذه الفواتير مرتبطة مباشرة بالمبنى أو بالطوابق/الأجزاء، وتم احتسابها داخل ملخص التكلفة أعلاه.'}
                      </p>
                    </div>
                    <div className="rounded-full border bg-muted/30 px-3 py-1 text-sm font-semibold text-sky-700">
                      {formatCurrency(liveMetrics.totalLinkedPurchaseCost, currencySymbol)}
                    </div>
                  </div>

                  <div className="rounded-md border overflow-hidden">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>{t?.purchaseInvoiceLabel ?? 'الفاتورة'}</TableHead>
                          <TableHead>{t?.supplierLabel ?? 'المورد'}</TableHead>
                          <TableHead>{t?.scopeLabel ?? 'النطاق'}</TableHead>
                          <TableHead>{t?.allocationMethodLabel ?? 'أساس التوزيع'}</TableHead>
                          <TableHead>{t?.detailsLabel ?? 'التفصيل'}</TableHead>
                          <TableHead>{t?.amountLabel ?? 'المبلغ'}</TableHead>
                          <TableHead>{t?.statusLabel ?? 'الحالة'}</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {liveMetrics.linkedPurchaseEntries.map((entry) => (
                          <TableRow key={`${entry.orderId}-${entry.scope}-${entry.sourceLabel}-${entry.amount}`}>
                            <TableCell>{entry.orderNumber || '-'}</TableCell>
                            <TableCell>{entry.supplierName || '-'}</TableCell>
                            <TableCell>
                              {entry.scope === 'project'
                                ? (t?.fullBuildingOption ?? 'المبنى كاملًا')
                                : entry.scope === 'floor'
                                  ? (t?.singleFloorOption ?? 'طابق محدد')
                                  : (t?.floorPartOption ?? 'جزء من طابق')}
                            </TableCell>
                            <TableCell>
                              {entry.scope === 'project'
                                ? (entry.allocationMethod === 'sale-value'
                                  ? (t?.allocateBySaleValueLabel ?? 'حسب القيمة البيعية')
                                  : entry.allocationMethod === 'manual-share'
                                    ? (t?.allocateByManualShareLabel ?? 'حسب النسبة اليدوية')
                                    : (t?.allocateByAreaLabel ?? 'حسب المساحة'))
                                : '—'}
                            </TableCell>
                            <TableCell>{[entry.floorLabel, entry.partLabel, entry.sourceLabel].filter(Boolean).join(' — ') || '-'}</TableCell>
                            <TableCell>{formatCurrency(entry.amount, currencySymbol)}</TableCell>
                            <TableCell>{entry.postingStatus === 'posted' ? (t?.postingPostedLabel ?? 'مرحل') : (t?.postingSavedLabel ?? 'محفوظ')}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              )}

              {liveMetrics.dueAlerts.length > 0 && (
                <div className="rounded-md border border-rose-300 bg-rose-50 p-3 text-sm text-rose-900">
                  <div className="font-medium">{t?.installmentAlertsTitle ?? 'تنبيهات الأقساط المستحقة'}</div>
                  <div className="mt-2 space-y-1">
                    {liveMetrics.dueAlerts.slice(0, 8).map((alert) => (
                      <div key={`${alert.unitName}-${alert.dueDate}-${alert.title}`}>
                        {alert.unitName} — {alert.title} — {alert.buyerName} — {alert.dueDate || '-'} — {formatCurrency(alert.remaining, currencySymbol)}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className="rounded-md border overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t?.unitNameLabel ?? 'الوحدة'}</TableHead>
                      <TableHead>{t?.buyerNameLabel ?? 'المشتري'}</TableHead>
                      <TableHead>{t?.areaLabel ?? 'المساحة'}</TableHead>
                      <TableHead>{t?.directCostLabel ?? 'التكلفة المباشرة'}</TableHead>
                      <TableHead>{t?.sharedCostsTitle ?? 'حصة التكاليف المشتركة'}</TableHead>
                      <TableHead>{t?.totalCostLabel ?? 'إجمالي التكلفة'}</TableHead>
                      <TableHead>{t?.costPerSqmLabel ?? 'تكلفة المتر'}</TableHead>
                      <TableHead>{t?.actualSaleValueLabel ?? 'قيمة العقد'}</TableHead>
                      <TableHead>{t?.collectedAmountLabel ?? 'المحصل'}</TableHead>
                      <TableHead>{t?.outstandingBalanceLabel ?? 'المتبقي'}</TableHead>
                      <TableHead>{t?.collectionRateLabel ?? 'التحصيل %'}</TableHead>
                      <TableHead>{t?.profitLabel ?? 'الربحية'}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {liveMetrics.unitSummaries.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={12} className="h-20 text-center text-muted-foreground">
                          {t?.noUnitsSummary ?? 'أضف وحدة واحدة على الأقل لعرض احتساب التكلفة.'}
                        </TableCell>
                      </TableRow>
                    ) : (
                      liveMetrics.unitSummaries.map((unit) => (
                        <TableRow key={unit.id}>
                          <TableCell>{unit.name || unit.unitCode || '-'}</TableCell>
                          <TableCell>{unit.buyerName || '-'}</TableCell>
                          <TableCell>{unit.area.toFixed(2)} m²</TableCell>
                          <TableCell>
                            <div>{formatCurrency(unit.directCost, currencySymbol)}</div>
                            {unit.linkedPurchaseDirectCost > 0 && (
                              <div className="text-[11px] text-muted-foreground">
                                {t?.linkedPurchaseShortLabel ?? 'من المشتريات'}: {formatCurrency(unit.linkedPurchaseDirectCost, currencySymbol)}
                              </div>
                            )}
                          </TableCell>
                          <TableCell>
                            <div>{formatCurrency(unit.allocatedSharedCost, currencySymbol)}</div>
                            {unit.linkedPurchaseSharedCost > 0 && (
                              <div className="text-[11px] text-muted-foreground">
                                {t?.linkedProjectScopeLabel ?? 'ربط على مستوى المبنى'}: {formatCurrency(unit.linkedPurchaseSharedCost, currencySymbol)}
                              </div>
                            )}
                          </TableCell>
                          <TableCell>{formatCurrency(unit.totalCost, currencySymbol)}</TableCell>
                          <TableCell>{formatCurrency(unit.costPerSqm, currencySymbol)}</TableCell>
                          <TableCell>{formatCurrency(unit.revenueValue, currencySymbol)}</TableCell>
                          <TableCell className="text-emerald-600">{formatCurrency(unit.collectedAmount, currencySymbol)}</TableCell>
                          <TableCell className="text-amber-600">{formatCurrency(unit.outstandingAmount, currencySymbol)}</TableCell>
                          <TableCell>{unit.collectionRate.toFixed(1)}%</TableCell>
                          <TableCell className={unit.margin >= 0 ? 'text-emerald-600' : 'text-destructive'}>{formatCurrency(unit.margin, currencySymbol)}</TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>

                </TabsContent>

                <TabsContent value="accounting" className="space-y-4">
              <div className="space-y-3 rounded-md border p-3">
                <div>
                  <p className="font-medium">{t?.accountingLinkTitle ?? 'الربط المحاسبي الداخلي'}</p>
                  <p className="text-xs text-muted-foreground">
                    {t?.realEstateAccountingHint ?? 'هذا الموديول مرتبط بشجرة الحسابات الداخلية للتطبيق، ويتم إنشاء الحسابات اللازمة تلقائياً عند عدم وجودها.'}
                  </p>
                </div>
                <div className="grid gap-2 md:grid-cols-2 xl:grid-cols-3 text-sm">
                  <div><span className="font-medium">{t?.projectAccountLabel ?? 'حساب المشروع'}:</span> <span className="font-mono">{activeAccountingSetup?.projectAccountCode || '-'}</span></div>
                  <div><span className="font-medium">{t?.directCostLabel ?? 'التكاليف المباشرة'}:</span> <span className="font-mono">{activeAccountingSetup?.directCostAccountCode || '-'}</span></div>
                  <div><span className="font-medium">{t?.sharedCostsTitle ?? 'التكاليف المشتركة'}:</span> <span className="font-mono">{activeAccountingSetup?.sharedCostAccountCode || '-'}</span></div>
                  <div><span className="font-medium">{t?.salesRevenueLabel ?? 'إيراد بيع الوحدات'}:</span> <span className="font-mono">{activeAccountingSetup?.salesRevenueAccountCode || '-'}</span></div>
                  <div><span className="font-medium">{t?.costOfSalesLabel ?? 'تكلفة الوحدات المباعة'}:</span> <span className="font-mono">{activeAccountingSetup?.costOfSalesAccountCode || '-'}</span></div>
                  <div><span className="font-medium">{t?.projectsRootAccountLabel ?? 'جذر حساب المشاريع'}:</span> <span className="font-mono">{activeAccountingSetup?.projectsRootAccountCode || '-'}</span></div>
                </div>
              </div>

              <div className="space-y-3 rounded-md border p-3">
                <div>
                  <p className="font-medium">{t?.realEstatePostingTitle ?? 'ترحيل تكلفة فعلية للمشروع'}</p>
                  <p className="text-xs text-muted-foreground">
                    {t?.realEstatePostingDescription ?? 'يمكنك هنا إنشاء قيد فعلي للمصاريف أو البنود المرتبطة بالمشروع، ليظهر مباشرة في القيود اليومية وعلى حساب المشروع.'}
                  </p>
                </div>
                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
                  <div className="space-y-2">
                    <Label>{t?.dateLabel ?? 'التاريخ'}</Label>
                    <DateInputWithPicker value={postingDate} onChange={setPostingDate} />
                  </div>
                  <div className="space-y-2 xl:col-span-2">
                    <Label>{t?.costItemLabel ?? 'البند'}</Label>
                    <Select value={postingItemId || 'none'} onValueChange={(value) => setPostingItemId(value === 'none' ? '' : value)}>
                      <SelectTrigger>
                        <SelectValue placeholder={t?.selectItemPlaceholder ?? 'اختر مادة أو مصروفاً'} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">{t?.itemGroupNone ?? 'بدون تحديد'}</SelectItem>
                        {linkedCatalogItems.map((entry) => (
                          <SelectItem key={`${entry.itemType}-${entry.id}`} value={entry.id}>
                            {entry.name} — {entry.itemType === 'material' ? (t?.manageMaterials ?? 'مادة') : (t?.manageExpenses ?? 'مصروف')}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>{t?.amountLabel ?? 'المبلغ'}</Label>
                    <Input
                      type="text"
                      inputMode="decimal"
                      lang="en"
                      dir="ltr"
                      className={ENGLISH_INPUT_CLASSNAME}
                      placeholder="0.00"
                      value={postingAmount}
                      onInput={handleEnglishDecimalInput}
                      onFocus={handleSelectInputContent}
                      onBlur={(event) => {
                        handleEnglishDecimalBlur(event);
                        setPostingAmount(event.currentTarget.value);
                      }}
                      onChange={(event) => setPostingAmount(sanitizeDecimalValue(event.target.value))}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t?.paymentMethodLabel ?? 'حساب المقابل'}</Label>
                    <Select value={postingPaymentSource} onValueChange={(value: 'cash' | 'bank' | 'payable') => setPostingPaymentSource(value)}>
                      <SelectTrigger>
                        <SelectValue placeholder={t?.paymentMethodLabel ?? 'حساب المقابل'} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="cash">{t?.cashLabel ?? 'الصندوق'}</SelectItem>
                        <SelectItem value="bank">{t?.bankLabel ?? 'البنك'}</SelectItem>
                        <SelectItem value="payable">{t?.payableLabel ?? 'مصروفات مستحقة'}</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]">
                  <div className="space-y-2">
                    <Label>{t?.notesLabel ?? 'ملاحظات'}</Label>
                    <Textarea value={postingNote} onChange={(event) => setPostingNote(event.target.value)} placeholder={t?.realEstatePostingNotePlaceholder ?? 'مثال: دفعة تشطيب، أجور مصعد، أو تكلفة تأسيس مشتركة'} />
                  </div>
                  <div className="flex items-end">
                    <Button type="button" onClick={handlePostAccountingEntry} disabled={isPending || !selectedProject}>
                      {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                      {t?.postAccountingEntryButton ?? 'ترحيل القيد'}
                    </Button>
                  </div>
                </div>
              </div>

              <div className="space-y-3 rounded-md border p-3">
                <div>
                  <p className="font-medium">{t?.projectAccountingEntriesTitle ?? 'آخر القيود المحاسبية للمشروع'}</p>
                  <p className="text-xs text-muted-foreground">
                    {t?.projectAccountingEntriesDescription ?? 'يعرض هذا الجدول آخر القيود التي أثّرت على حساب المشروع العقاري أو الحسابات المرتبطة به.'}
                  </p>
                </div>
                <div className="rounded-md border overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.dateLabel ?? 'التاريخ'}</TableHead>
                        <TableHead>{t?.detailsLabel ?? 'الوصف'}</TableHead>
                        <TableHead>{t?.referenceLabel ?? 'المرجع'}</TableHead>
                        <TableHead>{t?.debitLabel ?? 'مدين'}</TableHead>
                        <TableHead>{t?.creditLabel ?? 'دائن'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {projectJournalEntries.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={5} className="h-16 text-center text-muted-foreground">
                            {t?.noProjectAccountingEntries ?? 'لا توجد قيود محاسبية مرتبطة بهذا المشروع حتى الآن.'}
                          </TableCell>
                        </TableRow>
                      ) : (
                        projectJournalEntries.map((entry) => (
                          <TableRow key={entry.id}>
                            <TableCell>{formatDateDDMMYYYY(entry.date)}</TableCell>
                            <TableCell>{entry.description}</TableCell>
                            <TableCell>{entry.referenceType} / {entry.referenceId}</TableCell>
                            <TableCell>{formatCurrency(entry.relevantDebit || 0, currencySymbol)}</TableCell>
                            <TableCell>{formatCurrency(entry.relevantCredit || 0, currencySymbol)}</TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </div>

                </TabsContent>

                <TabsContent value="links" className="space-y-4">
              <div className="space-y-3 rounded-md border p-3">
                <div>
                  <p className="font-medium">{t?.linkedCatalogItemsTitle ?? 'المواد والمصاريف المرتبطة افتراضياً بالمشروع'}</p>
                  <p className="text-xs text-muted-foreground">
                    {t?.linkedCatalogItemsDescription ?? 'هذه العناصر تُستخدم كربط افتراضي عند تسجيل مواد أو مصاريف تخص هذا المشروع، بينما الترحيل المالي الفعلي يكون من حركات الشراء والمصاريف.'}
                  </p>
                </div>
                <div className="rounded-md border overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.typeLabel ?? 'النوع'}</TableHead>
                        <TableHead>{t?.itemNameLabel ?? 'الاسم'}</TableHead>
                        <TableHead>{t?.itemNumberLabel ?? 'الرمز'}</TableHead>
                        <TableHead>{t?.costTypeLabel ?? 'نوع التحميل'}</TableHead>
                        <TableHead>{t?.unitNameLabel ?? 'الوحدة'}</TableHead>
                        <TableHead>{t?.purchaseCostLabel ?? 'تكلفة الشراء'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {linkedCatalogItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={6} className="h-16 text-center text-muted-foreground">
                            {t?.noLinkedCatalogItems ?? 'لا توجد مواد أو مصاريف مرتبطة بهذا المشروع حتى الآن.'}
                          </TableCell>
                        </TableRow>
                      ) : (
                        linkedCatalogItems.map((entry) => (
                          <TableRow key={`${entry.itemType}-${entry.id}`}>
                            <TableCell>{entry.itemType === 'material' ? (t?.manageMaterials ?? 'مادة') : (t?.manageExpenses ?? 'مصروف')}</TableCell>
                            <TableCell>{entry.name}</TableCell>
                            <TableCell>{entry.itemNumber || '-'}</TableCell>
                            <TableCell>{entry.costType === 'direct-unit' ? (t?.directCostLabel ?? 'تكلفة مباشرة') : entry.costType === 'shared-project' ? (t?.sharedCostsTitle ?? 'تكلفة مشتركة') : (t?.generalLabel ?? 'عام')}</TableCell>
                            <TableCell>{entry.unitName || '-'}</TableCell>
                            <TableCell>{typeof entry.purchasePrice === 'number' ? formatCurrency(entry.purchasePrice, currencySymbol) : '-'}</TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </div>

                </TabsContent>
              </Tabs>

              <div className="flex flex-wrap gap-2">
                <Button type="submit" disabled={isPending}>
                  {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                  {t?.saveProjectButton ?? 'حفظ المشروع'}
                </Button>
                <Button type="button" variant="outline" disabled={isPending} onClick={handleDeleteCurrent}>
                  {t?.deleteProjectButton ?? 'حذف المشروع'}
                </Button>
              </div>
            </CardContent>
          </Card>
            </TabsContent>
          </Tabs>
          </div>

          <AddCustomerDialog
            open={showAddCustomerDialog}
            onOpenChange={setShowAddCustomerDialog}
            t={t}
            onCustomerAdded={(customer) => {
              setCustomerList((prev) => [customer, ...prev.filter((entry) => entry.id !== customer.id)]);
              if (buyerTargetUnitIndex !== null) {
                form.setValue(`units.${buyerTargetUnitIndex}.buyerCustomerId`, String(customer.id || ''), {
                  shouldDirty: true,
                  shouldTouch: true,
                  shouldValidate: false,
                });
                form.setValue(`units.${buyerTargetUnitIndex}.buyerName`, String(customer.name || ''), {
                  shouldDirty: true,
                  shouldTouch: true,
                  shouldValidate: false,
                });
              }
              setBuyerTargetUnitIndex(null);
            }}
          />
        </form>
      </Form>
    </div>
  );
}
