<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSearcher, apiURL } from '@Services/Api';
import { page } from '@Services/Page';
import { formatCurrency } from '@/utils/formatters';
import { useBarcodeScanner } from '@/composables/useBarcodeScanner';
import useCart from '@Stores/cart';
import salesService from '@Services/salesService';
import ticketService from '@Services/ticketService';
import quoteService from '@Services/quoteService';
import serialService from '@Services/serialService';

import GoogleIcon from '@Shared/GoogleIcon.vue';
import ProductCard from '@Components/POS/ProductCard.vue';
import CartItem from '@Components/POS/CartItem.vue';
import CheckoutModal from '@Components/POS/CheckoutModal.vue';
import ClientModal from '@Components/POS/ClientModal.vue';
import QRscan from '@Components/POS/QRscan.vue';
import SerialSelector from '@Components/POS/SerialSelector.vue';
import BundleSerialSelector from '@Components/POS/BundleSerialSelector.vue';
import UnitEquivalenceSelector from '@Components/POS/UnitEquivalenceSelector.vue';

/** i18n */
const { t } = useI18n();

/** Stores */
const cart = useCart();

/** Estado */
const products = ref([]);
const productsMeta = ref(null);
const bundles = ref([]);
const bundlesMeta = ref(null);
const activeTab = ref('products'); // 'products' | 'bundles'
const showCheckoutModal = ref(false);
const searchQuery = ref('');
const processingPayment = ref(false);
const scanMode = ref(false);
const showClientModal = ref(false);
const lastSaleData = ref(null);

// Estado para selector de seriales
const showSerialSelector = ref(false);
const serialSelectorProduct = ref(null);

// Estado para selector de seriales de bundles
const showBundleSerialSelector = ref(false);
const bundleSerialSelectorBundle = ref(null);

// Estado para selector de equivalencias de unidad
const showUnitEquivalenceSelector = ref(false);
const unitEquivalenceSelectorProduct = ref(null);
const unitEquivalenceSelectorData = ref({ equivalences: [], baseUnit: null });
const equivalencesCache = ref({});
const mainWarehouseId = ref(null);

/** Buscador de productos */
const searcher = useSearcher({
    url: apiURL('inventario'),
    onSuccess: (r) => {
        products.value = Array.isArray(r.products) ? r.products : (r.products?.data || []);
        productsMeta.value = Array.isArray(r.products) ? null : (r.products || null);
        if (r.main_warehouse_id && !mainWarehouseId.value) {
            mainWarehouseId.value = r.main_warehouse_id;
        }
    },
    onError: () => {
        products.value = [];
        productsMeta.value = null;
        window.Notify.error(t('error.loading'));
    }
});

/** Buscador de bundles */
const bundleSearcher = useSearcher({
    url: apiURL('bundles'),
    onSuccess: (r) => {
        bundles.value = r.bundles?.data || [];
        bundlesMeta.value = r.bundles || null;
    },
    onError: () => {
        bundles.value = [];
        bundlesMeta.value = null;
        window.Notify.error(t('error.loading'));
    }
});

/** Métodos de búsqueda */
const doSearch = () => {
    searcher.query = searchQuery.value;
    searcher.load({
        url: mainWarehouseId.value
            ? apiURL(`inventario/almacen/${mainWarehouseId.value}`)
            : apiURL('inventario'),
        filters: {}
    });
};
const doBundleSearch = () => bundleSearcher.search(searchQuery.value);

