@extends('layouts.app')
@section('title', 'Barcode/IMEI Scanner')
@section('header', 'Product Scanner')
@section('subheader', 'Scan products to add them to the inventory.')

@section('content')
    <div class="min-h-screen py-6 bg-gray-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <!-- Scanner Header -->
            <div class="bg-gradient-to-r from-primary to-purple-600 rounded-xl p-8 text-white mb-8 shadow-lg">
                <h1 class="text-2xl sm:text-3xl font-extrabold flex items-center">
                    <i class="fas fa-qrcode mr-3"></i>Barcode/IMEI Scanner
                </h1>
                <p class="mt-2 text-blue-100 text-sm sm:text-base">Scan or manually enter product codes to add them to the
                    database</p>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Scanner Interface -->
                <div class="lg:col-span-2">
                    <div class="bg-white rounded-xl shadow-md p-6">
                        <!-- Camera Scanner -->
                        <div class="mb-8">
                            <h2 class="text-lg sm:text-xl font-semibold mb-4 text-gray-800">
                                <i class="fas fa-camera mr-2"></i>Camera Scanner
                            </h2>
                            <div id="camera-scanner"
                                class="border-2 border-dashed border-gray-300 rounded-xl p-4 text-center">
                                <div id="reader" class="w-full h-64 sm:h-80 mx-auto"></div>
                                <div id="scanner-message" class="text-sm mt-2 text-center p-2 rounded"></div>
                                <div id="scanner-loading" class="text-primary text-sm mt-2 text-center hidden">
                                    <i class="fas fa-spinner fa-spin mr-2"></i> Starting camera...
                                </div>
                                <div class="mt-4 flex flex-wrap justify-center gap-3">
                                    <button id="start-camera"
                                        class="bg-primary text-white px-5 py-2.5 rounded-lg hover:bg-primary/90 transition duration-200 text-sm sm:text-base font-medium">
                                        <i class="fas fa-camera mr-2"></i>Start Camera
                                    </button>
                                    <button id="stop-camera"
                                        class="bg-red-500 text-white px-5 py-2.5 rounded-lg hover:bg-red-600 transition duration-200 text-sm sm:text-base font-medium hidden">
                                        <i class="fas fa-stop mr-2"></i>Stop Camera
                                    </button>
                                </div>
                                <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                                    <p class="text-xs text-yellow-800 text-center">
                                        <strong>Browser Support:</strong> Chrome, Firefox, Edge, Safari (iOS 15+), Samsung
                                        Internet
                                        <br><a href="https://support.google.com/chrome/answer/2693767" target="_blank"
                                            class="text-primary hover:underline">How to enable camera access</a>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Manual Input -->
                        <div class="mb-8">
                            <h2 class="text-lg sm:text-xl font-semibold mb-4 text-gray-800">
                                <i class="fas fa-keyboard mr-2"></i>Manual Input
                            </h2>
                            <div class="flex flex-col sm:flex-row gap-3">
                                <input type="text" id="manual-scan" placeholder="Enter Barcode, IMEI, or Serial Number"
                                    class="flex-grow px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary text-sm sm:text-base">
                                <button id="manual-scan-btn"
                                    class="bg-primary text-white px-5 py-3 rounded-lg hover:bg-primary/90 transition duration-200 text-sm sm:text-base font-medium">
                                    <i class="fas fa-paper-plane mr-2"></i>Submit
                                </button>
                            </div>
                            <p class="text-xs sm:text-sm text-gray-600 mt-2">Press Enter or click Submit to process</p>
                        </div>

                        <!-- Hardware Scanner Simulation -->
                        <div>
                            <h2 class="text-lg sm:text-xl font-semibold mb-4 text-gray-800">
                                <i class="fas fa-barcode mr-2"></i>Test Scanner
                            </h2>
                            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                                <button onclick="simulateScan('imei')"
                                    class="bg-purple-600 text-white p-4 rounded-lg hover:bg-purple-700 transition duration-200 flex items-center justify-center text-sm sm:text-base font-medium">
                                    <i class="fas fa-mobile-alt mr-2"></i>Scan IMEI
                                </button>
                                <button onclick="simulateScan('serial')"
                                    class="bg-indigo-600 text-white p-4 rounded-lg hover:bg-indigo-700 transition duration-200 flex items-center justify-center text-sm sm:text-base font-medium">
                                    <i class="fas fa-barcode mr-2"></i>Scan Serial
                                </button>
                                <button onclick="simulateScan('barcode')"
                                    class="bg-pink-600 text-white p-4 rounded-lg hover:bg-pink-700 transition duration-200 flex items-center justify-center text-sm sm:text-base font-medium">
                                    <i class="fas fa-qrcode mr-2"></i>Scan Barcode
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Scan Results -->
                <div class="lg:col-span-1">
                    <div class="bg-white rounded-xl shadow-md p-6 h-full">
                        <h2 class="text-lg sm:text-xl font-semibold mb-4 text-gray-800">
                            <i class="fas fa-history mr-2"></i>Scan Results
                        </h2>
                        <div id="scan-results" class="space-y-3 max-h-[400px] overflow-y-auto">
                            <div class="text-center text-gray-500 py-8">
                                <i class="fas fa-inbox text-2xl sm:text-3xl mb-2"></i>
                                <p class="text-sm sm:text-base">No scans yet</p>
                                <p class="text-xs sm:text-sm">Scanning results will appear here</p>
                            </div>
                        </div>
                        <div class="mt-4 text-center">
                            <button id="clear-results" class="text-gray-600 hover:text-gray-800 text-sm font-medium">
                                <i class="fas fa-trash mr-1"></i>Clear All
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Statistics -->
            <div class="mt-8 grid grid-cols-1 sm:grid-cols-3 gap-4 sm:gap-6">
                <div class="bg-white rounded-xl shadow-md p-6 text-center">
                    <div class="text-2xl sm:text-3xl font-bold text-primary" id="total-scans">0</div>
                    <div class="text-gray-600 mt-1 text-sm sm:text-base">Total Scans</div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 text-center">
                    <div class="text-2xl sm:text-3xl font-bold text-green-600" id="successful-scans">0</div>
                    <div class="text-gray-600 mt-1 text-sm sm:text-base">Successful</div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 text-center">
                    <div class="text-2xl sm:text-3xl font-bold text-red-600" id="failed-scans">0</div>
                    <div class="text-gray-600 mt-1 text-sm sm:text-base">Failed</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Product Creation Modal -->
    <div id="product-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-10 mx-auto p-4 sm:p-5 border w-full max-w-4xl shadow-lg rounded-md bg-white my-12">
            <div class="flex justify-between items-center pb-3 border-b mb-5">
                <h3 class="text-xl sm:text-2xl font-bold text-gray-800">Create New Product</h3>
                <button id="close-modal-btn" class="text-gray-600 hover:text-gray-900">
                    <i class="fas fa-times fa-lg"></i>
                </button>
            </div>
            <div>
                <form id="product-form" class="space-y-6">
                    <div id="modal-errors" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-4 hidden"
                        role="alert"></div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="product_name" class="block text-sm font-medium text-gray-700">Product Name</label>
                            <input type="text" name="product_name" id="product_name" list="product_names_list"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                            <datalist id="product_names_list">
                                @foreach($productNames as $name)
                                    <option value="{{ $name }}">
                                @endforeach
                            </datalist>
                        </div>
                        <div>
                            <label for="serial_no" class="block text-sm font-medium text-gray-700">Serial No</label>
                            <input type="text" name="serial_no" id="serial_no"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary bg-gray-100"
                                readonly>
                        </div>
                        <div>
                            <label for="imei" class="block text-sm font-medium text-gray-700">IMEI</label>
                            <input type="text" name="imei" id="imei"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                            <select name="status" id="status"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                                <option value="In Warehouse" selected>In Warehouse</option>
                                <option value="Shipped">Shipped</option>
                                <option value="Delivered">Delivered</option>
                                <option value="Sold">Sold</option>
                                <option value="Returned">Returned</option>
                            </select>
                        </div>
                        <div>
                            <label for="condition" class="block text-sm font-medium text-gray-700">Condition</label>
                            <select name="condition" id="condition"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                                <option value="New" selected>New</option>
                                <option value="Used">Used</option>
                                <option value="Refurbished">Refurbished</option>
                            </select>
                        </div>
                        <div>
                            <label for="quality" class="block text-sm font-medium text-gray-700">Quality</label>
                            <select name="quality" id="quality"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                                <option value="Authentic" selected>Authentic</option>
                                <option value="Premium">Premium</option>
                                <option value="Standard">Standard</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Color</label>
                            <input type="hidden" name="color[]" id="color" value="Unknown">
                            <div id="color-options-container" class="mt-2 flex flex-wrap gap-2">
                                <!-- Color options will be populated by JS -->
                                <p class="text-xs text-gray-500">Select a product name to see available colors.</p>
                            </div>
                        </div>
                        <div>
                            <label for="distributor_name" class="block text-sm font-medium text-gray-700">Distributor
                                Name</label>
                            <input type="text" name="distributor_name" id="distributor_name"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="retailer_name" class="block text-sm font-medium text-gray-700">Retailer
                                Name</label>
                            <input type="text" name="retailer_name" id="retailer_name"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div class="md:col-span-1">
                            <label for="description" class="block text-sm font-medium text-gray-700">Product Description</label>
                            <textarea name="description" id="description" rows="3"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary"></textarea>
                        </div>
                    </div>
                    <div
                        class="mt-8 flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-4 space-y-4 space-y-reverse sm:space-y-0">
                        <button type="button" id="cancel-modal-btn"
                            class="w-full sm:w-auto justify-center text-center bg-secondary text-white px-6 py-2 rounded-lg hover:bg-opacity-90 transition-colors">
                            Cancel
                        </button>
                        <button type="submit"
                            class="w-full sm:w-auto justify-center bg-primary text-white px-6 py-2 rounded-lg hover:bg-opacity-90 transition-colors flex items-center">
                            <i class="fas fa-save mr-2"></i>Create Product
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Product Edit Modal -->
    <div id="product-edit-modal"
        class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-10 mx-auto p-5 border w-full max-w-4xl shadow-lg rounded-md bg-white">
            <div class="flex justify-between items-center pb-3 border-b">
                <h3 class="text-2xl font-bold text-gray-800">Edit Product</h3>
                <button id="close-edit-modal-btn" class="text-gray-600 hover:text-gray-900">
                    <i class="fas fa-times fa-lg"></i>
                </button>
            </div>
            <div class="mt-5">
                <form id="product-edit-form">
                    @method('PUT')
                    <div id="edit-modal-errors" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-4 hidden"
                        role="alert"></div>
                    <input type="hidden" id="edit_product_id" name="product_id">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="edit_product_name" class="block text-sm font-medium text-gray-700">Product
                                Name</label>
                            <input type="text" name="product_name" id="edit_product_name" list="product_names_list"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                            <datalist id="product_names_list">
                                @foreach($productNames as $name)
                                    <option value="{{ $name }}">
                                @endforeach
                            </datalist>
                        </div>
                        <div>
                            <label for="edit_serial_no" class="block text-sm font-medium text-gray-700">Serial No</label>
                            <input type="text" name="serial_no" id="edit_serial_no"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="edit_imei" class="block text-sm font-medium text-gray-700">IMEI</label>
                            <input type="text" name="imei" id="edit_imei"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="edit_status" class="block text-sm font-medium text-gray-700">Status</label>
                            <select name="status" id="edit_status"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                                <option value="In Warehouse">In Warehouse</option>
                                <option value="Shipped">Shipped</option>
                                <option value="Delivered">Delivered</option>
                                <option value="Sold">Sold</option>
                                <option value="Returned">Returned</option>
                            </select>
                        </div>
                        <div>
                            <label for="edit_condition" class="block text-sm font-medium text-gray-700">Condition</label>
                            <select name="condition" id="edit_condition"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                                <option value="New">New</option>
                                <option value="Used">Used</option>
                                <option value="Refurbished">Refurbished</option>
                            </select>
                        </div>
                        <div>
                            <label for="edit_quality" class="block text-sm font-medium text-gray-700">Quality</label>
                            <select name="quality" id="edit_quality"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                                <option value="Authentic">Authentic</option>
                                <option value="Premium">Premium</option>
                                <option value="Standard">Standard</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Color</label>
                            <input type="hidden" name="color[]" id="edit_color" value="Unknown">
                            <div id="edit_color-options-container" class="mt-2 flex flex-wrap gap-2">
                                <!-- Color options will be populated by JS -->
                                <p class="text-xs text-gray-500">Select a product name to see available colors.</p>
                            </div>
                        </div>
                        <div>
                            <label for="edit_distributor_name" class="block text-sm font-medium text-gray-700">Distributor
                                Name</label>
                            <input type="text" name="distributor_name" id="edit_distributor_name"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div>
                            <label for="edit_retailer_name" class="block text-sm font-medium text-gray-700">Retailer
                                Name</label>
                            <input type="text" name="retailer_name" id="edit_retailer_name"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                        </div>
                        <div class="md:col-span-2">
                            <label for="edit_description" class="block text-sm font-medium text-gray-700">Product Description</label>
                            <textarea name="description" id="edit_description" rows="3"
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary"></textarea>
                        </div>
                    </div>
                    <div class="mt-8 flex justify-end space-x-4">
                        <button type="button" id="cancel-edit-modal-btn"
                            class="bg-secondary text-white px-6 py-2 rounded-lg hover:bg-opacity-90 transition-colors">Cancel</button>
                        <button type="submit"
                            class="bg-primary text-white px-6 py-2 rounded-lg hover:bg-opacity-90 transition-colors flex items-center">
                            <i class="fas fa-save mr-2"></i>Update Product
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    @php
        // Ensure 'Unknown' is part of the color list and create a unique, sorted list for JS
        $defaultColorList = ['Black', 'White', 'Silver', 'Gray', 'Red', 'Blue', 'Green', 'Gold', 'Cyan', 'Pink', 'Other'];
        $allExistingColors = collect($productColors)->prepend('Unknown');
        $mergedColors = $allExistingColors->merge($defaultColorList)->unique()->sort()->values();
        $allColorsJson = $mergedColors->toJson();
    @endphp
    <!-- Load html5-qrcode (local if available, else CDN) -->
    @if (file_exists(public_path('js/html5-qrcode.min.js')))
        <script src="{{ asset('js/html5-qrcode.min.js') }}"></script>
    @else
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js"></script>
    @endif
    <!-- Load JsBarcode for simulation -->
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>

    <script>
        let html5QrcodeScanner = null;
        let stats = {
            total: 0,
            successful: 0,
            failed: 0
        };
        let isProcessing = false;
        let scannedItems = new Set();

        document.addEventListener('DOMContentLoaded', function() {
            const startCameraBtn = document.getElementById('start-camera');
            const stopCameraBtn = document.getElementById('stop-camera');
            const scannerMessage = document.getElementById('scanner-message');
            const scannerLoading = document.getElementById('scanner-loading');

            // Check for required DOM elements
            if (!startCameraBtn || !stopCameraBtn || !scannerMessage || !scannerLoading) {
                console.error('Required DOM elements missing.');
                showMessage('Error: Page elements not found. Please refresh.', 'error');
                return;
            }

            // Check for getUserMedia support
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                showMessage('Error: Browser does not support camera access. Use Chrome/Firefox.', 'error');
                startCameraBtn.disabled = true;
                return;
            }

            // Check for HTTPS or localhost
            if (window.location.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(window.location
                    .hostname)) {
                showMessage('Error: Camera requires a secure connection (HTTPS).', 'error');
                startCameraBtn.disabled = true;
                return;
            }

            // Check if Html5Qrcode is available
            if (typeof Html5Qrcode === 'undefined') {
                showMessage('Error: QR scanner library failed to load. Check internet or server config.', 'error');
                startCameraBtn.disabled = true;
                return;
            }

            // Event listeners
            startCameraBtn.addEventListener('click', startCameraScanner);
            stopCameraBtn.addEventListener('click', stopCameraScanner);
            document.getElementById('manual-scan-btn').addEventListener('click', processManualScan);
            document.getElementById('manual-scan').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    processManualScan();
                }
            });
            document.getElementById('clear-results').addEventListener('click', clearResults);
            document.getElementById('manual-scan').focus();

            // Modal listeners
            const modal = document.getElementById('product-modal');
            document.getElementById('close-modal-btn').addEventListener('click', () => modal.classList.add(
                'hidden'));
            document.getElementById('cancel-modal-btn').addEventListener('click', () => modal.classList.add(
                'hidden'));
            document.getElementById('product-form').addEventListener('submit', submitProductForm);

            const editModal = document.getElementById('product-edit-modal');
            document.getElementById('close-edit-modal-btn').addEventListener('click', () => editModal.classList.add(
                'hidden'));
            document.getElementById('cancel-edit-modal-btn').addEventListener('click', () => editModal.classList
                .add('hidden'));
            document.getElementById('product-edit-form').addEventListener('submit', submitProductEditForm);

            // Add event listener for product name change to fetch colors
            const productNameInput = document.getElementById('product_name');
            if (productNameInput) {
                productNameInput.addEventListener('change', (event) => handleProductNameChange(event, 'color-options-container', 'color'));
            }

            const editProductNameInput = document.getElementById('edit_product_name');
            if (editProductNameInput) {
                editProductNameInput.addEventListener('change', (event) => handleProductNameChange(event, 'edit_color-options-container', 'edit_color'));
            }

            // Cleanup on page unload
            window.addEventListener('beforeunload', stopCameraScanner);
        });

        function colorNameToHex(colorName) {
            const map = {
                'black': '#1e293b', 'white': '#ffffff', 'silver': '#e2e8f0', 'gray': '#64748b',
                'red': '#ef4444', 'blue': '#3b82f6', 'green': '#22c55e', 'gold': '#facc15',
                'cyan': '#22d3ee', 'pink': '#ec4899', 'purple': '#8b5cf6', 'blue ae': '#4F86F7',
                // Add more colors as needed, these are tailwind-like colors
            };
            const lowerColorName = colorName.toLowerCase();
            if (map[lowerColorName]) {
                return map[lowerColorName];
            }
            return lowerColorName; // Fallback to CSS color name if not in map
        }

        // Alpine.js component for image gallery
        function imageColorUploader({
            initialImages,
            availableColors
        }) {
            return {
                availableColors: availableColors,
                colorImages: {},

                init() {
                    this.populate(initialImages);
                },

                populate(images) {
                    this.colorImages = {}; // Reset first
                    if (Array.isArray(images)) {
                        images.forEach(item => {
                            if (item && item.color && item.image) {
                                this.colorImages[item.color] = {
                                    preview: `{{ asset('storage') }}/${item.image}`,
                                    file: null,
                                    existing: item.image
                                };
                            }
                        });
                    }
                },

                handleFileChange(event, colorName) {
                    const file = event.target.files[0];
                    if (file) {
                        this.colorImages[colorName] = {
                            ...this.colorImages[colorName],
                            preview: URL.createObjectURL(file)
                        };
                    }
                },

                removeImage(colorName, prefix = 'edit_file_input_') {
                    this.colorImages[colorName] = undefined;
                    const fileInput = document.getElementById(prefix + colorName);
                    if (fileInput) fileInput.value = '';
                }
            }
        }

        // Validate IMEI using Luhn algorithm
        function validateIMEI(imei) {
            if (!/^\d{15}$/.test(imei)) return false;
            let sum = 0;
            for (let i = 0; i < 14; i++) {
                let digit = parseInt(imei[i]);
                if (i % 2 === 1) {
                    digit *= 2;
                    sum += Math.floor(digit / 10) + (digit % 10);
                } else {
                    sum += digit;
                }
            }
            const checkDigit = (10 - (sum % 10)) % 10;
            return checkDigit === parseInt(imei[14]);
        }

        function parseScanData(scanData) {
            console.log('Raw Scan Data:', scanData); // Log raw input for debugging
            let productData = {
                product_name: `Scanned Product - ${new Date().toLocaleTimeString()}`,
                serial_no: '',
                imei: '',
                status: 'In Warehouse',
                condition: 'New',
                quality: 'Authentic',
                color: 'Unknown',
                distributor_name: '',
                retailer_name: '',
                description: '',
                scan_source: 'unknown'
            };

            // Step 1: Try parsing as JSON
            try {
                const json = JSON.parse(scanData);
                productData = {
                    ...productData,
                    product_name: json.product_name || json.name || productData.product_name,
                    serial_no: json.serial_no || json.serial || '',
                    imei: json.imei || '',
                    status: json.status || productData.status,
                    condition: json.condition || productData.condition,
                    quality: json.quality || productData.quality,
                    color: json.color || productData.color,
                    distributor_name: json.distributor_name || json.distributor || '',
                    retailer_name: json.retailer_name || json.retailer || '',
                    description: json.description || '',
                    scan_source: 'json'
                };
                // Validate IMEI if present
                if (productData.imei && !validateIMEI(productData.imei)) {
                    console.warn('Invalid IMEI detected:', productData.imei);
                    productData.imei = '';
                    productData.serial_no = scanData.replace(/[^a-zA-Z0-9\-_]/g, '');
                    productData.scan_source = 'invalid_imei';
                }
                console.log('Parsed Scan Data (JSON):', productData);
                return productData;
            } catch (e) {
                console.log('Not JSON, trying URL parsing');
            }

            // Step 2: Try parsing as URL with query parameters
            try {
                const url = new URL(scanData);
                const params = url.searchParams;
                productData = {
                    ...productData,
                    product_name: params.get('product_name') || params.get('name') || productData.product_name,
                    serial_no: params.get('serial_no') || params.get('serial') || '',
                    imei: params.get('imei') || '',
                    status: params.get('status') || productData.status,
                    condition: params.get('condition') || productData.condition,
                    quality: params.get('quality') || productData.quality,
                    color: params.get('color') || productData.color,
                    distributor_name: params.get('distributor_name') || params.get('distributor') || '',
                    retailer_name: params.get('retailer_name') || params.get('retailer') || '',
                    description: params.get('description') || '',
                    scan_source: 'url'
                };
                // Validate IMEI if present
                if (productData.imei && !validateIMEI(productData.imei)) {
                    console.warn('Invalid IMEI detected:', productData.imei);
                    productData.imei = '';
                    productData.serial_no = scanData.replace(/[^a-zA-Z0-9\-_]/g, '');
                    productData.scan_source = 'invalid_imei';
                }
                console.log('Parsed Scan Data (URL):', productData);
                return productData;
            } catch (e) {
                console.log('Not URL, trying raw string parsing');
            }

            // Step 3: Try parsing as CSV or delimited format
            if (scanData.includes(',')) {
                try {
                    const [product_name, serial_no, imei, distributor_name, retailer_name, description] =
                    scanData.split(',');
                    productData = {
                        ...productData,
                        product_name: product_name || productData.product_name,
                        serial_no: serial_no || '',
                        imei: imei && validateIMEI(imei) ? imei : '',
                        distributor_name: distributor_name || '',
                        retailer_name: retailer_name || '',
                        description: description || '',
                        scan_source: 'csv'
                    };
                    if (imei && !validateIMEI(imei)) {
                        productData.serial_no = imei;
                        productData.imei = '';
                        productData.scan_source = 'invalid_imei';
                    }
                    console.log('Parsed Scan Data (CSV):', productData);
                    return productData;
                } catch (e) {
                    console.log('Not CSV, falling back to raw string');
                }
            }

            // Step 4: Handle as raw string (IMEI or serial number)
            scanData = scanData.trim().replace(/[^a-zA-Z0-9\-_]/g, '');
            // Default behavior: treat any raw scan as IMEI and Serial, and also set it as the product name.
            productData.product_name = scanData;
            productData.imei = scanData;
            productData.serial_no = scanData;
            productData.scan_source = 'raw';

            // If it's a valid IMEI, refine the source
            if (/^\d{15}$/.test(scanData) && validateIMEI(scanData)) {
                productData.scan_source = 'imei';
            }
            console.log('Parsed Scan Data (Raw):', productData);
            return productData;
        }

        function startCameraScanner() {
            if (html5QrcodeScanner && html5QrcodeScanner.isScanning) return;

            showMessage('Starting camera...', 'info');
            document.getElementById('scanner-loading').classList.remove('hidden');
            document.getElementById('start-camera').classList.add('hidden');
            document.getElementById('stop-camera').classList.remove('hidden');

            try {
                html5QrcodeScanner = new Html5Qrcode("reader");
                Html5Qrcode.getCameras().then(cameras => {
                    if (!cameras || cameras.length === 0) {
                        showMessage('Error: No cameras found.', 'error');
                        stopCameraScanner();
                        return;
                    }

                    const config = {
                        fps: 10,
                        qrbox: {
                            width: 250,
                            height: 250
                        },
                        aspectRatio: 1.0,
                        formatsToSupport: [
                            Html5QrcodeSupportedFormats.QR_CODE,
                            Html5QrcodeSupportedFormats.CODE_128,
                            Html5QrcodeSupportedFormats.EAN_13,
                            Html5QrcodeSupportedFormats.CODE_39,
                            Html5QrcodeSupportedFormats.UPC_A
                        ]
                    };

                    const constraints = [{
                            facingMode: 'environment'
                        },
                        {
                            facingMode: 'user'
                        },
                        cameras[0].id
                    ];

                    let started = false;
                    let errorMsg = '';

                    async function tryCamera(index = 0) {
                        if (index >= constraints.length) {
                            let message = 'Error: Unable to access camera.';
                            if (errorMsg.includes('NotAllowedError')) message =
                                'Error: Camera permission denied. Allow in browser settings.';
                            else if (errorMsg.includes('NotFoundError')) message = 'Error: No cameras found.';
                            else if (errorMsg.includes('NotReadableError')) message =
                                'Error: Camera in use by another app.';
                            else if (errorMsg.includes('OverconstrainedError')) message =
                                'Error: No suitable camera found.';
                            showMessage(message, 'error');
                            stopCameraScanner();
                            return;
                        }

                        try {
                            await html5QrcodeScanner.start(
                                constraints[index],
                                config,
                                (decodedText) => {
                                    processScan(decodedText, 'camera');
                                    stopCameraScanner();
                                },
                                () => {}
                            );
                            started = true;
                            showMessage('Scanning for barcode/serial...', 'info');
                        } catch (err) {
                            errorMsg = err.name || err.message;
                            tryCamera(index + 1);
                        }
                    }

                    tryCamera();
                }).catch(err => {
                    showMessage('Error: Failed to access cameras. Check permissions.', 'error');
                    stopCameraScanner();
                });
            } catch (err) {
                showMessage('Error: Scanner initialization failed.', 'error');
                stopCameraScanner();
            }
        }

        function stopCameraScanner() {
            if (html5QrcodeScanner && html5QrcodeScanner.isScanning) {
                html5QrcodeScanner.stop().then(() => {
                    html5QrcodeScanner.clear();
                    html5QrcodeScanner = null;
                    document.getElementById('scanner-loading').classList.add('hidden');
                    document.getElementById('start-camera').classList.remove('hidden');
                    document.getElementById('stop-camera').classList.add('hidden');
                    showMessage('', '');
                }).catch(console.error);
            }
        }

        function processManualScan() {
            const input = document.getElementById('manual-scan').value.trim();
            if (input) {
                processScan(input, 'manual');
                document.getElementById('manual-scan').value = '';
            }
        }

        function processScan(scanData, source) {
            if (isProcessing) {
                showMessage('Processing previous scan...', 'warning');
                return;
            }
            if (!scanData.trim()) {
                showMessage('Please enter scan data', 'error');
                return;
            }
            if (scannedItems.has(scanData)) {
                showMessage('This item has already been processed.', 'error');
                document.getElementById('manual-scan').focus();
                return; // Stop if already processed in this session
            }

            isProcessing = true;
            stats.total++; // Increment total immediately
            const resultId = 'scan-' + Date.now();
            addScanResult(resultId, 'loading', 'Processing scan...', scanData); // Show loading state

            // First, parse the data on the client side
            const productData = parseScanData(scanData);
            const checkData = productData.serial_no || productData.imei || scanData;

            fetch('{{ route('admin.scanner.scan') }}', { // This route checks if the product exists
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({
                        scan_data: checkData,
                        source: source
                    })
                })
                .then(res => res.ok ? res.json() : res.text().then(text => {
                    throw new Error(text);
                }))
                .then(data => {
                    if (data.success) {
                        if (data.action === 'new') {
                            updateScanResult(resultId, 'info', `📝 New product found. Please fill details.`, scanData,
                                data.product);
                            openProductModal(data.product, resultId, scanData); // Use server-parsed data
                        } else if (data.action === 'exists') {
                            stats.failed++;
                            updateScanResult(resultId, 'error', `❌ Already exists in database.`, scanData, data
                                .product); // Update result to show error
                            showMessage(`Product with code ${checkData} already exists.`,
                                'error'); // Show toast notification
                            scannedItems.add(checkData); // Add to session scanned items to prevent re-processing.
                            // Do NOT open any modal.
                        } else {
                            stats.failed++;
                            updateScanResult(resultId, 'error', `❌ Unknown action: ${data.action}`, scanData);
                        }
                    } else {
                        stats.failed++;
                        updateScanResult(resultId, 'error', `❌ ${data.message}`, scanData);
                        showMessage(data.message || 'An unknown error occurred during check.', 'error');
                    }
                })
                .catch(error => {
                    stats.failed++;
                    updateScanResult(resultId, 'error', `❌ Scan failed: ${error.message}`, scanData);
                    showMessage(error.message, 'error');
                })
                .finally(() => {
                    isProcessing = false;
                    updateStatistics();
                    document.getElementById('manual-scan').focus();
                });
        }

        function addScanResult(resultId, type, message, scanData, product = null) {
            const resultsDiv = document.getElementById('scan-results');
            const emptyState = resultsDiv.querySelector('.text-center');
            if (emptyState) emptyState.remove();
            const timestamp = new Date().toLocaleTimeString();
            const icon = type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-times-circle' :
                'fa-spinner fa-spin';
            const color = type === 'success' ? 'text-green-500' : type === 'error' ? 'text-red-500' : 'text-blue-500';
            const borderColor = type === 'success' ? 'border-l-green-500' : type === 'error' ? 'border-l-red-500' :
                'border-l-blue-500';

            const resultHtml = `
        <div id="${resultId}" class="flex items-start p-4 border-l-4 ${borderColor} bg-gray-50 rounded-r-lg scan-result">
            <i class="fas ${icon} ${color} mr-3 mt-1"></i>
            <div class="flex-grow">
                <div class="font-medium text-gray-800 text-sm sm:text-base">${message}</div>
                <div class="text-xs sm:text-sm text-gray-600 font-mono mt-1">${scanData}</div>
                ${product ? `<div class="text-xs text-gray-500 mt-2 pt-2 border-t border-gray-200 space-y-1">
                            <div><span class="font-medium text-gray-600">Product:</span> ${product.product_name}</div>
                            <div><span class="font-medium text-gray-600">Serial:</span> ${product.serial_no}</div>
                            ${product.imei ? `<div><span class="font-medium text-gray-600">IMEI:</span> ${product.imei}</div>` : ''}
                            <div>
                                <span class="font-medium text-gray-600">Status:</span> <span class="px-1.5 py-0.5 text-xs font-semibold rounded-full ${getStatusColor(product.status)}">${product.status}</span>
                                | <span class="font-medium text-gray-600">Quality:</span> ${product.quality}
                                ${product.distributor_name ? `<div><span class="font-medium text-gray-600">Distributor:</span> ${product.distributor_name}</div>` : ''}
                                ${product.retailer_name ? `<div><span class="font-medium text-gray-600">Retailer:</span> ${product.retailer_name}</div>` : ''}
                            </div>
                        </div>` : ''}
                <div class="text-xs text-gray-400 mt-1">${timestamp}</div>
            </div>
            <button onclick="removeResult('${resultId}')" class="text-gray-400 hover:text-gray-600 ml-2">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `;
            resultsDiv.insertAdjacentHTML('afterbegin', resultHtml);
        }

        function updateScanResult(resultId, type, message, scanData, product = null) {
            const element = document.getElementById(resultId);
            if (element) element.remove();
            addScanResult(resultId, type, message, scanData, product);
        }

        function openProductModal(productData, resultId, scanData) {
            const form = document.getElementById('product-form');
            form.reset();
            document.getElementById('modal-errors').classList.add('hidden');
            form.dataset.resultId = resultId;
            form.dataset.scanData = scanData;

            // Define form fields and their properties, mapping productData keys to form element IDs
            // This ensures all fields from the parsed data are correctly mapped to the modal form.
            const fields = [{
                    id: 'product_name',
                    key: 'product_name',
                    readonly: false
                },
                {
                    id: 'serial_no',
                    key: 'serial_no',
                    readonly: !!productData.serial_no
                },
                {
                    id: 'imei',
                    key: 'imei',
                    readonly: false
                },
                {
                    id: 'status',
                    key: 'status',
                    readonly: false
                },
                {
                    id: 'condition',
                    key: 'condition',
                    readonly: false
                },
                {
                    id: 'quality',
                    key: 'quality',
                    readonly: false
                },
                {
                    id: 'color',
                    key: 'color',
                    readonly: false
                },
                {
                    id: 'distributor_name',
                    key: 'distributor_name',
                    readonly: false
                },
                {
                    id: 'retailer_name',
                    key: 'retailer_name',
                    readonly: false
                },
                {
                    id: 'description',
                    key: 'description',
                    readonly: false
                }
            ];

            // Populate form fields and apply styles
            fields.forEach(field => {
                const input = form.querySelector(`#${field.id}`);
                if (!input) {
                    console.warn(`Form field with id #${field.id} not found.`);
                    return;
                }
                const value = productData[field.key] || '';
                input.value = value; // Set the value
                if (field.readonly) {
                    input.readOnly = true;
                    input.classList.add('bg-gray-100');
                } else {
                    input.readOnly = false;
                    input.classList.remove('bg-gray-100');
                }
                // Highlight fields populated from scan
                if (value && !['product_name', 'status', 'condition', 'quality', 'color'].includes(field.key)) {
                    input.classList.add('border-green-500', 'bg-green-50');
                } else {
                    input.classList.remove('border-green-500', 'bg-green-50');
                }
            });

            // Show message based on scan source
            let scanSourceMessage = '';
            switch (productData.scan_source) {
                case 'json':
                    scanSourceMessage = 'Scanned data parsed as JSON.';
                    break;
                case 'url':
                    scanSourceMessage = 'Scanned data parsed from URL parameters.';
                    break;
                case 'csv':
                    scanSourceMessage = 'Scanned data parsed as CSV.';
                    break;
                case 'imei':
                    scanSourceMessage = 'Scanned data recognized as IMEI.';
                    break;
                case 'serial':
                    scanSourceMessage = 'Scanned data recognized as serial number.';
                    break;
                case 'invalid_imei':
                    scanSourceMessage = 'Scanned data treated as serial number (invalid IMEI).';
                    break;
                default:
                    scanSourceMessage = 'Scanned data processed as raw input.';
            }
            showMessage(`${scanSourceMessage} Please verify and complete the form.`, 'info');

            // Warn if key fields are missing
            if (!productData.imei && !productData.serial_no) {
                showMessage('Warning: Limited data extracted from scan. Please fill in all required fields.', 'warning');
            }

            document.getElementById('product-modal').classList.remove('hidden');
            form.querySelector('#product_name').focus();
        }

        function openProductEditModal(productData, resultId, scanData) {
            // First, parse the newly scanned data to get any potential updates
            const scannedProductInfo = parseScanData(scanData);

            const form = document.getElementById('product-edit-form');
            form.reset();
            document.getElementById('edit-modal-errors').classList.add('hidden');
            form.dataset.resultId = resultId;
            form.dataset.scanData = scanData;

            // Combine data: Prioritize fresh scan data, then fill with existing DB data
            const finalData = {
                ...productData,
                ...scannedProductInfo
            };

            form.querySelector('#edit_product_id').value = finalData.id;
            form.querySelector('#edit_product_name').value = finalData.product_name || '';
            form.querySelector('#edit_serial_no').value = finalData.serial_no || '';
            form.querySelector('#edit_imei').value = finalData.imei || '';
            form.querySelector('#edit_status').value = finalData.status || 'In Warehouse';
            form.querySelector('#edit_condition').value = finalData.condition || 'New';
            form.querySelector('#edit_quality').value = finalData.quality || 'Authentic';
            form.querySelector('#edit_color').value = finalData.color || 'Unknown';
            form.querySelector('#edit_distributor_name').value = finalData.distributor_name || '';
            form.querySelector('#edit_retailer_name').value = finalData.retailer_name || '';
            form.querySelector('#edit_description').value = finalData.description || '';

            // Fetch and display colors for the product name, then select the current color
            fetchAndDisplayColors(finalData.product_name, 'edit_color-options-container', 'edit_color', finalData.color);

            document.getElementById('product-edit-modal').classList.remove('hidden');
            form.querySelector('#edit_product_name').focus();
        }

        function submitProductForm(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const resultId = form.dataset.resultId;
            const scanData = form.dataset.scanData;

            fetch('{{ route('admin.products.store') }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: formData
                })
                .then(response => response.json().then(body => ({
                    ok: response.ok,
                    body
                })))
                .then(({
                    ok,
                    body
                }) => {
                    if (ok && body.success) {
                        stats.successful++;
                        updateScanResult(resultId, 'success', `✅ New product created`, scanData, body.product);
                        showMessage(body.message || 'Product created successfully!', 'success');
                        scannedItems.add(scanData);
                        document.getElementById('product-modal').classList.add('hidden');
                    } else {
                        const errorContainer = document.getElementById('modal-errors');
                        let errorHtml =
                            '<p class="font-bold">Please correct the following errors:</p><ul class="list-disc list-inside">';
                        if (body.errors) {
                            for (const field in body.errors) {
                                errorHtml += `<li>${body.errors[field][0]}</li>`;
                            }
                        } else {
                            errorHtml += `<li>${body.message || 'An unknown error occurred.'}</li>`;
                        }
                        errorHtml += '</ul>';
                        errorContainer.innerHTML = errorHtml;
                        errorContainer.classList.remove('hidden');
                        showMessage(body.message || 'Please correct the form errors.', 'error');
                    }
                })
                .catch(error => {
                    showMessage(`Error: ${error.message}`, 'error');
                })
                .finally(() => updateStatistics());
        }

        function submitProductEditForm(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const productId = formData.get('product_id');
            const resultId = form.dataset.resultId;
            const scanData = form.dataset.scanData;

            fetch(`/admin/products/${productId}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: formData // FormData is used, so Content-Type is set by browser
                })
                .then(response => response.json().then(body => ({
                    ok: response.ok,
                    body
                })))
                .then(({
                    ok,
                    body
                }) => {
                    if (ok && body.success) {
                        stats.successful++;
                        updateScanResult(resultId, 'success', `✅ Product updated successfully`, scanData, body.product);
                        showMessage(body.message || 'Product updated successfully!', 'success');
                        scannedItems.add(scanData);
                        document.getElementById('product-edit-modal').classList.add('hidden');
                    } else {
                        const errorContainer = document.getElementById('edit-modal-errors');
                        let errorHtml =
                            '<p class="font-bold">Please correct the following errors:</p><ul class="list-disc list-inside">';
                        if (body.errors) {
                            for (const field in body.errors) {
                                errorHtml += `<li>${body.errors[field][0]}</li>`;
                            }
                        } else {
                            errorHtml += `<li>${body.message || 'An unknown error occurred.'}</li>`;
                        }
                        errorHtml += '</ul>';
                        errorContainer.innerHTML = errorHtml;
                        errorContainer.classList.remove('hidden');
                        showMessage(body.message || 'Please correct the form errors.', 'error');
                    }
                })
                .catch(error => {
                    showMessage(`Error: ${error.message}`, 'error');
                })
                .finally(() => updateStatistics());
        }

        function removeResult(resultId) {
            const element = document.getElementById(resultId);
            if (element) element.remove();
            const resultsDiv = document.getElementById('scan-results');
            if (resultsDiv.children.length === 0) {
                resultsDiv.innerHTML = `<div class="text-center text-gray-500 py-8">
            <i class="fas fa-inbox text-2xl sm:text-3xl mb-2"></i>
            <p class="text-sm sm:text-base">No scans yet</p>
            <p class="text-xs sm:text-sm">Scanning results will appear here</p>
        </div>`;
            }
        }

        function clearResults() {
            document.getElementById('scan-results').innerHTML = `<div class="text-center text-gray-500 py-8">
        <i class="fas fa-inbox text-2xl sm:text-3xl mb-2"></i>
        <p class="text-sm sm:text-base">No scans yet</p>
        <p class="text-xs sm:text-sm">Scanning results will appear here</p>
    </div>`;
            scannedItems.clear();
        }

        function simulateScan(type) {
            let testData;
            if (type === 'imei') {
                testData = generateIMEI();
            } else if (type === 'serial') {
                testData = `SN${Date.now().toString().slice(-8)}`;
                const canvas = document.createElement('canvas');
                document.getElementById('camera-scanner').appendChild(canvas);
                JsBarcode(canvas, testData, {
                    format: 'CODE128',
                    displayValue: true
                });
                setTimeout(() => canvas.remove(), 5000);
            } else if (type === 'barcode') {
                testData = JSON.stringify({
                    product_name: "Test Smartphone",
                    serial_no: `SN${Date.now().toString().slice(-8)}`,
                    imei: generateIMEI(),
                    status: "In Warehouse",
                    condition: "New",
                    quality: "Authentic",
                    color: "Black",
                    distributor_name: "Test Distributor",
                    retailer_name: "Test Retailer"
                });
            }
            processScan(testData, 'simulation');
        }

        function generateIMEI() {
            let imei = '35';
            for (let i = 0; i < 12; i++) imei += Math.floor(Math.random() * 10);
            let sum = 0;
            for (let i = 0; i < 14; i++) {
                let digit = parseInt(imei[i]);
                if (i % 2 === 1) {
                    digit *= 2;
                    sum += Math.floor(digit / 10) + (digit % 10);
                } else {
                    sum += digit;
                }
            }
            const checkDigit = (10 - (sum % 10)) % 10;
            return imei + checkDigit;
        }

        function updateStatistics() {
            document.getElementById('total-scans').textContent = stats.total;
            document.getElementById('successful-scans').textContent = stats.successful;
            document.getElementById('failed-scans').textContent = stats.failed;
        }

        function getStatusColor(status) {
            const colors = {
                'In Warehouse': 'bg-blue-100 text-blue-800',
                'Shipped': 'bg-amber-100 text-amber-800',
                'Delivered': 'bg-green-100 text-green-800',
                'Sold': 'bg-purple-100 text-purple-800',
                'Returned': 'bg-red-100 text-red-800'
            };
            return colors[status] || 'bg-gray-100 text-gray-800';
        }

        function showMessage(message, type) {
            const toast = document.createElement('div');
            toast.className =
                `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 flex items-center text-sm sm:text-base
        ${type === 'success' ? 'bg-green-500 text-white' : type === 'error' ? 'bg-red-500 text-white' : type === 'warning' ? 'bg-amber-500 text-white' : 'bg-primary text-white'}`;
            toast.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle'} mr-2"></i>
        <span>${message}</span>
        <button onclick="this.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
            <i class="fas fa-times"></i>
        </button>`;
            document.body.appendChild(toast);
            setTimeout(() => {
                if (toast.parentElement) toast.remove();
            }, 5000);
        }

        function handleProductNameChange(event, containerId, inputId) {
            const productName = event.target.value;
            fetchAndDisplayColors(productName, containerId, inputId);
        }

        function fetchAndDisplayColors(productName, containerId, inputId, selectedColor = null) {
            const colorOptionsContainer = document.getElementById(containerId);
            const hiddenColorInput = document.getElementById(inputId);
            const defaultColors = {!! $allColorsJson !!};

            if (!productName || !colorOptionsContainer) {
                displayColorOptions(defaultColors, containerId, inputId, selectedColor);
                return;
            }

            // Show loading state
            colorOptionsContainer.innerHTML = '<p class="text-xs text-gray-500">Loading colors...</p>';
            if (hiddenColorInput) hiddenColorInput.value = 'Unknown'; // Reset value

            fetch(`{{ route('admin.products.colors_by_name') }}?product_name=${encodeURIComponent(productName)}`)
                .then(response => {
                    if (!response.ok) throw new Error('Failed to fetch colors');
                    return response.json();
                })
                .then(colors => {
                    // If colors are returned, it means the product exists with those colors.
                    // We should only show those specific colors.
                    if (colors.length > 0) {
                        const existingColors = [...new Set(colors.flat())].filter(Boolean).sort();
                        displayColorOptions(existingColors, containerId, inputId, selectedColor || existingColors[0]);
                    } else {
                        // If no colors are returned, it's a new product name, so show all default colors.
                        displayColorOptions(defaultColors, containerId, inputId, selectedColor);
                    }
                })
                .catch(error => {
                    console.error('Error fetching colors:', error);
                    // On error (e.g., network issue or server error), fall back to showing default colors.
                    // This ensures the form is still usable.
                    displayColorOptions(defaultColors, containerId, inputId, selectedColor);
                });
        }

        function displayColorOptions(colors, containerId, inputId, selectedColor = null) {
            const colorOptionsContainer = document.getElementById(containerId);
            const hiddenColorInput = document.getElementById(inputId);
            if (!colorOptionsContainer || !hiddenColorInput) return;

            let currentlySelected = selectedColor || (colors.length > 0 ? colors[0] : 'Unknown');

            colorOptionsContainer.innerHTML = ''; // Clear previous options
            hiddenColorInput.value = currentlySelected;

            colors.forEach((color, index) => {
                const colorDiv = document.createElement('div');
                colorDiv.className = 'flex items-center gap-2 cursor-pointer p-1 rounded-full transition-colors';
                colorDiv.dataset.color = color;

                const isActive = currentlySelected === color;
                if (isActive) {
                    colorDiv.classList.add('bg-primary/10', 'ring-2', 'ring-primary');
                }

                colorDiv.innerHTML = `
                    <span class="h-5 w-5 rounded-full border" style="background-color: ${colorNameToHex(color)}"></span>
                    <span class="text-sm font-medium ${isActive ? 'text-primary' : 'text-gray-700'}">${color}</span>
                `;

                colorDiv.addEventListener('click', (e) => {
                    const clickedColor = e.currentTarget.dataset.color;
                    hiddenColorInput.value = clickedColor;

                    // Re-render buttons to update styles
                    displayColorOptions(colors, containerId, inputId, clickedColor);
                });
                colorOptionsContainer.appendChild(colorDiv);
            });
        }
    </script>

    <style>
        #reader {
            min-height: 300px;
            position: relative;
        }

        #reader video {
            width: 100% !important;
            height: auto !important;
            border-radius: 8px;
            object-fit: cover;
        }

        .scan-result {
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        #scan-results::-webkit-scrollbar {
            width: 6px;
        }

        #scan-results::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        #scan-results::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        #scan-results::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        .bg-yellow-50 {
            background-color: #fffbeb;
        }

        .text-yellow-800 {
            color: #a16207;
        }
    </style>
@endpush
