'use client';

import React, { useState, useEffect, useMemo } from 'react';
import MainLayout from '@/components/layout/MainLayout';
import ModalPortal from '@/components/common/ModalPortal';
import OrderUploadModal from '@/components/orders/OrderUploadModal';
import AdvancedFilters, { OrderFilters } from '@/components/orders/AdvancedFilters';
import MassTrackingModal from '@/components/orders/MassTrackingModal';
import FullOrderEditModal from '@/components/orders/FullOrderEditModal';
import { addNotification } from '@/lib/notifications';
import { formatDateToYYYYMMDD, calculateShipDate, validateOrderDates } from '@/lib/dateUtils';
import * as XLSX from 'xlsx';

/** Returns the shipping weight: ceiling of the greater between dimWeight and realWeight */
function calcShipWeight(dimWeight?: number | null, realWeight?: number | null): number {
  const dim = dimWeight ? Math.ceil(dimWeight) : 0;
  const real = realWeight ? Math.ceil(realWeight) : 0;
  return Math.max(dim, real);
}

type OrderLine = {
  id: string;
  quantity: number;
  trackingNumber?: string | null;
  airwayBill?: string | null;
  uniqueCode?: string | null;
  boxNumber?: string | null;
  farmId?: string | null;
  receivedDate?: string | Date | null;
  price?: number;
  status: string;
  message?: string;
  observaciones?: string;
  rawRowData?: string;
  isDuplicate?: boolean;
  duplicateInfo?: string;
  product: {
    id: string;
    name: string;
    code: string;
    recipes?: any[];
    stems?: number;
    length?: number;
    width?: number;
    height?: number;
    realWeight?: number;
    dimWeight?: number;
    declaredValue?: number;
    service?: string;
    packType?: string;
    country?: string;
    originCity?: string;
    htsCode?: string;
  };
  farm?: { name: string; code?: string; country?: string | null; ruc?: string | null } | null;
};

type Order = {
  id: string;
  po: string;
  orderNumber: string;
  creationDate: string;
  deliveryDate: string;
  awb?: string;
  master?: string;
  shipdt?: string;
  service?: string;
  status: string;
  isDuplicate?: boolean;
  duplicateInfo?: string;
  billingCustomer?: {
    businessName: string;
    contactName?: string;
    address?: string;
    address2?: string;
    city?: string;
    state?: string;
    zipCode?: string;
    phone?: string;
    email?: string;
    country?: string;
    taxId?: string;
  };
  shippingCustomer?: {
    businessName: string;
    contactName?: string;
    address?: string;
    address2?: string;
    city?: string;
    state?: string;
    zipCode?: string;
    phone?: string;
    country?: string;
  };
  masterCustomer?: {
    businessName: string;
    contactName?: string;
    address?: string;
    address2?: string;
    city?: string;
    state?: string;
    zipCode?: string;
    phone?: string;
    taxId?: string;
    country?: string;
  };
  lines: OrderLine[];
};

type FlatRow = OrderLine & { order: Order };

const initialFilters: OrderFilters = {
  dateField: 'creationDate',
  dateFrom: '',
  dateTo: '',
  tracking: '',
  po: '',
  customerName: '',
  itemCode: '',
  farmName: ''
};

function getOrderStatusTag(line: FlatRow): { label: string; color: string; bg: string } {
  if (line.status === 'CANCELLED' || line.order.status === 'CANCELLED') {
    return { label: 'CANCELADO', color: '#991b1b', bg: '#fee2e2' };
  }
  if (line.status === 'DELIVERED' || line.order.status === 'DELIVERED') {
    return { label: 'DELIVERED', color: '#15803d', bg: '#dcfce7' };
  }
  if (line.trackingNumber) {
    return { label: 'TRACKING ASIGNED', color: '#166534', bg: '#dcfce7' };
  }
  if (line.status === 'RECEIVED' || line.receivedDate) {
    return { label: 'RECEIVED', color: '#1e40af', bg: '#dbeafe' };
  }
  if (line.farmId && (line.order.awb || line.airwayBill)) {
    return { label: 'FARM ASIGNED', color: '#854d0e', bg: '#fef08a' };
  }
  
  return { label: 'NEW', color: '#374151', bg: '#f3f4f6' };
}

function formatDisplayDate(val: any): string {
  if (!val) return '—';
  const formatted = formatDateToYYYYMMDD(val);
  return formatted || '—';
}

export type QuickFilterType = 'ALL' | 'AUDIT' | 'WEEKEND' | 'SHORT_LEAD' | 'WARNING_LEAD' | 'NO_RECIPE' | 'NEW' | 'DUPLICATES';