/** Métodos */
const addBundleToCart = async (bundle) => {
    try {
        // Verificar stock actual del bundle antes de agregar
        const response = await fetch(
            apiURL(`bundles/${bundle.id}/check-stock?quantity=1`),
            {
                headers: {
                    'Authorization': `Bearer ${sessionStorage.token}`,
                    'Accept': 'application/json'
                }
            }
        );

        if (!response.ok) {
            window.Notify.error('Error al verificar stock del paquete');
            return;
        }

        const stockData = await response.json();
        const data = stockData.data || stockData;

        if (!data.has_stock || data.available_stock <= 0) {
            window.Notify.error(`El paquete "${bundle.name}" no tiene stock disponible`);
            return;
        }

        // Actualizar stock real del bundle antes de agregar al carrito
        bundle.available_stock = data.available_stock;

        // Verificar si ya está en el carrito y si alcanza el stock
        const existingItem = cart.items.find(i => i.item_key === 'b:' + bundle.id);
        if (existingItem && existingItem.quantity >= data.available_stock) {
            window.Notify.warning(`Solo hay ${data.available_stock} kit(s) disponible(s)`);
            return;
        }

        // Verificar si el bundle tiene componentes con seriales
        try {
            const components = await serialService.getBundleComponents(bundle.id);
            const hasSerialComponents = components.some(item => {
                const inv = item.inventory || item.product || {};
                return inv.track_serials || item.track_serials;
            });

            if (hasSerialComponents) {
                // Abrir selector de seriales para el bundle
                bundleSerialSelectorBundle.value = bundle;
                showBundleSerialSelector.value = true;
                return;
            }
        } catch {
            // Si falla la consulta de componentes, agregar sin seriales
        }

        // Agregar bundle/kit al carrito sin seriales
        cart.addBundle(bundle);
        window.Notify.success(`${bundle.name} agregado al carrito`);
    } catch (error) {
        console.error('Error verificando stock del bundle:', error);
        window.Notify.error('Error al verificar disponibilidad del paquete');
    }
};

const loadEquivalencesForProduct = async (productId) => {
    if (equivalencesCache.value[productId]) {
        return equivalencesCache.value[productId];
    }
    try {
        const response = await fetch(apiURL(`inventario/${productId}/equivalencias`), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });
        const result = await response.json();
        const data = {
            equivalences: (result.data?.equivalences || []).filter(e => e.is_active),
            baseUnit: result.data?.base_unit || null
        };
        equivalencesCache.value[productId] = data;
        return data;
    } catch {
        return { equivalences: [], baseUnit: null };
    }
};

const addToCart = async (product) => {
    try {
        const response = await serialService.getAvailableSerials(product.id);

        const allSerials = response.serials?.data || [];

        if (allSerials.length > 0) {
            // Verificar cuántos quedan después de excluir los del carrito
            const excluded = cart.getSelectedSerials();
            const available = allSerials.filter(s => !excluded.includes(s.serial_number));

            if (available.length === 0) {
                // Todos los seriales están bloqueados — buscar si un paquete del carrito los tiene
                const blockingBundle = cart.items.find(item => {
                    if (!item.is_bundle || !item.serial_numbers) return false;
                    const bundleSerials = item.serial_numbers[product.id] || [];
                    return bundleSerials.length > 0;
                });

                if (blockingBundle) {
                    window.Notify.warning(`"${product.name}" forma parte del paquete "${blockingBundle.product_name}". No hay suficiente stock para vender`);
                } else {
                    window.Notify.warning(`No hay seriales disponibles para "${product.name}"`);
                }
                return;
            }

            // Hay seriales disponibles — abrir selector
            product.track_serials = true;
            serialSelectorProduct.value = product;
            showSerialSelector.value = true;
            return;
        }

        // Si el producto ya está en el carrito (sin seriales), solo incrementar sin abrir selectores
        const existingItem = cart.items.find(i => i.item_key === 'p:' + product.id);
        if (existingItem && !existingItem.track_serials) {
            if (existingItem.quantity < existingItem.max_stock) {
                existingItem.quantity++;
                window.Notify.success(`${product.name} agregado al carrito`);
            } else {
                window.Notify.warning('No hay suficiente stock disponible');
            }
            return;
        }

        // Producto nuevo: verificar si tiene equivalencias activas
        const eqData = await loadEquivalencesForProduct(product.id);
        if (eqData.equivalences.length > 0) {
            unitEquivalenceSelectorProduct.value = product;
            unitEquivalenceSelectorData.value = eqData;
            showUnitEquivalenceSelector.value = true;
            return;
        }

        cart.addProduct(product);
        window.Notify.success(`${product.name} agregado al carrito`);
    } catch (error) {
        // Si el API falla, agregar sin seriales
        cart.addProduct(product);
        window.Notify.success(`${product.name} agregado al carrito`);
    }
};

const closeUnitEquivalenceSelector = () => {
    showUnitEquivalenceSelector.value = false;
    unitEquivalenceSelectorProduct.value = null;
};

const handleUnitEquivalenceConfirm = (unitConfig) => {
    if (!unitEquivalenceSelectorProduct.value) return;
    cart.addProduct(unitEquivalenceSelectorProduct.value, unitConfig);
    window.Notify.success(`${unitEquivalenceSelectorProduct.value.name} agregado al carrito`);
    closeUnitEquivalenceSelector();
};

const closeSerialSelector = () => {
    showSerialSelector.value = false;
    serialSelectorProduct.value = null;
};

const handleSerialConfirm = (serialConfig) => {
    if (!serialSelectorProduct.value) return;

    cart.addProductWithSerials(
        serialSelectorProduct.value,
        serialConfig.quantity,
        serialConfig
    );

    window.Notify.success(`${serialSelectorProduct.value.name} agregado al carrito`);
    closeSerialSelector();
};

const closeBundleSerialSelector = () => {
    showBundleSerialSelector.value = false;
    bundleSerialSelectorBundle.value = null;
};

const handleBundleSerialConfirm = (serialConfig) => {
    if (!bundleSerialSelectorBundle.value) return;

    cart.addBundle(bundleSerialSelectorBundle.value, serialConfig);
    window.Notify.success(`${bundleSerialSelectorBundle.value.name} agregado al carrito`);
    closeBundleSerialSelector();
};

const generateQuote = async () => {
    if (cart.isEmpty) {
        window.Notify.error('El carrito está vacío');
        return;
    }
    try {
        window.Notify.info('Generando cotización...');
        await quoteService.generate(
            cart.items,
            { subtotal: cart.subtotal, tax: cart.tax, total: cart.total },
            { autoDownload: true }
        );
        window.Notify.success('Cotización generada correctamente');
    } catch (e) {
        console.error('Error generando cotización:', e);
        window.Notify.error('Error al generar la cotización');
    }
};

const handleClearCart = () => {
    if (confirm(t('cart.clearConfirm'))) {
        cart.clear();
        window.Notify.success('Carrito vaciado');
    }
};

const openCheckout = () => {
    if (cart.isEmpty) {
        window.Notify.error('El carrito está vacío');
        return;
    }
    showCheckoutModal.value = true;
};

const closeCheckout = () => {
    showCheckoutModal.value = false;
};

const toggleScanMode = () => {
    scanMode.value = !scanMode.value;
    if(scanMode.value) {
        window.Notify.info('Modo escaneo activado');
    } else {
        window.Notify.info('Modo escaneo desactivado');
    }
};

const handleCodeDetected = async (barcode) => {
    if (!barcode || barcode.trim() === '') {
        window.Notify.error('Código de barras inválido');
        return;
    }

    try {
        window.Notify.info('Buscando producto...');

        // Intentar buscar como código de barras del producto
        const productResponse = await fetch(
            apiURL(`inventario?q=${encodeURIComponent(barcode)}`),
            {
                headers: {
                    'Authorization': `Bearer ${sessionStorage.token}`,
                    'Accept': 'application/json'
                }
            }
        );

        const productResult = await productResponse.json();

        if (productResult.data?.products?.data?.length > 0) {
            const product = productResult.data.products.data[0];

            const availableStock = product.main_warehouse_stock ?? product.stock;
            if (availableStock <= 0) {
                window.Notify.warning(`El producto "${product.name}" no tiene stock disponible`);
                return;
            }

            addToCart(product);
            return;
        }

        // Si no se encontró como producto, buscar como número de serie
        window.Notify.info('Buscando por número de serie...');

        const serialResponse = await fetch(
            apiURL(`serials/search?serial_number=${encodeURIComponent(barcode)}`),
            {
                headers: {
                    'Authorization': `Bearer ${sessionStorage.token}`,
                    'Accept': 'application/json'
                }
            }
        );

        const serialResult = await serialResponse.json();

        if (serialResult.data?.serial) {
            const serial = serialResult.data.serial;
            const product = serial.inventory;

            if (!product) {
                window.Notify.error('Producto del serial no encontrado');
                return;
            }

            if (serial.status !== 'disponible') {
                window.Notify.error(`Serial ${barcode} no está disponible (${serial.status})`);
                return;
            }

            // Agregar producto con ese serial específico
            product.track_serials = true;
            cart.addProductWithSerials(product, 1, {
                serialNumbers: [serial.serial_number],
                selectionMode: 'manual'
            });

            window.Notify.success(`${product.name} (SN: ${barcode}) agregado al carrito`);
            return;
        }

        window.Notify.error('Producto o serial no encontrado');

    } catch (error) {
        console.error('Error buscando producto:', error);
        window.Notify.error('Error al buscar el producto');
    }
};