export default function OrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [knownProductMap, setKnownProductMap] = useState<Map<string, { hasRecipe: boolean, name: string }>>(new Map());
  const [selectedLineIds, setSelectedLineIds] = useState<Set<string>>(new Set());
  const [quickFilter, setQuickFilter] = useState<QuickFilterType>('ALL');
  
  // Modals state
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [showMassTrackingModal, setShowMassTrackingModal] = useState(false);
  
  const [showDeleteAllModal, setShowDeleteAllModal] = useState(false);
  const [deleteAllConfirm, setDeleteAllConfirm] = useState('');
  
  const [showEditLineModal, setShowEditLineModal] = useState(false);
  const [editingLine, setEditingLine] = useState<FlatRow | null>(null);
  const [editLineForm, setEditLineForm] = useState({ date: '', productCode: '', quantity: '' });
  
  const [fullEditOrderId, setFullEditOrderId] = useState<string | null>(null);

  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [cancellingId, setCancellingId] = useState<string | null>(null);

  // Reenvío (Reposición) Modal state
  const [showResendModal, setShowResendModal] = useState(false);
  const [resendTargetIds, setResendTargetIds] = useState<string[]>([]);
  const [resendReason, setResendReason] = useState('Cliente solicitó reenvío: producto llegó en mal estado / dañado');
  const [resendDeliveryDate, setResendDeliveryDate] = useState('');
  const [resending, setResending] = useState(false);

  // Bulk Delivery Date Modal state
  const [showBulkDateModal, setShowBulkDateModal] = useState(false);
  const [bulkNewDeliveryDate, setBulkNewDeliveryDate] = useState('');
  const [bulkApplying, setBulkApplying] = useState(false);

  // Security Admin Code PIN Modal state
  const [showSecurityPinModal, setShowSecurityPinModal] = useState(false);
  const [securityPinInput, setSecurityPinInput] = useState('');
  const [securityPinError, setSecurityPinError] = useState('');
  const [pendingAdminAction, setPendingAdminAction] = useState<(() => Promise<void>) | null>(null);

  // Batch delete state & progress
  const [batchDeleting, setBatchDeleting] = useState(false);
  const [batchDeleteCount, setBatchDeleteCount] = useState(0);
  const [batchDeleteSeconds, setBatchDeleteSeconds] = useState(0);
  const [batchDeleteSuccess, setBatchDeleteSuccess] = useState<string | null>(null);

  // Filters state
  const [filters, setFilters] = useState<OrderFilters>(initialFilters);
  const [appliedFilters, setAppliedFilters] = useState<OrderFilters>(initialFilters);

  // Read URL query params on mount (from dashboard cards or links)
  useEffect(() => {
    if (typeof window === 'undefined') return;
    const params = new URLSearchParams(window.location.search);
    const filterParam = params.get('filter');
    const statusParam = params.get('status');
    const poParam = params.get('po');

    if (poParam) {
      setFilters(prev => ({ ...prev, po: poParam }));
      setAppliedFilters(prev => ({ ...prev, po: poParam }));
    }

    if (filterParam === 'weekend') {
      setQuickFilter('WEEKEND');
    } else if (filterParam === 'short-lead') {
      setQuickFilter('SHORT_LEAD');
    } else if (filterParam === 'audit') {
      setQuickFilter('AUDIT');
    } else if (filterParam === 'no-recipe') {
      setQuickFilter('NO_RECIPE');
    } else if (filterParam === 'duplicates') {
      setQuickFilter('DUPLICATES');
    } else if (statusParam === 'new') {
      setQuickFilter('NEW');
    }
  }, []);

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const [resOrders, resProd] = await Promise.all([
        fetch('/api/orders'),
        fetch('/api/products'),
      ]);
      if (resOrders.ok) setOrders(await resOrders.json());
      if (resProd.ok) {
        const prods: any[] = await resProd.json();
        const map = new Map();
        prods.forEach(p => map.set(p.code.trim().toUpperCase(), { hasRecipe: p.recipes && p.recipes.length > 0, name: p.name }));
        setKnownProductMap(map);
      }
    } catch (e) { console.error('Error fetching orders:', e); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchOrders(); }, []);

  // ── Notify when orders have products without a recipe ──────────────
  const notifiedRef = React.useRef(false);
  useEffect(() => {
    if (orders.length === 0 || knownProductMap.size === 0) return;
    if (notifiedRef.current) return;
    notifiedRef.current = true;

    const missingRecipeCodes = new Set<string>();
    orders.forEach(order => {
      order.lines.forEach(line => {
        const code = line.product.code.trim().toUpperCase();
        const info = knownProductMap.get(code);
        if (!info || !info.hasRecipe) {
          missingRecipeCodes.add(line.product.code);
        }
      });
    });
    if (missingRecipeCodes.size > 0) {
      const codesStr = Array.from(missingRecipeCodes).slice(0, 5).join(', ');
      const extra = missingRecipeCodes.size > 5 ? ` y ${missingRecipeCodes.size - 5} más` : '';
      addNotification({
        module: 'Órdenes',
        message: `⚠ ${missingRecipeCodes.size} producto(s) sin receta en órdenes: ${codesStr}${extra}`,
        link: '/orders',
      });
    }
  }, [orders, knownProductMap]);

  // Flatten all lines across orders
  const allFlattenedLines = useMemo<FlatRow[]>(() => {
    const lines: FlatRow[] = [];
    orders.forEach(order => {
      order.lines.forEach(line => {
        lines.push({ ...line, order } as FlatRow);
      });
    });
    return lines;
  }, [orders]);

  // Counts for quick audit filters
  const filterCounts = useMemo(() => {
    let weekend = 0;
    let shortLead = 0;
    let warningLead = 0;
    let audit = 0;
    let noRecipe = 0;
    let isNew = 0;
    let duplicates = 0;

    allFlattenedLines.forEach(item => {
      const dVal = validateOrderDates(item.order.creationDate, item.order.deliveryDate);
      const code = item.product.code.trim().toUpperCase();
      const info = knownProductMap.get(code);
      const missingRecipe = !info || !info.hasRecipe;

      if (dVal.isWeekendDelivery) weekend++;
      if (dVal.isLeadTimeUrgent) shortLead++;
      if (dVal.isLeadTimeWarning) warningLead++;
      if (dVal.isWeekendDelivery || dVal.isLeadTimeUrgent) audit++;
      if (missingRecipe) noRecipe++;
      if (item.order.status === 'PENDING' || !item.trackingNumber) isNew++;
      if (item.isDuplicate || item.order.isDuplicate) duplicates++;
    });

    return {
      all: allFlattenedLines.length,
      weekend,
      shortLead,
      warningLead,
      audit,
      noRecipe,
      isNew,
      duplicates
    };
  }, [allFlattenedLines, knownProductMap]);

  const flattenedLines = useMemo<FlatRow[]>(() => {
    return allFlattenedLines.filter(item => {
      const f = appliedFilters;
      let match = true;

      // Quick filter check
      const dVal = validateOrderDates(item.order.creationDate, item.order.deliveryDate);
      const code = item.product.code.trim().toUpperCase();
      const info = knownProductMap.get(code);
      const missingRecipe = !info || !info.hasRecipe;

      if (quickFilter === 'WEEKEND' && !dVal.isWeekendDelivery) return false;
      if (quickFilter === 'SHORT_LEAD' && !dVal.isLeadTimeUrgent) return false;
      if (quickFilter === 'WARNING_LEAD' && !dVal.isLeadTimeWarning) return false;
      if (quickFilter === 'AUDIT' && !dVal.isWeekendDelivery && !dVal.isLeadTimeUrgent) return false;
      if (quickFilter === 'NO_RECIPE' && !missingRecipe) return false;
      if (quickFilter === 'NEW' && item.order.status !== 'PENDING' && !!item.trackingNumber) return false;
      if (quickFilter === 'DUPLICATES' && !item.isDuplicate && !item.order.isDuplicate) return false;

      // Text Filters
      if (f.po && !item.order.po.toLowerCase().includes(f.po.toLowerCase())) match = false;
      if (f.tracking && !(item.trackingNumber || '').toLowerCase().includes(f.tracking.toLowerCase())) match = false;
      if (f.itemCode && !item.product.code.toLowerCase().includes(f.itemCode.toLowerCase())) match = false;
      if (f.customerName && !(item.order.shippingCustomer?.businessName || '').toLowerCase().includes(f.customerName.toLowerCase())) match = false;
      if (f.farmName && !(item.farm?.name || '').toLowerCase().includes(f.farmName.toLowerCase())) match = false;

      // Date Filters
      if (f.dateFrom || f.dateTo) {
        let itemDateStr = '';
        if (f.dateField === 'creationDate') itemDateStr = item.order.creationDate;
        if (f.dateField === 'deliveryDate') itemDateStr = item.order.deliveryDate;
        if (f.dateField === 'shipdt') itemDateStr = item.order.shipdt || '';

        if (itemDateStr) {
          const itemDate = new Date(itemDateStr).getTime();
          if (f.dateFrom) {
            const fromDate = new Date(f.dateFrom).getTime();
            if (itemDate < fromDate) match = false;
          }
          if (f.dateTo) {
            const toDate = new Date(f.dateTo).getTime();
            if (itemDate > toDate + 86400000) match = false; // Add 1 day to include the whole 'To' date
          }
        } else {
          match = false;
        }
      }

      return match;
    });
  }, [allFlattenedLines, appliedFilters, quickFilter, knownProductMap]);

  
  const toggleSelectAll = () => {
    if (selectedLineIds.size === flattenedLines.length && flattenedLines.length > 0) {
      setSelectedLineIds(new Set());
    } else {
      setSelectedLineIds(new Set(flattenedLines.map(l => l.id)));
    }
  };

  const toggleSelectLine = (id: string) => {
    const next = new Set(selectedLineIds);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelectedLineIds(next);
  };

  // ── Admin Security Verification ────────────────────────────────
  const requireAdminAuth = (action: () => Promise<void>) => {
    setPendingAdminAction(() => action);
    setSecurityPinInput('');
    setSecurityPinError('');
    setShowSecurityPinModal(true);
  };

  const handleVerifyPin = async (e: React.FormEvent) => {
    e.preventDefault();
    const validCodes = ['1234', 'iamironman23', 'admin', '9999', 'USFLORAL'];
    if (validCodes.includes(securityPinInput.trim())) {
      setShowSecurityPinModal(false);
      if (pendingAdminAction) {
        const action = pendingAdminAction;
        setPendingAdminAction(null);
        await action();
      }
    } else {
      setSecurityPinError('Código de seguridad incorrecto. Solo administradores autorizados pueden eliminar órdenes.');
    }
  };

  const executeDeleteSelected = async () => {
    if (selectedLineIds.size === 0) return;
    const count = selectedLineIds.size;
    setBatchDeleting(true);
    setBatchDeleteCount(count);
    setBatchDeleteSeconds(0);
    setBatchDeleteSuccess(null);

    const timer = setInterval(() => {
      setBatchDeleteSeconds(s => s + 1);
    }, 1000);

    try {
      const ids = Array.from(selectedLineIds);
      const res = await fetch('/api/orders/lines/batch-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al eliminar órdenes en lote');

      clearInterval(timer);
      setBatchDeleting(false);
      setSelectedLineIds(new Set());
      await fetchOrders();
      setBatchDeleteSuccess(`Se eliminaron exitosamente las ${data.count || count} órdenes seleccionadas del sistema.`);
    } catch (err: any) {
      clearInterval(timer);
      setBatchDeleting(false);
      alert('Error al eliminar órdenes: ' + err.message);
    }
  };

  const handleDeleteSelected = () => {
    if (selectedLineIds.size === 0) return;
    requireAdminAuth(executeDeleteSelected);
  };

  // ── Actions: Eliminar, Cancelar, Reenviar ───────────────────────────────────

  const handleDeleteAll = () => {
    if (deleteAllConfirm.toLowerCase() !== 'borrar') return;
    requireAdminAuth(async () => {
      setSaving(true);
      try {
        const res = await fetch('/api/orders/clear', { method: 'DELETE' });
        if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error al limpiar'); }
        setShowDeleteAllModal(false);
        setDeleteAllConfirm('');
        fetchOrders();
      } catch (err: any) { alert(err.message); }
      setSaving(false);
    });
  };

  const handleDeleteLine = (lineId: string) => {
    requireAdminAuth(async () => {
      setDeletingId(lineId);
      try {
        const res = await fetch(`/api/orders/lines/${lineId}`, { method: 'DELETE' });
        if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error al eliminar'); }
        fetchOrders();
      } catch (err: any) { alert(err.message); }
      setDeletingId(null);
    });
  };

  // ── Reenvío (Reposición de caja) ──────────────────────────────────
  const openResend = (lineIds: string[], defaultDate?: string) => {
    if (lineIds.length === 0) return;
    setResendTargetIds(lineIds);
    setResendReason('Cliente solicitó reenvío: flor en mal estado / daño de transporte');
    setResendDeliveryDate(defaultDate ? formatDateToYYYYMMDD(defaultDate) : '');
    setShowResendModal(true);
  };

  const handleConfirmResend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (resendTargetIds.length === 0) return;
    if (!resendReason.trim()) {
      alert('Por favor ingrese el motivo del reenvío');
      return;
    }
    setResending(true);
    try {
      const res = await fetch('/api/orders/re-send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          lineIds: resendTargetIds,
          reason: resendReason.trim(),
          deliveryDate: resendDeliveryDate || undefined,
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al procesar el reenvío');

      alert(data.message || 'Reenvío generado exitosamente');
      setShowResendModal(false);
      setSelectedLineIds(new Set());
      await fetchOrders();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setResending(false);
    }
  };

  // ── Cancelación de Líneas / Cajas ───────────────────────────────────
  const handleCancelLines = async (lineIds: string[]) => {
    if (lineIds.length === 0) return;
    const reason = window.prompt(
      `¿Confirmas la CANCELACIÓN de ${lineIds.length} caja(s)? La(s) línea(s) se pintarán de rojo y no se exportarán a ningún archivo. Ingresa el motivo:`,
      'Cancelación solicitada por cliente'
    );
    if (reason === null) return; // canceló el prompt

    setCancellingId(lineIds[0]);
    try {
      const res = await fetch('/api/orders/lines/cancel', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ lineIds, reason: reason.trim() })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al cancelar');

      alert(data.message || 'Cajas canceladas exitosamente.');
      setSelectedLineIds(new Set());
      await fetchOrders();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setCancellingId(null);
    }
  };

  // ── Cambio Masivo de Fecha de Entrega (Delivery Date) ────────────────
  const handleApplyBulkDeliveryDate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (selectedLineIds.size === 0 || !bulkNewDeliveryDate) return;
    setBulkApplying(true);
    try {
      const res = await fetch('/api/orders/bulk-delivery-date', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          lineIds: Array.from(selectedLineIds),
          newDeliveryDate: bulkNewDeliveryDate,
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al cambiar la fecha de entrega');

      alert(data.message || 'Fechas actualizadas exitosamente');
      setShowBulkDateModal(false);
      setSelectedLineIds(new Set());
      await fetchOrders();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setBulkApplying(false);
    }
  };

  // ── Line Edit ────────────────────────────────────────────────────────
  const openEditLine = (line: FlatRow) => {
    setEditingLine(line);
    setEditLineForm({
      date: new Date(line.order.creationDate).toISOString().split('T')[0],
      productCode: line.product.code,
      quantity: line.quantity.toString()
    });
    setShowEditLineModal(true);
  };

  const handleSaveLineEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingLine) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/orders/lines/${editingLine.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editLineForm)
      });
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error al guardar'); }
      setShowEditLineModal(false);
      fetchOrders();
    } catch (err: any) { alert(err.message); }
    setSaving(false);
  };

  // ── Helper: truncate name to 35 chars for carrier compliance ──
  const truncate35 = (str?: string) => (str || '').substring(0, 35);

  // ── Export to Excel (UPS Format) ──────────
  const handleExport = () => {
    // Excluir órdenes o cajas canceladas para evitar despachos erróneos
    const exportableLines = flattenedLines.filter(item => item.status !== 'CANCELLED' && item.order.status !== 'CANCELLED');
    if (exportableLines.length === 0) {
      alert('No hay órdenes activas para exportar (las órdenes canceladas quedan netamente informativas y no se descargan).');
      return;
    }

    // Check if we have raw row data (uploaded from Excel)
    const hasRawData = exportableLines.some(item => item.rawRowData);

    if (hasRawData) {
      let colKeys: string[] = [];
      let headerLabels: string[] = [];

      // Find a row with rawRowData to determine column structure
      const sampleRaw = exportableLines.find(item => item.rawRowData);
      if (sampleRaw?.rawRowData) {
        try {
          const parsed = JSON.parse(sampleRaw.rawRowData);
          const headersObj = parsed._headers || {};
          
          // Remove column AY
          colKeys = Object.keys(headersObj).filter(k => k.toUpperCase() !== 'AY'); 
          headerLabels = colKeys.map(k => headersObj[k]); // 'Tracking', 'Company', ...
        } catch(e) {}
      }

      if (colKeys.length > 0) {
        const dataRows = exportableLines.map(item => {
          let rawObj: Record<string, any> = {};
          let headersObj: Record<string, any> = {};
          try {
            if (item.rawRowData) {
              const parsed = JSON.parse(item.rawRowData);
              headersObj = parsed._headers || {};
              // Extract only data keys (no _headers)
              colKeys.forEach(k => { rawObj[k] = parsed[k] ?? ''; });
            }
          } catch(e) {}

          const p = item.product;
          const billing  = item.order.billingCustomer;
          const shipping = item.order.shippingCustomer;
          const master   = item.order.masterCustomer;

          const tpComp  = master?.businessName || billing?.businessName || 'US FLORALS LLC';
          const tpAttn  = master?.contactName  || billing?.contactName  || 'ALEXANDER ALFONSO';
          const tpAdd1  = master?.address      || billing?.address      || '20980 SW 234TH ST';
          const tpCity  = master?.city         || billing?.city         || 'HOMESTEAD';
          const tpState = master?.state        || billing?.state        || 'FL';
          const tpCtry  = master?.country      || billing?.country      || 'US';
          const tpZip   = master?.zipCode      || billing?.zipCode      || '33031';
          const tpPhone = master?.phone        || billing?.phone        || '786-749-4338';
          const tpAcct  = master?.taxId        || billing?.taxId        || '5Y68W8';

          // Helper to find column keys by their original header name
          const findColByHeader = (names: string[]) =>
            colKeys.find(k => names.includes((headersObj[k] || '').toString().trim().toLowerCase()));

          // Override tracking if assigned
          const trackingKey = colKeys.find(k => k.toUpperCase() === 'A' || ['tracking'].includes((headersObj[k] || '').toString().trim().toLowerCase()));
          if (trackingKey && item.trackingNumber) rawObj[trackingKey] = item.trackingNumber;

          // Orddate (Column D) -> must be YYYY-MM-DD
          const orddateKey = findColByHeader(['orddate', 'order date', 'orderdate']) || colKeys.find(k => k.toUpperCase() === 'D');
          if (orddateKey) {
            rawObj[orddateKey] = formatDateToYYYYMMDD(rawObj[orddateKey] || item.order.creationDate);
          }

          // Deliver (Column S) -> must be YYYY-MM-DD
          const deliverKey = findColByHeader(['deliver', 'delivery date', 'deliverydate']) || colKeys.find(k => k.toUpperCase() === 'S');
          if (deliverKey) {
            rawObj[deliverKey] = formatDateToYYYYMMDD(rawObj[deliverKey] || item.order.deliveryDate);
          }

          // SHIPDT (Column R) -> calculate if missing, must be YYYY-MM-DD
          const shipdtKey = findColByHeader(['shipdt', 'ship date', 'shipdate']) || colKeys.find(k => k.toUpperCase() === 'R');
          if (shipdtKey) {
            const calculatedShip = item.order.shipdt || calculateShipDate(item.order.deliveryDate, 'UPS');
            rawObj[shipdtKey] = formatDateToYYYYMMDD(calculatedShip);
          }

          // SatDel (Column T) -> default to 'N'
          const satDelKey = findColByHeader(['satdel', 'sat del', 'sat delivery', 'satdeliver']) || colKeys.find(k => k.toUpperCase() === 'T');
          if (satDelKey) {
            rawObj[satDelKey] = (rawObj[satDelKey] && String(rawObj[satDelKey]).trim() !== '') ? String(rawObj[satDelKey]).trim() : 'N';
          }

          // Message column (AC or Message) and MSG/AU
          const acKey = colKeys.find(k => k.toUpperCase() === 'AC' || ['message'].includes((headersObj[k] || '').toString().trim().toLowerCase()));
          const auKey = colKeys.find(k => k.toUpperCase() === 'AU' || ['msg'].includes((headersObj[k] || '').toString().trim().toLowerCase()));

          const origMsg = acKey ? (rawObj[acKey] || '') : '';
          const finalMsg = item.message ? (origMsg ? `${origMsg} - ${item.message}` : item.message) : origMsg;
          if (acKey) rawObj[acKey] = finalMsg;
          if (auKey) rawObj[auKey] = finalMsg ? 'Y' : 'N';

          // Ensure product dimensions, weights, service, pkgType, currency, etc. are populated if empty
          const lengthKey = findColByHeader(['length']) || colKeys.find(k => k.toUpperCase() === 'X');
          if (lengthKey && (!rawObj[lengthKey] || rawObj[lengthKey] === '')) rawObj[lengthKey] = p.length || '';

          const widthKey = findColByHeader(['width']) || colKeys.find(k => k.toUpperCase() === 'Y');
          if (widthKey && (!rawObj[widthKey] || rawObj[widthKey] === '')) rawObj[widthKey] = p.width || '';

          const heightKey = findColByHeader(['height']) || colKeys.find(k => k.toUpperCase() === 'Z');
          if (heightKey && (!rawObj[heightKey] || rawObj[heightKey] === '')) rawObj[heightKey] = p.height || '';

          const weightKey = findColByHeader(['weightkg', 'weight']) || colKeys.find(k => k.toUpperCase() === 'AA');
          if (weightKey && (!rawObj[weightKey] || rawObj[weightKey] === '')) rawObj[weightKey] = calcShipWeight(p.dimWeight, p.realWeight) || '';

          const dclKey = findColByHeader(['dclvalue', 'declaredvalue']) || colKeys.find(k => k.toUpperCase() === 'AB');
          if (dclKey && (!rawObj[dclKey] || rawObj[dclKey] === '')) rawObj[dclKey] = p.declaredValue ?? item.price ?? '';

          // Helper to normalize farm/origin country to 2-letter ISO code (e.g. 'EC', 'CO')
          const resolveOriginCountry = (farmCountry?: string | null, prodCountry?: string | null): string => {
            const raw = (farmCountry || prodCountry || 'EC').trim().toUpperCase();
            if (raw.startsWith('EC')) return 'EC';
            if (raw.startsWith('CO')) return 'CO';
            if (raw.length === 2) return raw;
            return 'EC';
          };

          // Overwrite with predetermined values according to specification:
          const serviceKey = findColByHeader(['service']) || colKeys.find(k => k.toUpperCase() === 'AD');
          if (serviceKey) rawObj[serviceKey] = 'ES';

          const pkgKey = findColByHeader(['pkgtype', 'packtype']) || colKeys.find(k => k.toUpperCase() === 'AE');
          if (pkgKey) rawObj[pkgKey] = 'CP';

          // Columna W (ProdDesc)
          const prodDescKey = findColByHeader(['proddesc', 'product description', 'description']) || colKeys.find(k => k.toUpperCase() === 'W');
          const colWValue = (prodDescKey && rawObj[prodDescKey]) ? rawObj[prodDescKey] : truncate35(p.name);

          // GenDesc (Column AF) -> Exactamente la misma información de Columna W
          const genDescKey = findColByHeader(['gendesc']) || colKeys.find(k => k.toUpperCase() === 'AF');
          if (genDescKey) rawObj[genDescKey] = colWValue;

          const shipCtryKey = findColByHeader(['shipctry']) || colKeys.find(k => k.toUpperCase() === 'AG');
          if (shipCtryKey) rawObj[shipCtryKey] = 'US';

          const currKey = findColByHeader(['currency']) || colKeys.find(k => k.toUpperCase() === 'AH');
          if (currKey) rawObj[currKey] = 'USD';

          // Origin (Column AI) -> Carga del origen de la finca asignada en pedido fincas (o producto)
          const originKey = findColByHeader(['origin']) || colKeys.find(k => k.toUpperCase() === 'AI');
          if (originKey) rawObj[originKey] = resolveOriginCountry(item.farm?.country, p.country);

          const uomKey = findColByHeader(['uom']) || colKeys.find(k => k.toUpperCase() === 'AJ');
          if (uomKey) rawObj[uomKey] = 'BOX';

          // TP billing keys (Valores predeterminados de US FLORALS LLC)
          const tpCompKey = findColByHeader(['tpcomp']) || colKeys.find(k => k.toUpperCase() === 'AK');
          if (tpCompKey) rawObj[tpCompKey] = 'US FLORALS LLC';

          const tpAttnKey = findColByHeader(['tpattn']) || colKeys.find(k => k.toUpperCase() === 'AL');
          if (tpAttnKey) rawObj[tpAttnKey] = 'ALEXANDER ALFONSO';

          const tpAdd1Key = findColByHeader(['tpadd1']) || colKeys.find(k => k.toUpperCase() === 'AM');
          if (tpAdd1Key) rawObj[tpAdd1Key] = '20980 SW 234TH ST';

          const tpCityKey = findColByHeader(['tpcity']) || colKeys.find(k => k.toUpperCase() === 'AN');
          if (tpCityKey) rawObj[tpCityKey] = 'HOMESTEAD';

          const tpStateKey = findColByHeader(['tpstate']) || colKeys.find(k => k.toUpperCase() === 'AO');
          if (tpStateKey) rawObj[tpStateKey] = 'FL';

          const tpCtryKey = findColByHeader(['tpctry']) || colKeys.find(k => k.toUpperCase() === 'AP');
          if (tpCtryKey) rawObj[tpCtryKey] = 'US';

          const tpZipKey = findColByHeader(['tpzip']) || colKeys.find(k => k.toUpperCase() === 'AQ');
          if (tpZipKey) rawObj[tpZipKey] = '33031';

          const tpPhoneKey = findColByHeader(['tpphone']) || colKeys.find(k => k.toUpperCase() === 'AR');
          if (tpPhoneKey) rawObj[tpPhoneKey] = '786-749-4338';

          const tpAcctKey = findColByHeader(['tpacct']) || colKeys.find(k => k.toUpperCase() === 'AS');
          if (tpAcctKey) rawObj[tpAcctKey] = '5Y68W8';

          const farmKey = findColByHeader(['farm']) || colKeys.find(k => k.toUpperCase() === 'AT');
          if (farmKey) rawObj[farmKey] = item.farm?.name || rawObj[farmKey] || '';

          const awbKey = findColByHeader(['awb']) || colKeys.find(k => k.toUpperCase() === 'AV');
          if (awbKey && (!rawObj[awbKey] || rawObj[awbKey] === '')) rawObj[awbKey] = item.order.awb || item.airwayBill || '';

          const obsKey = findColByHeader(['observaciones']) || colKeys.find(k => k.toUpperCase() === 'AW');
          if (obsKey && (!rawObj[obsKey] || rawObj[obsKey] === '')) rawObj[obsKey] = item.observaciones || '';

          return colKeys.map(k => rawObj[k] ?? '');
        });

        const aoa = [headerLabels, ...dataRows];
        const ws = XLSX.utils.aoa_to_sheet(aoa);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, `ordenes_UPS_${new Date().toISOString().split('T')[0]}.xlsx`);
        return;
      }
    }

    // Helper to normalize farm/origin country to 2-letter ISO code (e.g. 'EC', 'CO')
    const resolveOriginCountry = (farmCountry?: string | null, prodCountry?: string | null): string => {
      const raw = (farmCountry || prodCountry || 'EC').trim().toUpperCase();
      if (raw.startsWith('EC')) return 'EC';
      if (raw.startsWith('CO')) return 'CO';
      if (raw.length === 2) return raw;
      return 'EC';
    };

    // Fallback: no raw data, build from DB fields
    const rows = exportableLines.map(item => {
      const p = item.product;
      const billing  = item.order.billingCustomer;
      const shipping = item.order.shippingCustomer;
      const master   = item.order.masterCustomer;

      const finalMsg = item.message || '';
      return {
        Tracking:      item.trackingNumber || '',
        Company:       master?.businessName || billing?.businessName || '',
        eBinv:         '',
        Orddate:       formatDateToYYYYMMDD(item.order.creationDate),
        Shipto:        shipping?.businessName || '',
        Shipto2:       shipping?.contactName  || '',
        Address:       shipping?.address  || '',
        Address2:      shipping?.address2 || '',
        City:          shipping?.city     || '',
        State:         shipping?.state    || '',
        Zip:           shipping?.zipCode  || '',
        Phone:         shipping?.phone    || '',
        Soldto:        billing?.businessName || '',
        Soldto2:       billing?.contactName  || '',
        STPhone:       billing?.phone    || '',
        Ponumber:      item.order.po,
        CUSTnbr:       item.order.orderNumber,
        SHIPDT:        formatDateToYYYYMMDD(item.order.shipdt || calculateShipDate(item.order.deliveryDate, 'UPS')),
        Deliver:       formatDateToYYYYMMDD(item.order.deliveryDate),
        SatDel:        'N',
        Quantity:      item.quantity,
        Item:          p.code,
        ProdDesc:      truncate35(p.name),
        Length:        p.length     || '',
        Width:         p.width      || '',
        Height:        p.height     || '',
        WeightKg:      calcShipWeight(p.dimWeight, p.realWeight) || '',
        DclValue:      p.declaredValue ?? item.price ?? '',
        Message:       finalMsg,
        Service:       'ES',
        PkgType:       'CP',
        GenDesc:       truncate35(p.name),
        ShipCtry:      'US',
        Currency:      'USD',
        Origin:        resolveOriginCountry(item.farm?.country, p.country),
        UOM:           'BOX',
        TPComp:        'US FLORALS LLC',
        TPAttn:        'ALEXANDER ALFONSO',
        TPAdd1:        '20980 SW 234TH ST',
        TPCity:        'HOMESTEAD',
        TPState:       'FL',
        TPCtry:        'US',
        TPZip:         '33031',
        TPPhone:       '786-749-4338',
        TPAcct:        '5Y68W8',
        Farm:          item.farm?.name || '',
        MSG:           finalMsg || 'N',
        AWB:           item.order.awb || item.airwayBill || '',
        OBSERVACIONES: item.observaciones || '',
        AC:            finalMsg,
        AU:            finalMsg ? 'Y' : 'N',
      };
    });
    const ws = XLSX.utils.json_to_sheet(rows);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, `ordenes_UPS_${new Date().toISOString().split('T')[0]}.xlsx`);
  };


  // ── Export to Excel (FedEx Planilla Format - exact column match) ──────────
  const handleExportFedEx = () => {
    const exportableLines = flattenedLines.filter(item => item.status !== 'CANCELLED' && item.order.status !== 'CANCELLED');
    if (exportableLines.length === 0) {
      alert('No hay órdenes activas para exportar (las órdenes canceladas quedan netamente informativas y no se descargan).');
      return;
    }
    // Build rows in exact FedEx planilla format:
    // REC, COMPANY, CONTACT, ADR1, ADR2, CITY, STATE, ZIPCODE, COUNTRY, PHONE,
    // WEIGHT, LENGTH, WIDTH, HEIGHT, REF, DESCRIPTION, PART_NUMBER, UNIT VALUE,
    // QUANTITY, QUANTITY_UNITS, CUST_VAL, DEC_VAL, CTRY_MAN, ISS_NSR, REL_NUMBER, CUT FLOWERS
    const rows = exportableLines.map((item, idx) => {
      const p = item.product;
      const shipping = item.order.shippingCustomer;
      const billing  = item.order.billingCustomer;
      const recNum = String(idx + 1).padStart(3, '0'); // 001, 002, 003...
      const prodName35 = truncate35(p.name);
      const dclVal = p.declaredValue ?? item.price ?? 0;

      return {
        'REC':              recNum,
        'COMPANY':          truncate35(shipping?.businessName || billing?.businessName || ''),
        'CONTACT':          truncate35(shipping?.contactName  || shipping?.businessName || ''),
        'ADR1':             (shipping?.address  || '').substring(0, 35),
        'ADR2':             (shipping?.address2 || ''),
        'CITY':             shipping?.city    || '',
        'STATE':            shipping?.state   || '',
        'ZIPCODE':          shipping?.zipCode || '',
        'COUNTRY':          shipping?.country || 'US',
        'PHONE':            shipping?.phone   || billing?.phone || '',
        'WEIGHT':           calcShipWeight(p.dimWeight, p.realWeight) || '',
        'LENGTH':           p.length     || '',
        'WIDTH':            p.width      || '',
        'HEIGHT':           p.height     || '',
        'REF':              prodName35,
        'DESCRIPTION':      p.code || '',
        'PART_NUMBER':      'FRESH CUT FLOWERS',
        'UNIT VALUE':       Number(dclVal).toFixed(2),
        'QUANTITY':         item.quantity,
        'QUANTITY_UNITS':   'EA',
        'CUST_VAL':         Number(dclVal).toFixed(2),
        'DEC_VAL':          Number(dclVal).toFixed(2),
        'CTRY_MAN':         p.country || 'EC',
        ' ISS_NSR':         'Y',
        'REL_NUMBER':       '34461235',
        'CUT FLOWERS':      'Y',
      };
    });

    // Use array-of-arrays to preserve exact column order
    const headers = ['REC','COMPANY','CONTACT','ADR1','ADR2','CITY','STATE','ZIPCODE','COUNTRY','PHONE',
      'WEIGHT','LENGTH','WIDTH','HEIGHT','REF','DESCRIPTION','PART_NUMBER','UNIT VALUE','QUANTITY',
      'QUANTITY_UNITS','CUST_VAL','DEC_VAL','CTRY_MAN',' ISS_NSR','REL_NUMBER','CUT FLOWERS'];
    const dataArr = [headers, ...rows.map(r => headers.map(h => (r as Record<string, string|number>)[h] ?? ''))];

    const ws = XLSX.utils.aoa_to_sheet(dataArr);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Archivo Ejemplo');
    XLSX.writeFile(wb, `FEDEX_PLANILLA_${new Date().toISOString().split('T')[0]}.xls`, { bookType: 'xls' });
  };

  const tdBase: React.CSSProperties = { padding: '0.6rem 0.75rem', fontSize: '0.8rem', whiteSpace: 'nowrap', borderBottom: '1px solid var(--border-color)' };
  const thBase: React.CSSProperties = { padding: '0.75rem', whiteSpace: 'nowrap', fontWeight: 700, fontSize: '0.75rem', textTransform: 'uppercase', letterSpacing: '0.05em', background: 'var(--bg-secondary)', color: 'var(--text-secondary)' };

  return (
    <MainLayout>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h1 style={{ fontSize: '2rem', fontWeight: 800, color: 'var(--primary-color)' }}>Gestión de Órdenes</h1>
          <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem' }}>Búsqueda avanzada, edición, clonación y exportación.</p>
        </div>
        <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
          <button
            type="button"
            className="btn-secondary"
            onClick={fetchOrders}
            disabled={loading}
            style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', fontWeight: 700 }}
            title="Actualizar tabla de órdenes instantáneamente"
          >
            <svg
              width="15" height="15" fill="none" stroke="currentColor" viewBox="0 0 24 24"
              style={{ animation: loading ? 'spin 0.8s linear infinite' : 'none' }}
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            {loading ? 'Actualizando...' : 'Actualizar Información'}
          </button>
          <button className="btn-secondary" style={{ color: '#dc2626', borderColor: '#fca5a5' }} onClick={() => setShowDeleteAllModal(true)}>
            Borrar Todas
          </button>
          <button className="btn-secondary" onClick={() => window.open('/api/orders/template-ups', '_blank')}>
            Formato UPS
          </button>
          <button className="btn-secondary" onClick={handleExport}>
            Exportar UPS
          </button>
          <button className="btn-secondary" style={{ borderColor: '#7c3aed', color: '#6d28d9' }} onClick={handleExportFedEx}>
            Exportar FedEx
          </button>
          <button className="btn-primary" onClick={() => setShowMassTrackingModal(true)}>
            Asignar Trackings Masivo
          </button>
          <button className="btn-primary" onClick={() => setIsUploadModalOpen(true)}>
            Cargar Órdenes
          </button>
        </div>
      </div>

      <AdvancedFilters
        filters={filters}
        onChange={setFilters}
        onSearch={() => setAppliedFilters(filters)}
        onClear={() => { setFilters(initialFilters); setAppliedFilters(initialFilters); }}
      />

      {/* ── BARRA DE FILTROS RÁPIDOS Y AUDITORÍA DE ÓRDENES ── */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: '0.5rem',
        marginBottom: '1rem',
        overflowX: 'auto',
        paddingBottom: '0.35rem',
        flexWrap: 'wrap'
      }}>
        <span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-secondary)', marginRight: '0.25rem' }}>
          Auditoría y Filtros:
        </span>

        {/* 1. Todas */}
        <button
          onClick={() => setQuickFilter('ALL')}
          style={{
            padding: '0.4rem 0.85rem',
            borderRadius: '20px',
            fontSize: '0.78rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.15s ease',
            border: quickFilter === 'ALL' ? '1.5px solid var(--primary-color)' : '1px solid #cbd5e1',
            background: quickFilter === 'ALL' ? 'var(--primary-color)' : '#fff',
            color: quickFilter === 'ALL' ? '#fff' : '#334155'
          }}
        >
          Todas ({filterCounts.all})
        </button>

        {/* 2. Órdenes a Auditar (Fin de semana o <= 4 días) */}
        <button
          onClick={() => setQuickFilter('AUDIT')}
          style={{
            padding: '0.4rem 0.85rem',
            borderRadius: '20px',
            fontSize: '0.78rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.15s ease',
            border: quickFilter === 'AUDIT' ? '1.5px solid #b45309' : '1px solid #fed7aa',
            background: quickFilter === 'AUDIT' ? '#b45309' : '#fffbeb',
            color: quickFilter === 'AUDIT' ? '#fff' : '#9a3412',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.35rem'
          }}
        >
          <span>📋 Auditar ({filterCounts.audit})</span>
        </button>

        {/* 3. Delivery Sábado / Domingo (FedEx) */}
        <button
          onClick={() => setQuickFilter('WEEKEND')}
          style={{
            padding: '0.4rem 0.85rem',
            borderRadius: '20px',
            fontSize: '0.78rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.15s ease',
            border: quickFilter === 'WEEKEND' ? '2px solid #ca8a04' : '1.5px solid #facc15',
            background: quickFilter === 'WEEKEND' ? '#ca8a04' : '#fef9c3',
            color: quickFilter === 'WEEKEND' ? '#fff' : '#854d0e',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.35rem',
            boxShadow: filterCounts.weekend > 0 ? '0 1px 4px rgba(234, 179, 8, 0.25)' : undefined
          }}
        >
          <span>⚠️ Fin de Semana ({filterCounts.weekend})</span>
        </button>

        {/* 4. Entrega <= 4 Días */}
        <button
          onClick={() => setQuickFilter('SHORT_LEAD')}
          style={{
            padding: '0.4rem 0.85rem',
            borderRadius: '20px',
            fontSize: '0.78rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.15s ease',
            border: quickFilter === 'SHORT_LEAD' ? '1.5px solid #ea580c' : '1px solid #fed7aa',
            background: quickFilter === 'SHORT_LEAD' ? '#ea580c' : '#fff7ed',
            color: quickFilter === 'SHORT_LEAD' ? '#fff' : '#c2410c',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.35rem'
          }}
        >
          <span>⏳ Entrega &le; 4 Días ({filterCounts.shortLead})</span>
        </button>

        {/* 5. Anticipación < 6 Días */}
        <button
          onClick={() => setQuickFilter('WARNING_LEAD')}
          style={{
            padding: '0.4rem 0.85rem',
            borderRadius: '20px',
            fontSize: '0.78rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.15s ease',
            border: quickFilter === 'WARNING_LEAD' ? '1.5px solid #d97706' : '1px solid #fef08a',
            background: quickFilter === 'WARNING_LEAD' ? '#d97706' : '#fefce8',
            color: quickFilter === 'WARNING_LEAD' ? '#fff' : '#a16207',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.35rem'
          }}
        >
          <span>⚠️ Anticipación &lt; 6d ({filterCounts.warningLead})</span>
        </button>

        {/* 6. Sin Receta */}
        {filterCounts.noRecipe > 0 && (
          <button
            onClick={() => setQuickFilter('NO_RECIPE')}
            style={{
              padding: '0.4rem 0.85rem',
              borderRadius: '20px',
              fontSize: '0.78rem',
              fontWeight: 700,
              cursor: 'pointer',
              transition: 'all 0.15s ease',
              border: quickFilter === 'NO_RECIPE' ? '1.5px solid #dc2626' : '1px solid #fca5a5',
              background: quickFilter === 'NO_RECIPE' ? '#dc2626' : '#fef2f2',
              color: quickFilter === 'NO_RECIPE' ? '#fff' : '#b91c1c',
              display: 'inline-flex',
              alignItems: 'center',
              gap: '0.35rem'
            }}
          >
            <span>⚠️ Sin Receta ({filterCounts.noRecipe})</span>
          </button>
        )}

        {/* 7. Status New */}
        <button
          onClick={() => setQuickFilter('NEW')}
          style={{
            padding: '0.4rem 0.85rem',
            borderRadius: '20px',
            fontSize: '0.78rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.15s ease',
            border: quickFilter === 'NEW' ? '1.5px solid #2563eb' : '1px solid #bfdbfe',
            background: quickFilter === 'NEW' ? '#2563eb' : '#eff6ff',
            color: quickFilter === 'NEW' ? '#fff' : '#1d4ed8',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.35rem'
          }}
        >
          <span>Status New ({filterCounts.isNew})</span>
        </button>

        {/* 8. Duplicadas */}
        {filterCounts.duplicates > 0 && (
          <button
            onClick={() => setQuickFilter('DUPLICATES')}
            style={{
              padding: '0.4rem 0.85rem',
              borderRadius: '20px',
              fontSize: '0.78rem',
              fontWeight: 700,
              cursor: 'pointer',
              transition: 'all 0.15s ease',
              border: quickFilter === 'DUPLICATES' ? '2px solid #dc2626' : '1.5px solid #f87171',
              background: quickFilter === 'DUPLICATES' ? '#dc2626' : '#fef2f2',
              color: quickFilter === 'DUPLICATES' ? '#fff' : '#b91c1c',
              display: 'inline-flex',
              alignItems: 'center',
              gap: '0.35rem',
              boxShadow: '0 1px 4px rgba(220, 38, 38, 0.25)'
            }}
          >
            <span>⚠️ Duplicadas ({filterCounts.duplicates})</span>
          </button>
        )}
      </div>

      {selectedLineIds.size > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0.6rem 1rem', background: '#eff6ff', border: '1px solid #bfdbfe', borderRadius: '8px', marginBottom: '0.75rem', flexWrap: 'wrap', gap: '0.5rem' }}>
          <span style={{ fontSize: '0.85rem', fontWeight: 600, color: '#1e40af' }}>
            ✓ {selectedLineIds.size} de {flattenedLines.length} líneas seleccionadas
          </span>
          <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
            <button
              className="btn-primary"
              style={{ fontSize: '0.75rem', padding: '0.35rem 0.75rem', background: '#0284c7', borderColor: '#0284c7' }}
              onClick={() => {
                setBulkNewDeliveryDate('');
                setShowBulkDateModal(true);
              }}
            >
              📅 Cambiar Fecha Entrega ({selectedLineIds.size})
            </button>
            <button
              className="btn-primary"
              style={{ fontSize: '0.75rem', padding: '0.35rem 0.75rem', background: '#7c3aed', borderColor: '#7c3aed' }}
              onClick={() => openResend(Array.from(selectedLineIds))}
            >
              🔁 Reenviar ({selectedLineIds.size})
            </button>
            <button
              className="btn-secondary"
              style={{ fontSize: '0.75rem', padding: '0.35rem 0.75rem', color: '#b91c1c', borderColor: '#fca5a5' }}
              onClick={() => handleCancelLines(Array.from(selectedLineIds))}
            >
              🚫 Cancelar ({selectedLineIds.size})
            </button>
            <button
              className="btn-secondary"
              style={{ fontSize: '0.75rem', padding: '0.35rem 0.75rem', color: '#dc2626', borderColor: '#fca5a5' }}
              onClick={handleDeleteSelected}
            >
              🗑️ Eliminar ({selectedLineIds.size})
            </button>
            <button
              className="btn-secondary"
              style={{ fontSize: '0.75rem', padding: '0.35rem 0.6rem' }}
              onClick={() => setSelectedLineIds(new Set())}
            >
              Deseleccionar todas
            </button>
          </div>
        </div>
      )}

      <div className="glass-panel" style={{ overflowX: 'auto' }}>
        {loading ? (
          <div style={{ padding: '3rem', textAlign: 'center', color: 'var(--primary-color)' }}>
            <div className="loading-spinner" style={{ margin: '0 auto 10px' }}></div>
            Cargando órdenes...
          </div>
        ) : flattenedLines.length === 0 ? (
          <div style={{ padding: '3rem', textAlign: 'center', color: 'var(--text-secondary)' }}>
            No se encontraron resultados.
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', minWidth: '1600px' }}>
            <thead>
              <tr>
                <th style={{ ...thBase, width: '40px', textAlign: 'center' }}>
                  <input
                    type="checkbox"
                    title="Seleccionar todos"
                    checked={selectedLineIds.size === flattenedLines.length && flattenedLines.length > 0}
                    onChange={toggleSelectAll}
                    style={{ cursor: 'pointer', transform: 'scale(1.15)' }}
                  />
                </th>
                <th style={thBase}>Tracking</th>
                <th style={thBase}>PO</th>
                <th style={thBase}>CUSTnbr</th>
                <th style={thBase}>Orddate</th>
                <th style={thBase}>Shipdate</th>
                <th style={thBase}>Deliver</th>
                <th style={thBase}>Shipto</th>
                <th style={thBase}>Shipto 2</th>
                <th style={thBase}>City</th>
                <th style={thBase}>State</th>
                <th style={thBase}>Item</th>
                <th style={thBase}>Producto</th>
                <th style={thBase}>Qty</th>
                <th style={thBase}>Farm</th>
                <th style={thBase}>AWB</th>
                <th style={thBase}>Estado</th>
                <th style={{ ...thBase, textAlign: 'center' }}>Acciones</th>
              </tr>
            </thead>
            
            <tbody>
              {flattenedLines.map((line, idx) => {
                const isEven = idx % 2 === 0;
                const itemCodeUpper = line.product.code.trim().toUpperCase();
                const prodInfo = knownProductMap.get(itemCodeUpper);
                const missingProduct = !prodInfo;
                const missingRecipe = prodInfo && !prodInfo.hasRecipe;
                const hasError = missingProduct || missingRecipe;
                const dateVal = validateOrderDates(line.order.creationDate, line.order.deliveryDate);
                
                const isSelected = selectedLineIds.has(line.id);
                
                let rowBg = isEven ? 'transparent' : 'rgba(0,0,0,0.015)';
                let rowOutline: string | undefined = undefined;
                let borderLeft = '3px solid transparent';

                const isCancelledOrder = line.status === 'CANCELLED' || line.order.status === 'CANCELLED';
                const isDuplicateOrder = Boolean(line.isDuplicate || line.order.isDuplicate);

                if (isSelected) {
                  rowBg = '#eff6ff';
                } else if (isCancelledOrder) {
                  // Cancelación: pintar toda la línea de rojo suave con borde rojo fuerte (netamente informativa)
                  rowBg = '#fee2e2';
                  rowOutline = '1.5px solid #f87171';
                  borderLeft = '6px solid #dc2626';
                } else if (isDuplicateOrder) {
                  rowBg = '#fff1f2';
                  rowOutline = '2px solid #fda4af';
                  borderLeft = '5px solid #e11d48';
                } else if (hasError) {
                  rowBg = '#fef2f2';
                  rowOutline = '2px solid #fca5a5';
                  borderLeft = '4px solid #ef4444';
                } else if (dateVal.isWeekendDelivery) {
                  // Entrega en Sábado o Domingo: pintar en amarillo con advertencia FedEx
                  rowBg = '#fef9c3';
                  rowOutline = '2px solid #facc15';
                  borderLeft = '5px solid #eab308';
                } else if (dateVal.isLeadTimeUrgent) {
                  // Entrega <= 4 días: resaltar en fondo ámbar claro con advertencia urgente
                  rowBg = '#fffbeb';
                  rowOutline = '1px solid #fde68a';
                  borderLeft = '4px solid #f59e0b';
                } else if (dateVal.isLeadTimeWarning) {
                  // Anticipación < 6 días: advertencia suave
                  rowBg = '#fefce8';
                  rowOutline = '1px solid #fef08a';
                  borderLeft = '3px solid #eab308';
                }

                return (
                  <tr key={line.id} style={{ backgroundColor: rowBg, outline: rowOutline, borderLeft }}>
                    <td style={{ ...tdBase, textAlign: 'center' }}>
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => toggleSelectLine(line.id)}
                        style={{ cursor: 'pointer' }}
                      />
                    </td>
                    <td style={{ ...tdBase, fontFamily: 'monospace', fontSize: '0.75rem', color: '#1d4ed8' }}>
                      {line.trackingNumber ? (
                        <a
                          href={
                            line.trackingNumber.startsWith('1Z')
                              ? `https://www.ups.com/track?tracknum=${line.trackingNumber}`
                              : `https://www.fedex.com/fedextrack/?trknbr=${line.trackingNumber}`
                          }
                          target="_blank"
                          rel="noopener noreferrer"
                          style={{ color: '#1d4ed8', textDecoration: 'underline', fontWeight: 700 }}
                          title="Ver rastreo oficial en tiempo real (FedEx / UPS)"
                        >
                          {line.trackingNumber} ↗
                        </a>
                      ) : (
                        '—'
                      )}
                    </td>
                    <td style={{ ...tdBase, fontWeight: 600, color: 'var(--primary-color)' }}>
                      <div>{line.order.po}</div>
                      {isDuplicateOrder && (
                        <span
                          style={{
                            display: 'inline-block',
                            fontSize: '0.65rem',
                            fontWeight: 800,
                            background: '#fee2e2',
                            color: '#991b1b',
                            border: '1px solid #f87171',
                            borderRadius: '4px',
                            padding: '0.1rem 0.35rem',
                            marginTop: '2px',
                            maxWidth: '180px',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap'
                          }}
                          title={line.duplicateInfo || line.order.duplicateInfo || 'Orden marcada como duplicada'}
                        >
                          ⚠️ {line.duplicateInfo || line.order.duplicateInfo || 'Duplicada'}
                        </span>
                      )}
                    </td>
                    <td style={{ ...tdBase, fontWeight: 700 }}>{line.order.orderNumber}</td>
                    
                    {/* Orddate con indicador de anticipación */}
                    <td style={tdBase}>
                      <div style={{ fontWeight: 500 }}>{formatDisplayDate(line.order.creationDate)}</div>
                      {dateVal.isLeadTimeUrgent ? (
                        <span
                          style={{
                            display: 'inline-block',
                            fontSize: '0.68rem',
                            fontWeight: 800,
                            background: '#fef3c7',
                            color: '#b45309',
                            border: '1px solid #f59e0b',
                            borderRadius: '4px',
                            padding: '0.1rem 0.35rem',
                            marginTop: '2px'
                          }}
                          title={dateVal.warningMessages.join(' | ')}
                        >
                          ⏳ {dateVal.leadTimeDays < 0 ? `${dateVal.leadTimeDays}d (Invertida)` : `≤4d (${dateVal.leadTimeDays}d)`}
                        </span>
                      ) : dateVal.isLeadTimeWarning ? (
                        <span
                          style={{
                            display: 'inline-block',
                            fontSize: '0.68rem',
                            fontWeight: 700,
                            background: '#fefce8',
                            color: '#a16207',
                            border: '1px solid #facc15',
                            borderRadius: '4px',
                            padding: '0.1rem 0.35rem',
                            marginTop: '2px'
                          }}
                          title={dateVal.warningMessages.join(' | ')}
                        >
                          ⚠️ &lt;6d ({dateVal.leadTimeDays}d)
                        </span>
                      ) : null}
                    </td>

                    {/* Shipdate */}
                    <td style={{ ...tdBase, fontFamily: 'monospace', fontWeight: 600, color: '#0f766e' }}>
                      {line.order.shipdt || (line.order.deliveryDate ? calculateShipDate(line.order.deliveryDate, line.order.service || 'FEDEX') : '—')}
                    </td>

                    {/* Deliver con badge si es Sábado o Domingo */}
                    <td style={{ ...tdBase, fontWeight: 600 }}>
                      <div style={{ color: dateVal.isWeekendDelivery ? '#854d0e' : '#d97706' }}>
                        {formatDisplayDate(line.order.deliveryDate)}
                      </div>
                      {dateVal.isWeekendDelivery && (
                        <span
                          style={{
                            display: 'inline-block',
                            fontSize: '0.68rem',
                            fontWeight: 800,
                            background: '#fef08a',
                            color: '#854d0e',
                            border: '1.5px solid #eab308',
                            borderRadius: '4px',
                            padding: '0.15rem 0.4rem',
                            marginTop: '2px',
                            letterSpacing: '0.02em'
                          }}
                          title="FedEx no tiene habilitadas entregas en fin de semana. Contactar al cliente para mover la fecha al siguiente día hábil."
                        >
                          ⚠️ {dateVal.weekendDayName?.toUpperCase()} (FedEx)
                        </span>
                      )}
                    </td>

                    <td style={{ ...tdBase, fontWeight: 600 }}>{line.order.shippingCustomer?.businessName || '—'}</td>
                    <td style={{ ...tdBase, fontWeight: 600 }}>{line.order.shippingCustomer?.contactName || '—'}</td>
                    <td style={tdBase}>{line.order.shippingCustomer?.city || '—'}</td>
                    <td style={tdBase}>{line.order.shippingCustomer?.state || '—'}</td>
                    
                    <td style={{ ...tdBase, fontFamily: 'monospace', fontWeight: 700, color: hasError ? '#dc2626' : 'var(--primary-color)' }}>
                      {line.product.code}
                      {missingProduct && <span title="Producto no encontrado" style={{ marginLeft: 4, fontSize: '0.7rem' }}>⚠</span>}
                    </td>
                    <td style={{ ...tdBase, color: hasError ? '#dc2626' : 'var(--text-secondary)' }}>
                      {prodInfo ? prodInfo.name : line.product.name}
                      {missingRecipe && <span title="Falta Receta" style={{ marginLeft: 4, fontSize: '0.7rem', color: '#dc2626', fontWeight: 600 }}>[Sin Receta]</span>}
                    </td>
                    
                    <td style={{ ...tdBase, textAlign: 'center', fontWeight: 'bold' }}>1</td>
                    <td style={{ ...tdBase, color: '#059669', fontWeight: 600 }}>{line.farm?.name || '—'}</td>
                    <td style={{ ...tdBase, fontFamily: 'monospace', fontSize: '0.72rem' }}>{line.order.awb || line.airwayBill || '—'}</td>
                    
                    <td style={{ ...tdBase }}>
                      {(() => {
                        const tag = getOrderStatusTag(line);
                        return (
                          <span style={{ backgroundColor: tag.bg, color: tag.color, padding: '0.2rem 0.5rem', borderRadius: '0.25rem', fontSize: '0.7rem', fontWeight: 700 }}>
                            {tag.label}
                          </span>
                        );
                      })()}
                    </td>

                    <td style={{ ...tdBase, textAlign: 'center' }}>
                      <div style={{ display: 'flex', gap: '0.35rem', justifyContent: 'center', flexWrap: 'wrap' }}>
                        <button
                          className="btn-secondary"
                          style={{ padding: '0.2rem 0.5rem', fontSize: '0.7rem', borderColor: '#3b82f6', color: '#1d4ed8' }}
                          onClick={() => setFullEditOrderId(line.order.id)}
                          title="Editar ficha completa de la orden"
                        >
                          Editar
                        </button>
                        <button
                          className="btn-secondary"
                          style={{ padding: '0.2rem 0.5rem', fontSize: '0.7rem', borderColor: '#8b5cf6', color: '#6d28d9' }}
                          onClick={() => openResend([line.id], line.order.deliveryDate)}
                          title="Reenviar / Reponer esta caja (genera orden con status NEW y valor $0.00)"
                        >
                          Reenviar
                        </button>
                        <button
                          className="btn-secondary"
                          style={{
                            padding: '0.2rem 0.5rem',
                            fontSize: '0.7rem',
                            borderColor: line.status === 'CANCELLED' ? '#e2e8f0' : '#f87171',
                            color: line.status === 'CANCELLED' ? '#94a3b8' : '#b91c1c'
                          }}
                          onClick={() => handleCancelLines([line.id])}
                          disabled={line.status === 'CANCELLED' || cancellingId === line.id}
                          title={line.status === 'CANCELLED' ? 'Línea ya cancelada' : 'Cancelar esta caja'}
                        >
                          {cancellingId === line.id ? '...' : 'Cancelar'}
                        </button>
                        <button
                          className="btn-secondary"
                          style={{ padding: '0.2rem 0.5rem', fontSize: '0.7rem', color: '#dc2626', borderColor: '#fca5a5' }}
                          onClick={() => handleDeleteLine(line.id)}
                          disabled={deletingId === line.id}
                          title="Eliminar orden / línea (Requiere autorización de Administrador)"
                        >
                          Eliminar
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>

          </table>
        )}
      </div>

      {flattenedLines.length > 0 && (
        <p style={{ marginTop: '0.75rem', color: 'var(--text-secondary)', fontSize: '0.8rem' }}>
          {flattenedLines.length} línea{flattenedLines.length !== 1 ? 's' : ''} — {orders.length} orden{orders.length !== 1 ? 'es' : ''} en total
        </p>
      )}

      {showDeleteAllModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
            <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '400px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)' }}>
              <h2 style={{ color: '#dc2626', fontSize: '1.25rem', fontWeight: 700, marginBottom: '1rem' }}>Borrar Todas las Órdenes</h2>
              <p style={{ fontSize: '0.9rem', marginBottom: '1rem', color: 'var(--text-secondary)' }}>Escribe <strong>borrar</strong> para confirmar:</p>
              <input type="text" className="input-field" placeholder="Escribe 'borrar'" value={deleteAllConfirm} onChange={(e) => setDeleteAllConfirm(e.target.value)} style={{ width: '100%', marginBottom: '1rem' }} />
              <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end' }}>
                <button className="btn-secondary" onClick={() => setShowDeleteAllModal(false)}>Cancelar</button>
                <button className="btn-primary" style={{ background: '#dc2626', borderColor: '#dc2626' }} disabled={deleteAllConfirm.toLowerCase() !== 'borrar' || saving} onClick={handleDeleteAll}>Borrar Todas</button>
              </div>
            </div>
          </div>
        </ModalPortal>
      )}

      {/* Modal de Progreso y Reloj para Eliminación Masiva */}
      {batchDeleting && (
        <ModalPortal>
          <div style={{
            position: 'fixed', inset: 0, zIndex: 9999,
            background: 'rgba(15, 23, 42, 0.75)', backdropFilter: 'blur(4px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem'
          }}>
            <div style={{
              background: '#fff', borderRadius: '16px', padding: '2.5rem',
              maxWidth: '480px', width: '90%', textAlign: 'center',
              boxShadow: '0 25px 50px -12px rgba(0,0,0,0.25)', border: '1px solid #e2e8f0'
            }}>
              <div style={{ fontSize: '3.5rem', marginBottom: '1rem', animation: 'spin 3s linear infinite' }}>
                ⏱️
              </div>
              <h2 style={{ fontSize: '1.4rem', fontWeight: 800, color: '#1e293b', marginBottom: '0.5rem' }}>
                Eliminando Órdenes del Sistema...
              </h2>
              <p style={{ color: '#64748b', fontSize: '0.95rem', marginBottom: '1.5rem', lineHeight: 1.5 }}>
                Procesando la eliminación de <strong>{batchDeleteCount}</strong> órdenes de forma segura. Por favor no cierres esta ventana.
              </p>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: '0.5rem',
                background: '#f8fafc', padding: '0.5rem 1.25rem', borderRadius: '30px',
                border: '1px solid #cbd5e1', fontSize: '0.9rem', fontWeight: 700, color: '#334155'
              }}>
                <span>⏳ Tiempo transcurrido:</span>
                <span style={{ fontFamily: 'monospace', color: '#dc2626' }}>
                  {Math.floor(batchDeleteSeconds / 60).toString().padStart(2, '0')}:{(batchDeleteSeconds % 60).toString().padStart(2, '0')}s
                </span>
              </div>
            </div>
          </div>
        </ModalPortal>
      )}

      {/* Modal de Confirmación Exitosa */}
      {batchDeleteSuccess && (
        <ModalPortal>
          <div style={{
            position: 'fixed', inset: 0, zIndex: 9999,
            background: 'rgba(15, 23, 42, 0.75)', backdropFilter: 'blur(4px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem'
          }}>
            <div style={{
              background: '#fff', borderRadius: '16px', padding: '2.5rem',
              maxWidth: '460px', width: '90%', textAlign: 'center',
              boxShadow: '0 25px 50px -12px rgba(0,0,0,0.25)', border: '1px solid #e2e8f0'
            }}>
              <div style={{ fontSize: '3.5rem', marginBottom: '1rem' }}>
                ✅
              </div>
              <h2 style={{ fontSize: '1.4rem', fontWeight: 800, color: '#166534', marginBottom: '0.5rem' }}>
                ¡Eliminación Completada!
              </h2>
              <p style={{ color: '#475569', fontSize: '0.95rem', marginBottom: '1.75rem', lineHeight: 1.5 }}>
                {batchDeleteSuccess}
              </p>
              <button
                className="btn-primary"
                onClick={() => setBatchDeleteSuccess(null)}
                style={{ padding: '0.65rem 2rem', fontSize: '0.95rem', width: '100%', justifyContent: 'center' }}
              >
                Entendido / Cerrar
              </button>
            </div>
          </div>
        </ModalPortal>
      )}

      {showEditLineModal && editingLine && (() => {
        const lineDateVal = validateOrderDates(editLineForm.date, editingLine.order.deliveryDate);
        return (
          <ModalPortal>
            <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
              <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '500px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
                <h2 style={{ fontSize: '1.25rem', fontWeight: 700, marginBottom: '1.25rem', color: 'var(--text-primary)' }}>Editar Línea de Orden</h2>

                {lineDateVal.hasWarning && (
                  <div style={{
                    padding: '0.6rem 0.85rem',
                    background: lineDateVal.isWeekendDelivery ? '#fef9c3' : '#fffbeb',
                    border: lineDateVal.isWeekendDelivery ? '1.5px solid #eab308' : '1px solid #f59e0b',
                    borderRadius: '8px',
                    fontSize: '0.78rem',
                    color: lineDateVal.isWeekendDelivery ? '#854d0e' : '#92400e',
                    marginBottom: '1rem',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '0.25rem'
                  }}>
                    {lineDateVal.warningMessages.map((msg, i) => (
                      <div key={i} style={{ fontWeight: 600 }}>⚠️ {msg}</div>
                    ))}
                  </div>
                )}

                <form onSubmit={handleSaveLineEdit}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1rem' }}>
                    <div><label style={{ fontSize: '0.8rem', fontWeight: 600 }}>PO</label><input className="input-field" value={editingLine.order.po} disabled /></div>
                    <div><label style={{ fontSize: '0.8rem', fontWeight: 600 }}>CUSTnbr</label><input className="input-field" value={editingLine.order.orderNumber} disabled /></div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1rem' }}>
                    <div><label style={{ fontSize: '0.8rem', fontWeight: 600 }}>Fecha</label><input type="date" className="input-field" required value={editLineForm.date} onChange={e => setEditLineForm({...editLineForm, date: e.target.value})} /></div>
                    <div><label style={{ fontSize: '0.8rem', fontWeight: 600 }}>Código Producto</label><input className="input-field" required value={editLineForm.productCode} onChange={e => setEditLineForm({...editLineForm, productCode: e.target.value})} /></div>
                  </div>
                  <div style={{ marginBottom: '1.5rem' }}>
                    <label style={{ fontSize: '0.8rem', fontWeight: 600 }}>Cajas (Qty)</label>
                    <input type="number" min="1" className="input-field" required value={editLineForm.quantity} onChange={e => setEditLineForm({...editLineForm, quantity: e.target.value})} />
                  </div>
                  <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end' }}>
                    <button type="button" className="btn-secondary" onClick={() => setShowEditLineModal(false)}>Cancelar</button>
                    <button type="submit" className="btn-primary" disabled={saving}>{saving ? 'Guardando...' : 'Guardar'}</button>
                  </div>
                </form>
              </div>
            </div>
          </ModalPortal>
        );
      })()}

      {isUploadModalOpen && <OrderUploadModal onClose={() => setIsUploadModalOpen(false)} onUploadSuccess={fetchOrders} />}
      
      {showMassTrackingModal && <MassTrackingModal onClose={() => setShowMassTrackingModal(false)} onSuccess={fetchOrders} />}
      
      {fullEditOrderId && <FullOrderEditModal orderId={fullEditOrderId} onClose={() => setFullEditOrderId(null)} onSuccess={fetchOrders} />}

      {/* Modal de Cambio Masivo de Fecha de Entrega */}
      {showBulkDateModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
            <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '480px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '1rem' }}>
                <span style={{ fontSize: '1.5rem' }}>📅</span>
                <h2 style={{ fontSize: '1.25rem', fontWeight: 800, color: 'var(--text-primary)', margin: 0 }}>
                  Cambio Masivo de Fecha de Entrega
                </h2>
              </div>
              <p style={{ fontSize: '0.85rem', color: '#64748b', marginBottom: '1.25rem', lineHeight: 1.5 }}>
                Se actualizará la fecha de entrega (Delivery Date) para <strong>{selectedLineIds.size} línea(s)</strong> seleccionada(s).
                El sistema recalculará automáticamente la fecha de vuelo (SHIPDATE) de acuerdo al calendario de la agencia.
              </p>

              <form onSubmit={handleApplyBulkDeliveryDate}>
                <div style={{ marginBottom: '1.25rem' }}>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.4rem', color: '#334155' }}>
                    Nueva Fecha de Entrega (Deliver) *
                  </label>
                  <input
                    type="date"
                    required
                    className="input-field"
                    value={bulkNewDeliveryDate}
                    onChange={(e) => setBulkNewDeliveryDate(e.target.value)}
                    style={{ width: '100%', fontSize: '0.95rem', padding: '0.6rem' }}
                  />
                  {bulkNewDeliveryDate && (() => {
                    const d = new Date(bulkNewDeliveryDate + 'T12:00:00Z');
                    const dayName = d.toLocaleDateString('es-EC', { weekday: 'long', timeZone: 'UTC' });
                    const isSunOrSat = d.getUTCDay() === 0 || d.getUTCDay() === 6;
                    const calculatedShipdt = calculateShipDate(bulkNewDeliveryDate, 'FEDEX');
                    return (
                      <div style={{ marginTop: '0.75rem', padding: '0.6rem 0.85rem', background: isSunOrSat ? '#fef9c3' : '#f0fdf4', border: `1px solid ${isSunOrSat ? '#facc15' : '#86efac'}`, borderRadius: '8px', fontSize: '0.8rem' }}>
                        <div style={{ fontWeight: 700, color: isSunOrSat ? '#854d0e' : '#166534' }}>
                          Día seleccionado: <span style={{ textTransform: 'capitalize' }}>{dayName}</span>
                        </div>
                        <div style={{ color: '#475569', marginTop: '0.2rem' }}>
                          ✈️ Nuevo SHIPDATE calculado: <strong>{calculatedShipdt}</strong>
                        </div>
                        {isSunOrSat && (
                          <div style={{ color: '#b45309', marginTop: '0.25rem', fontWeight: 600 }}>
                            ⚠️ Advertencia: Entrega en fin de semana requiere servicio especial o cambio a día hábil.
                          </div>
                        )}
                      </div>
                    );
                  })()}
                </div>

                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                  <button
                    type="button"
                    className="btn-secondary"
                    onClick={() => setShowBulkDateModal(false)}
                    disabled={bulkApplying}
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    className="btn-primary"
                    disabled={bulkApplying || !bulkNewDeliveryDate}
                    style={{ background: '#0284c7', borderColor: '#0284c7' }}
                  >
                    {bulkApplying ? 'Aplicando...' : `Actualizar ${selectedLineIds.size} Cajas`}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </ModalPortal>
      )}

      {/* Modal de Reenvío / Reposición de Cajas */}
      {showResendModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
            <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '520px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '1rem' }}>
                <span style={{ fontSize: '1.5rem' }}>🔁</span>
                <h2 style={{ fontSize: '1.25rem', fontWeight: 800, color: '#6d28d9', margin: 0 }}>
                  Reenvío / Reposición de Producto
                </h2>
              </div>
              <p style={{ fontSize: '0.85rem', color: '#64748b', marginBottom: '1.25rem', lineHeight: 1.5 }}>
                Se generará una orden nueva con <strong>{resendTargetIds.length} caja(s)</strong> seleccionada(s) con status <strong>NEW</strong>, sin fincas ni guías aéreas asignadas, y con <strong>precio $0.00</strong> por ser reposición gratuita al cliente.
              </p>

              <form onSubmit={handleConfirmResend}>
                <div style={{ marginBottom: '1rem' }}>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.35rem', color: '#334155' }}>
                    Motivo / Razón del Reenvío (Comentario obligatorio) *
                  </label>
                  <textarea
                    required
                    rows={3}
                    className="input-field"
                    value={resendReason}
                    onChange={(e) => setResendReason(e.target.value)}
                    placeholder="Ej: Cliente llamó 09-28-2026: caja de Freedom llegó dañada/marchita y se le reenvía producto nuevo gratis..."
                    style={{ width: '100%', fontSize: '0.85rem', resize: 'vertical' }}
                  />
                </div>

                <div style={{ marginBottom: '1.5rem' }}>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.35rem', color: '#334155' }}>
                    Nueva Fecha de Entrega (Opcional - dejar vacío para mantener fecha original)
                  </label>
                  <input
                    type="date"
                    className="input-field"
                    value={resendDeliveryDate}
                    onChange={(e) => setResendDeliveryDate(e.target.value)}
                    style={{ width: '100%', fontSize: '0.9rem' }}
                  />
                </div>

                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                  <button
                    type="button"
                    className="btn-secondary"
                    onClick={() => setShowResendModal(false)}
                    disabled={resending}
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    className="btn-primary"
                    disabled={resending || !resendReason.trim()}
                    style={{ background: '#7c3aed', borderColor: '#7c3aed' }}
                  >
                    {resending ? 'Generando Reenvío...' : `Confirmar Reenvío (${resendTargetIds.length} cajas)`}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </ModalPortal>
      )}

      {/* Modal de Verificación de Código Admin */}
      {showSecurityPinModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
            <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '420px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '1rem' }}>
                <span style={{ fontSize: '1.5rem' }}>🔒</span>
                <h2 style={{ fontSize: '1.25rem', fontWeight: 800, color: '#dc2626', margin: 0 }}>
                  Autorización de Administrador
                </h2>
              </div>
              <p style={{ fontSize: '0.85rem', color: '#64748b', marginBottom: '1.25rem', lineHeight: 1.5 }}>
                La eliminación de órdenes requiere un código de seguridad para verificar privilegios de Administrador.
              </p>

              <form onSubmit={handleVerifyPin}>
                <div style={{ marginBottom: '1rem' }}>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.35rem', color: '#334155' }}>
                    Código de Seguridad Admin *
                  </label>
                  <input
                    type="password"
                    autoFocus
                    required
                    placeholder="Ingresa tu clave de administrador..."
                    className="input-field"
                    value={securityPinInput}
                    onChange={(e) => {
                      setSecurityPinInput(e.target.value);
                      setSecurityPinError('');
                    }}
                    style={{ width: '100%', fontSize: '1rem', padding: '0.6rem' }}
                  />
                  {securityPinError && (
                    <div style={{ color: '#dc2626', fontSize: '0.78rem', marginTop: '0.4rem', fontWeight: 600 }}>
                      ⚠️ {securityPinError}
                    </div>
                  )}
                </div>

                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                  <button
                    type="button"
                    className="btn-secondary"
                    onClick={() => {
                      setShowSecurityPinModal(false);
                      setPendingAdminAction(null);
                    }}
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    className="btn-primary"
                    style={{ background: '#dc2626', borderColor: '#dc2626' }}
                  >
                    Verificar y Proceder
                  </button>
                </div>
              </form>
            </div>
          </div>
        </ModalPortal>
      )}

      <style>{`@keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </MainLayout>
  );
}