const handleConfirmSale = async (paymentData) => {
    if (processingPayment.value) return;
    processingPayment.value = true;

    try {
        // Validar stock de bundles en el carrito antes de procesar
        const bundleItems = cart.items.filter(item => item.is_bundle);

        for (const item of bundleItems) {
            const response = await fetch(
                apiURL(`bundles/${item.bundle_id}/check-stock?quantity=${item.quantity}`),
                {
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.token}`,
                        'Accept': 'application/json'
                    }
                }
            );

            if (!response.ok) {
                window.Notify.error(`Error al verificar stock del paquete "${item.product_name}"`);
                processingPayment.value = false;
                return;
            }

            const stockData = await response.json();
            const data = stockData.data || stockData;

            if (!data.has_stock) {
                // Encontrar qué componente falta
                const insufficientComponents = (data.components_stock || [])
                    .filter(c => c.available_stock < c.required_quantity * item.quantity)
                    .map(c => c.product_name)
                    .join(', ');

                window.Notify.error(
                    `Stock insuficiente para "${item.product_name}". ` +
                    `Disponibles: ${data.available_stock} kit(s), Solicitados: ${item.quantity}. ` +
                    (insufficientComponents ? `Componentes sin stock: ${insufficientComponents}` : '')
                );
                processingPayment.value = false;
                return;
            }
        }

        // Continuar con la venta normalmente...
        // Establecer método de pago
        cart.setPaymentMethod(paymentData.paymentMethod);

        // Preparar datos de la venta
        const saleData = {
            user_id: page.user.id,
            subtotal: parseFloat(cart.subtotal.toFixed(2)),
            tax: parseFloat(cart.tax.toFixed(2)),
            total: parseFloat(cart.total.toFixed(2)), // El backend recalculará con descuento
            payment_method: paymentData.paymentMethod,
            items: cart.items.map(item => {
                if (item.is_bundle) {
                    const bundleItem = {
                        type: 'bundle',
                        bundle_id: item.bundle_id,
                        quantity: item.quantity,
                    };
                    if (item.track_serials && item.serial_numbers && Object.keys(item.serial_numbers).length > 0) {
                        bundleItem.serial_numbers = item.serial_numbers;
                    }
                    return bundleItem;
                }
                const productItem = {
                    type: 'product',
                    inventory_id: item.inventory_id,
                    product_name: item.product_name,
                    quantity: item.quantity,
                    unit_price: item.unit_price,
                    subtotal: parseFloat((item.quantity * item.unit_price).toFixed(2)),
                    serial_numbers: item.track_serials ? (item.serial_numbers || []) : undefined
                };
                if (item.unit_of_measure_id) {
                    productItem.unit_of_measure_id = item.unit_of_measure_id;
                }
                return productItem;
            })
        };

        // Agregar client_number si se seleccionó un cliente
        if (paymentData.clientNumber) {
            saleData.client_number = paymentData.clientNumber;
        }

        // Agregar cash_received si es pago en efectivo
        if (paymentData.paymentMethod === 'cash' && paymentData.cashReceived) {
            saleData.cash_received = parseFloat(paymentData.cashReceived.toFixed(2));
        }

        // Crear venta
        window.Notify.info('Procesando venta...');
        const response = await salesService.createSale(saleData);

        // Mostrar información del descuento aplicado si hay
        if (response.discount_amount && parseFloat(response.discount_amount) > 0) {
            window.Notify.success(
                `¡Descuento aplicado! -$${parseFloat(response.discount_amount).toFixed(2)} (${parseFloat(response.discount_percentage).toFixed(2)}%)`,
                '',
                5
            );
        }

        // Detectar upgrade/downgrade de tier
        if (paymentData.clientData?.tier?.tier_name && response.client?.tier?.tier_name) {
            const oldTier = paymentData.clientData.tier.tier_name;
            const newTier = response.client.tier.tier_name;

            if (oldTier !== newTier) {
                window.Notify.success(
                    `¡El cliente subió de nivel! ${oldTier} → ${newTier} (${response.client.tier.discount_percentage}% descuento)`,
                    '',
                    8
                );
            }
        }

        // Mostrar mensaje de éxito con cambio si es efectivo
        if (paymentData.paymentMethod === 'cash' && response.change !== undefined) {
            window.Notify.success(
                `¡Venta realizada! Cambio: $${parseFloat(response.change).toFixed(2)}`,
                '',
                8
            );
        } else {
            window.Notify.success('¡Venta realizada exitosamente!');
        }

        if (response && response.id) {
            try {
                // Mostrar notificación de que se está generando el ticket
                window.Notify.info('Generando ticket...');

                // Construir bundleMap desde los items del carrito (antes de limpiarlo)
                const bundleMap = {};
                cart.items.filter(i => i.is_bundle).forEach(item => {
                    bundleMap[item.bundle_id] = {
                        name: item.product_name,
                        sku: item.sku,
                        unit_price: item.unit_price
                    };
                });

                const unitMap = {};
                cart.items.filter(i => !i.is_bundle && i.unit_of_measure_id).forEach(item => {
                    unitMap[item.inventory_id] = {
                        unit_name: item.unit_name,
                        quantity: item.quantity
                    };
                });

                // Generar ticket PDF con descarga automática e impresión
                await ticketService.generateSaleTicket(response, {
                    businessName: 'HIKVISION DISTRIBUIDOR',
                    autoDownload: true,
                    autoPrint: false,
                    bundleMap,
                    unitMap
                });

                window.Notify.success('Ticket generado e impreso correctamente');
            } catch (ticketError) {
                console.error('Error generando ticket:', ticketError);
                window.Notify.warning('Venta registrada, pero hubo un error al generar el ticket');
            }
        }

        lastSaleData.value = {
            id: response.id,
            total: saleData.total,
            payment_method: saleData.payment_method
        };

        // Limpiar carrito DESPUÉS de generar el ticket
        cart.clear();

        // Cerrar modal
        showCheckoutModal.value = false;

        // Recargar productos para actualizar stock
        searcher.search();

        // Solo mostrar modal de registro de cliente si NO se asoció un cliente a la venta
        if (!paymentData.clientNumber) {
            showClientModal.value = true;
        }

    } catch (error) {
        console.error('Error en venta:', error);

        // Manejar errores de validación
        if (error.status === 422 && error.errors) {
            const errorMessages = Object.values(error.errors).flat();
            errorMessages.forEach(msg => window.Notify.error(msg));
        } else {
            window.Notify.error(error.message || t('cart.error'));
        }
    } finally {
        processingPayment.value = false;
    }
};

const closeClientModal = () => {
    showClientModal.value = false;
    lastSaleData.value = null;
};

/** Event listener para abrir selector de seriales */
const handleOpenSerialSelector = (event) => {
    const productId = event.detail.productId;
    const product = products.value.find(p => p.id === productId);
    if (product) {
        serialSelectorProduct.value = product;
        showSerialSelector.value = true;
    }
};

useBarcodeScanner({
  onScan: (barcode) => {
    // Reutilizar la misma lógica que ya tienes
    handleCodeDetected(barcode);
  },
  minLength: 5, // Ajusta según tus códigos de barras
  scanTimeout: 100
});

/** Ciclo de vida */
onMounted(() => {
    searcher.search();
    bundleSearcher.search();
    // Escuchar evento personalizado para abrir selector de seriales
    window.addEventListener('open-serial-selector', handleOpenSerialSelector);
});

onUnmounted(() => {
    window.removeEventListener('open-serial-selector', handleOpenSerialSelector);
});

watch(activeTab, (newTab) => {
    if (newTab === 'bundles') {
        doBundleSearch();
    }
});
</script>

<template>
    <div class="h-full">
        <!-- Header -->
        <div class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 mb-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <GoogleIcon name="point_of_sale" class="text-3xl text-indigo-600 dark:text-indigo-400" />
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                            {{ $t('pos.title') }}
                        </h1>
                        <p class="text-sm text-gray-600 dark:text-gray-400">
                            {{ $t('pos.subtitle') }}
                        </p>
                    </div>
                </div>
                <button
                    @click="toggleScanMode"
                    :class="[
                        'flex items-center gap-2 px-4 py-3 rounded-lg font-semibold transition-all',
                        scanMode
                            ? 'bg-red-500 hover:bg-red-600 text-white'
                            : 'bg-indigo-500 hover:bg-indigo-600 text-white'
                    ]"
                    type="button"
                >
                    <GoogleIcon :name="scanMode ? 'close' : 'qr_code_scanner'" class="text-xl" />
                    {{ scanMode ? 'Cerrar escáner' : 'Escanear código' }}
                </button>
            </div>
        </div>

        <!-- Contenido Principal -->
        <div class="flex gap-6 h-[calc(100%-120px)] px-6">
            <!-- Columna de Productos -->
            <div class="flex-1 flex flex-col overflow-hidden">
                <div v-if="scanMode" class="h-full">
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 p-6 h-full">
                        <div class="flex flex-col h-full">
                            <h2 class="text-xl font-bold text-gray-900 dark:text-gray-100 mb-4 flex items-center gap-2">
                                <GoogleIcon name="qr_code_scanner" class="text-2xl text-indigo-600" />
                                Escáner de Códigos de Barras
                            </h2>
                            <div class="flex-1 relative bg-gray-100 dark:bg-gray-900 rounded-lg overflow-hidden">
                                <QRscan 
                                    @qr-detected="handleCodeDetected"
                                    class="w-full h-full"
                                />
                            </div>
                            <div class="mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                                <p class="text-sm text-blue-800 dark:text-blue-300">
                                    <strong>Instrucciones:</strong> Coloca el código de barras frente a la cámara. 
                                    El producto se agregará automáticamente al carrito cuando se detecte.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Buscador + Tabs -->
                <div class="mb-3">
                    <div class="relative mb-3">
                        <input
                            v-model="searchQuery"
                            type="text"
                            placeholder="Buscar por nombre, SKU o código..."
                            class="w-full px-4 py-3 pl-12 pr-4 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:text-gray-100"
                            @keyup.enter="activeTab === 'products' ? doSearch() : doBundleSearch()"
                        />
                        <GoogleIcon
                            name="search"
                            class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-xl cursor-pointer hover:text-gray-600"
                            @click="activeTab === 'products' ? doSearch() : doBundleSearch()"
                        />
                    </div>
                    <!-- Tabs -->
                    <div class="flex gap-1">
                        <button
                            type="button"
                            @click="activeTab = 'products'"
                            class="flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors"
                            :class="activeTab === 'products'
                                ? 'bg-indigo-600 text-white'
                                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'"
                        >
                            Productos
                        </button>
                        <button
                            type="button"
                            @click="activeTab = 'bundles'"
                            class="flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors"
                            :class="activeTab === 'bundles'
                                ? 'bg-purple-600 text-white'
                                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'"
                        >
                            Paquetes / Kits
                        </button>
                    </div>
                </div>

                <!-- Grid de Productos -->
                <div v-if="activeTab === 'products'" class="flex-1 overflow-y-auto">
                    <div v-if="products.length === 0 && !searcher.processing" class="flex items-center justify-center h-full">
                        <div class="text-center">
                            <GoogleIcon name="inventory_2" class="text-6xl text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                            <p class="text-gray-500 dark:text-gray-400">
                                {{ searchQuery ? 'No se encontraron productos' : 'No hay productos disponibles' }}
                            </p>
                        </div>
                    </div>
                    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 pb-4">
                        <ProductCard
                            v-for="product in products"
                            :key="product.id"
                            :product="product"
                            @add-to-cart="addToCart"
                        />
                    </div>
                    <!-- Paginación productos -->
                    <div
                        v-if="productsMeta && productsMeta.last_page > 1"
                        class="flex items-center justify-between px-2 py-3 border-t border-gray-200 dark:border-gray-700 mt-2"
                    >
                        <button
                            :disabled="!productsMeta.prev_page_url || searcher.processing"
                            @click="searcher.pagination(productsMeta.prev_page_url)"
                            class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                        >
                            <GoogleIcon name="chevron_left" class="text-lg" />
                            Anterior
                        </button>
                        <span class="text-xs text-gray-500 dark:text-gray-400">
                            Página {{ productsMeta.current_page }} de {{ productsMeta.last_page }}
                        </span>
                        <button
                            :disabled="!productsMeta.next_page_url || searcher.processing"
                            @click="searcher.pagination(productsMeta.next_page_url)"
                            class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                        >
                            Siguiente
                            <GoogleIcon name="chevron_right" class="text-lg" />
                        </button>
                    </div>
                </div>

                <!-- Grid de Bundles -->
                <div v-else class="flex-1 overflow-y-auto">
                    <div v-if="bundles.length === 0 && !bundleSearcher.processing" class="flex items-center justify-center h-full">
                        <div class="text-center">
                            <GoogleIcon name="inventory_2" class="text-6xl text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                            <p class="text-gray-500 dark:text-gray-400">
                                {{ searchQuery ? 'No se encontraron paquetes' : 'No hay paquetes disponibles' }}
                            </p>
                        </div>
                    </div>
                    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 pb-4">
                        <ProductCard
                            v-for="bundle in bundles"
                            :key="bundle.id"
                            :product="{ ...bundle, stock: bundle.available_stock, category: { name: 'Paquete/Kit' } }"
                            @add-to-cart="() => addBundleToCart(bundle)"
                        />
                    </div>
                    <!-- Paginación bundles -->
                    <div
                        v-if="bundlesMeta && bundlesMeta.last_page > 1"
                        class="flex items-center justify-between px-2 py-3 border-t border-gray-200 dark:border-gray-700 mt-2"
                    >
                        <button
                            :disabled="!bundlesMeta.prev_page_url || bundleSearcher.processing"
                            @click="bundleSearcher.pagination(bundlesMeta.prev_page_url)"
                            class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                        >
                            <GoogleIcon name="chevron_left" class="text-lg" />
                            Anterior
                        </button>
                        <span class="text-xs text-gray-500 dark:text-gray-400">
                            Página {{ bundlesMeta.current_page }} de {{ bundlesMeta.last_page }}
                        </span>
                        <button
                            :disabled="!bundlesMeta.next_page_url || bundleSearcher.processing"
                            @click="bundleSearcher.pagination(bundlesMeta.next_page_url)"
                            class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                        >
                            Siguiente
                            <GoogleIcon name="chevron_right" class="text-lg" />
                        </button>
                    </div>
                </div>
            </div>

            <!-- Panel del Carrito -->
            <div class="w-96 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 flex flex-col">
                <!-- Header del Carrito -->
                <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <h2 class="text-lg font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
                            <GoogleIcon name="shopping_cart" class="text-2xl text-indigo-600" />
                            {{ $t('cart.title') }}
                        </h2>
                        <span class="px-3 py-1 bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 text-sm font-semibold rounded-full">
                            {{ cart.itemCount }} {{ cart.itemCount === 1 ? 'item' : 'items' }}
                        </span>
                    </div>
                </div>

                <!-- Items del Carrito -->
                <div class="flex-1 overflow-y-auto p-4 space-y-3">
                    <div v-if="cart.isEmpty" class="flex flex-col items-center justify-center h-full text-center py-12">
                        <GoogleIcon name="shopping_cart" class="text-6xl text-gray-300 dark:text-gray-600 mb-4" />
                        <p class="text-gray-500 dark:text-gray-400 font-medium">
                            {{ $t('cart.empty') }}
                        </p>
                        <p class="text-sm text-gray-400 dark:text-gray-500 mt-2">
                            {{ $t('cart.emptyMessage') }}
                        </p>
                    </div>

                    <CartItem
                        v-for="item in cart.items"
                        :key="item.item_key"
                        :item="item"
                        @update-quantity="cart.updateQuantity"
                        @remove="cart.removeProduct"
                    />
                </div>

                <!-- Resumen y Botones -->
                <div class="p-4 border-t border-gray-200 dark:border-gray-700 space-y-4">
                    <!-- Totales -->
                    <div class="space-y-2">
                        <div class="flex justify-between text-sm text-gray-600 dark:text-gray-400">
                            <span>{{ $t('cart.subtotal') }}</span>
                            <span class="font-semibold">{{ formatCurrency(cart.subtotal) }}</span>
                        </div>
                        <div class="flex justify-between text-sm text-gray-600 dark:text-gray-400">
                            <span>IVA (16%)</span>
                            <span class="font-semibold">{{ formatCurrency(cart.tax) }}</span>
                        </div>
                        <div class="pt-2 border-t border-gray-200 dark:border-gray-700">
                            <div class="flex justify-between items-center">
                                <span class="text-base font-bold text-gray-900 dark:text-gray-100">
                                    {{ $t('cart.total') }}
                                </span>
                                <span class="text-2xl font-bold text-indigo-600 dark:text-indigo-400">
                                    {{ formatCurrency(cart.total) }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- Botones de Acción -->
                    <div class="space-y-2">
                        <button
                            type="button"
                            class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-300 disabled:cursor-not-allowed text-white text-base font-semibold rounded-lg transition-colors shadow-lg"
                            :disabled="cart.isEmpty"
                            @click="openCheckout"
                        >
                            <GoogleIcon name="point_of_sale" class="text-xl" />
                            {{ $t('cart.checkout') }}
                        </button>

                        <button
                            type="button"
                            class="w-full flex items-center justify-center gap-2 px-4 py-2 text-emerald-600 dark:text-emerald-400 hover:bg-emerald-50 dark:hover:bg-emerald-900/20 disabled:text-gray-400 disabled:cursor-not-allowed text-sm font-semibold rounded-lg transition-colors"
                            :disabled="cart.isEmpty"
                            @click="generateQuote"
                        >
                            <GoogleIcon name="request_quote" class="text-lg" />
                            Cotizar
                        </button>

                        <button
                            type="button"
                            class="w-full flex items-center justify-center gap-2 px-4 py-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:text-gray-400 disabled:cursor-not-allowed text-sm font-semibold rounded-lg transition-colors"
                            :disabled="cart.isEmpty"
                            @click="handleClearCart"
                        >
                            <GoogleIcon name="delete_sweep" class="text-lg" />
                            {{ $t('cart.clear') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal de Checkout -->
        <CheckoutModal
            :show="showCheckoutModal"
            :cart="cart"
            :processing="processingPayment"
            @close="closeCheckout"
            @confirm="handleConfirmSale"
        />
        <ClientModal
            :show="showClientModal"
            :sale-data="lastSaleData"
            @close="closeClientModal"
        />

        <!-- Modal de Selección de Seriales -->
        <SerialSelector
            v-if="serialSelectorProduct"
            :show="showSerialSelector"
            :product="serialSelectorProduct"
            :exclude-serials="cart.getSelectedSerials()"
            :main-warehouse="true"
            @close="closeSerialSelector"
            @confirm="handleSerialConfirm"
        />

        <!-- Modal de Selección de Seriales para Bundles -->
        <BundleSerialSelector
            v-if="bundleSerialSelectorBundle"
            :show="showBundleSerialSelector"
            :bundle="bundleSerialSelectorBundle"
            :exclude-serials="cart.getSelectedSerials()"
            :main-warehouse="true"
            @close="closeBundleSerialSelector"
            @confirm="handleBundleSerialConfirm"
        />

        <!-- Modal de Selección de Unidad de Medida -->
        <UnitEquivalenceSelector
            v-if="unitEquivalenceSelectorProduct"
            :show="showUnitEquivalenceSelector"
            :product="unitEquivalenceSelectorProduct"
            :equivalences="unitEquivalenceSelectorData.equivalences"
            :base-unit="unitEquivalenceSelectorData.baseUnit"
            @close="closeUnitEquivalenceSelector"
            @confirm="handleUnitEquivalenceConfirm"
        />
    </div>
</template>
