<x-tenant-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Add New Product') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            
            <!-- Mode Toggle Tabs -->
            <div class="mb-6 flex space-x-4 border-b border-gray-200">
                <button type="button" id="tab-manual" class="pb-2 px-4 border-b-2 border-green-500 font-medium text-green-600 focus:outline-none transition-colors duration-200">
                    Manual Entry
                </button>
                <button type="button" id="tab-import" class="pb-2 px-4 border-b-2 border-transparent font-medium text-gray-500 hover:text-gray-700 focus:outline-none transition-colors duration-200">
                    Bulk Import (CSV/Excel)
                </button>
            </div>

            <!-- Import Section -->
            <div id="import-section" class="bg-white overflow-hidden shadow-sm sm:rounded-lg mb-6" style="display: none;">
                <div class="p-6 bg-white border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Import Products</h3>
                    
                    <form action="{{ route('tenant.products.import') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="space-y-6">
                            <div class="bg-blue-50 border-l-4 border-blue-400 p-4">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <!-- Heroicon name: solid/information-circle -->
                                        <svg class="h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                                        </svg>
                                    </div>
                                    <div class="ml-3">
                                        <p class="text-sm text-blue-700">
                                            Download the template file to ensure your data is formatted correctly. 
                                            Currently supports <strong>Simple Products</strong> only.
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div class="flex items-center gap-4">
                                <a href="{{ route('tenant.products.template') }}" class="inline-flex items-center px-4 py-2 bg-gray-200 border border-transparent rounded-md font-semibold text-xs text-gray-700 uppercase tracking-widest hover:bg-gray-300 active:bg-gray-400 focus:outline-none focus:border-gray-500 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150">
                                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                                    Download Template
                                </a>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Upload CSV/Excel File</label>
                                <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md hover:border-green-400 transition-colors">
                                    <div class="space-y-1 text-center">
                                        <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                            <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                        </svg>
                                        <div class="flex text-sm text-gray-600 justify-center">
                                            <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500">
                                                <span>Upload a file</span>
                                                <input id="file-upload" name="file" type="file" class="sr-only" accept=".csv,.xlsx,.xls">
                                            </label>
                                            <p class="pl-1">or drag and drop</p>
                                        </div>
                                        <p class="text-xs text-gray-500">CSV, XLS, XLSX up to 10MB</p>
                                    </div>
                                </div>
                            </div>

                            <div class="flex justify-end">
                                <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                                    Import Products
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Manual Entry Section -->
            <div id="manual-section" class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form method="POST" action="{{ route('tenant.products.store') }}" id="product-form" enctype="multipart/form-data">
                        @csrf
                        <input type="hidden" name="has_variants" id="has_variants_input" value="0">

                        <!-- Basic Information -->
                        <div class="mb-8">
                            <h3 class="text-lg font-medium text-gray-900 border-b-2 border-green-100 pb-2 mb-6 flex items-center">
                                <span class="bg-green-100 text-green-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">1</span>
                                Basic Information
                            </h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label for="name" class="block text-sm font-medium text-gray-700">Product Name</label>
                                    <input type="text" name="name" id="product_name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" placeholder="e.g. Fresh Apples" required>
                                </div>

                                <div>
                                    <label for="category_id" class="block text-sm font-medium text-gray-700">Category</label>
                                    <select name="category_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                        <option value="">-- Select Category --</option>
                                        @foreach($categories as $category)
                                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div>
                                    <label for="brand_id" class="block text-sm font-medium text-gray-700">Brand</label>
                                    <select name="brand_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                        <option value="">-- Select Brand --</option>
                                        @foreach($brands as $brand)
                                            <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div>
                                    <label for="unit_id" class="block text-sm font-medium text-gray-700">Base Unit</label>
                                    <select name="unit_id" id="base_unit" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" required>
                                        <option value="">-- Select Base Unit --</option>
                                        @foreach($units as $unit)
                                            <option value="{{ $unit->id }}" data-name="{{ $unit->name }}">{{ $unit->name }} ({{ $unit->short_name }})</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div>
                                    <label for="manufacture_date" class="block text-sm font-medium text-gray-700">Manufacture Date</label>
                                    <input type="date" name="manufacture_date" id="manufacture_date" value="{{ date('Y-m-d') }}" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                </div>
                                <div>
                                    <label for="expiry_date" class="block text-sm font-medium text-gray-700">Expiry Date</label>
                                    <input type="date" name="expiry_date" id="expiry_date" value="{{ date('Y-m-d', strtotime('+6 months')) }}" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                </div>

                                <div class="col-span-1 md:col-span-2">
                                    <label for="image" class="block text-sm font-medium text-gray-700">Product Image (Optional)</label>
                                    <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md hover:border-green-400 transition-colors">
                                        <div class="space-y-1 text-center">
                                            <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                                <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                            </svg>
                                            <div class="flex text-sm text-gray-600 justify-center">
                                                <label for="product-image-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500">
                                                    <span>Upload a file</span>
                                                    <input id="product-image-upload" name="image" type="file" class="sr-only" accept="image/*">
                                                </label>
                                                <p class="pl-1">or drag and drop</p>
                                            </div>
                                            <p class="text-xs text-gray-500">PNG, JPG, GIF up to 2MB</p>
                                        </div>
                                    </div>
                                    <div id="image-preview" class="mt-4 hidden">
                                        <p class="text-sm text-gray-500 mb-2">Preview:</p>
                                        <img src="#" alt="Image Preview" class="h-32 w-auto object-cover rounded-md border border-gray-200">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Variant Toggle -->
                        <div class="mb-8 p-4 bg-gray-50 rounded-lg border border-gray-200 flex items-center justify-between">
                            <div class="flex items-center">
                                <input type="checkbox" id="has_variants_checkbox" class="form-checkbox h-5 w-5 text-green-600 rounded focus:ring-green-500 transition duration-150 ease-in-out">
                                <label for="has_variants_checkbox" class="ml-3 cursor-pointer">
                                    <span class="block text-sm font-medium text-gray-900">This product has multiple options</span>
                                    <span class="block text-sm text-gray-500">Enable this if you sell variants like Size, Color, etc.</span>
                                </label>
                            </div>
                        </div>

                        <!-- SIMPLE PRODUCT FORM -->
                        <div id="simple_product_section">
                            <h3 class="text-lg font-medium text-gray-900 border-b-2 border-blue-100 pb-2 mb-6 flex items-center">
                                <span class="bg-blue-100 text-blue-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">2</span>
                                Pricing & Inventory
                            </h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 bg-gray-50 p-6 rounded-lg border border-gray-100">
                                <div>
                                    <label for="simple_sku" class="block text-sm font-medium text-gray-700">SKU</label>
                                    <div class="mt-1 relative rounded-md shadow-sm">
                                        <input type="text" id="simple_sku" name="sku" class="focus:ring-green-500 focus:border-green-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="e.g. SKU-12345">
                                    </div>
                                </div>
                                <div>
                                    <label for="simple_stock" class="block text-sm font-medium text-gray-700">Initial Stock</label>
                                    <input type="number" id="simple_stock" name="stock" class="mt-1 focus:ring-green-500 focus:border-green-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="0">
                                </div>
                                <div>
                                    <label for="simple_price" class="block text-sm font-medium text-gray-700">Selling Price ($)</label>
                                    <div class="mt-1 relative rounded-md shadow-sm">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span class="text-gray-500 sm:text-sm">$</span>
                                        </div>
                                        <input type="number" id="simple_price" name="price" step="0.01" class="focus:ring-green-500 focus:border-green-500 block w-full pl-7 sm:text-sm border-gray-300 rounded-md" placeholder="0.00">
                                    </div>
                                </div>
                                <div>
                                    <label for="simple_cost" class="block text-sm font-medium text-gray-700">Cost Price ($)</label>
                                    <div class="mt-1 relative rounded-md shadow-sm">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span class="text-gray-500 sm:text-sm">$</span>
                                        </div>
                                        <input type="number" id="simple_cost" name="cost" step="0.01" class="focus:ring-green-500 focus:border-green-500 block w-full pl-7 sm:text-sm border-gray-300 rounded-md" placeholder="0.00">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- COMPLEX PRODUCT FORM -->
                        <div id="complex_product_section" style="display: none;">
                            
                            <!-- Step 1: Define Attributes -->
                            <div class="mb-8">
                                <h3 class="text-lg font-medium text-gray-900 border-b-2 border-indigo-100 pb-2 mb-6 flex items-center">
                                    <span class="bg-indigo-100 text-indigo-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">2</span>
                                    Define Attributes
                                </h3>
                                <div id="attributes_container" class="space-y-4">
                                    <!-- Attributes will be added here dynamically -->
                                    <div class="attribute-row flex gap-4 items-start bg-indigo-50 p-4 rounded-md border border-indigo-100">
                                        <div class="w-1/3">
                                            <label class="block text-xs font-medium text-gray-500 mb-1">Attribute Name</label>
                                            <input type="text" class="attribute-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Color">
                                        </div>
                                        <div class="w-1/2">
                                            <label class="block text-xs font-medium text-gray-500 mb-1">Values (comma separated)</label>
                                            <input type="text" class="attribute-values mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Red, Blue, Green">
                                        </div>
                                        <div class="pt-6">
                                            <button type="button" class="remove-attribute text-red-400 hover:text-red-600 transition-colors">
                                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="mt-4">
                                    <button type="button" id="add_attribute_btn" class="inline-flex items-center px-3 py-2 border border-indigo-300 shadow-sm text-sm leading-4 font-medium rounded-md text-indigo-700 bg-white hover:bg-indigo-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                        + Add Another Attribute
                                    </button>
                                </div>
                            </div>

                            <!-- Step 2: Define Units -->
                            <div class="mb-8">
                                <h3 class="text-lg font-medium text-gray-900 border-b-2 border-purple-100 pb-2 mb-6 flex items-center">
                                    <span class="bg-purple-100 text-purple-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">3</span>
                                    Define Additional Units (Optional)
                                </h3>
                                <div id="units_container" class="space-y-4">
                                    <!-- Units will be added here dynamically -->
                                </div>
                                <div class="mt-4">
                                    <button type="button" id="add_unit_btn" class="inline-flex items-center px-3 py-2 border border-purple-300 shadow-sm text-sm leading-4 font-medium rounded-md text-purple-700 bg-white hover:bg-purple-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500">
                                        + Add Unit (e.g. Case, Pack)
                                    </button>
                                </div>
                            </div>

                            <!-- Step 3: Generate & Price -->
                            <div class="mb-8">
                                <div class="flex justify-between items-center border-b-2 border-gray-100 pb-2 mb-6">
                                    <h3 class="text-lg font-medium text-gray-900 flex items-center">
                                        <span class="bg-gray-200 text-gray-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">4</span>
                                        Variant Matrix & Pricing
                                    </h3>
                                    <button type="button" id="generate_variants_btn" class="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-150">
                                        Generate Variants
                                    </button>
                                </div>

                                <div class="overflow-x-auto shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                                    <table id="variants_table" class="min-w-full divide-y divide-gray-300" style="display: none;">
                                        <thead class="bg-gray-50">
                                            <tr>
                                                <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">Variant</th>
                                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">SKU</th>
                                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Pricing (Per Unit)</th>
                                                <th scope="col" class="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">Stock (Base)</th>
                                                <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
                                                    <span class="sr-only">Delete</span>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-200 bg-white">
                                            <!-- Variants will be generated here -->
                                        </tbody>
                                    </table>
                                    <div id="variants_placeholder" class="text-center py-12 px-6 text-gray-500 bg-gray-50 border-t border-gray-100">
                                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.384-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path></svg>
                                        <p class="mt-2 text-sm">Define attributes above and click "Generate Variants" to create the product matrix.</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="flex items-center justify-end mt-8 border-t pt-6 space-x-4">
                            <a href="{{ route('tenant.products.index') }}" class="text-gray-500 hover:text-gray-700 font-medium mr-auto transition-colors">Cancel</a>
                            
                            <button type="submit" name="action" value="save_and_add_another" class="inline-flex items-center px-4 py-3 bg-blue-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-blue-700 active:bg-blue-900 focus:outline-none focus:border-blue-900 focus:ring ring-blue-300 disabled:opacity-25 transition ease-in-out duration-150 shadow-md">
                                Save & Add Another
                            </button>

                            <button type="submit" name="action" value="save" class="inline-flex items-center px-6 py-3 bg-green-600 border border-transparent rounded-md font-semibold text-base text-white uppercase tracking-widest hover:bg-green-700 active:bg-green-900 focus:outline-none focus:border-green-900 focus:ring ring-green-300 disabled:opacity-25 transition ease-in-out duration-150 shadow-lg">
                                Create Product
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        $(document).ready(function() {
            // --- Debug Information ---
            console.log('Create page - jQuery loaded');
            console.log('Create page - Simple section exists:', $('#simple_product_section').length > 0);
            console.log('Create page - Complex section exists:', $('#complex_product_section').length > 0);
            console.log('Create page - Checkbox exists:', $('#has_variants_checkbox').length > 0);
            console.log('Create page - Initial checkbox state:', $('#has_variants_checkbox').is(':checked'));
            
            // --- Tab Switching ---
            $('#tab-manual').click(function() {
                $(this).addClass('border-green-500 text-green-600').removeClass('border-transparent text-gray-500');
                $('#tab-import').addClass('border-transparent text-gray-500').removeClass('border-green-500 text-green-600');
                
                $('#manual-section').show();
                $('#import-section').hide();
            });

            $('#tab-import').click(function() {
                $(this).addClass('border-green-500 text-green-600').removeClass('border-transparent text-gray-500');
                $('#tab-manual').addClass('border-transparent text-gray-500').removeClass('border-green-500 text-green-600');
                
                $('#manual-section').hide();
                $('#import-section').show();
            });

            // --- File Upload UI (Import) ---
            $('#file-upload').change(function() {
                var fileName = $(this).val().split('\\').pop(); 
                if(fileName) {
                    $(this).parent().find('span').text(fileName);
                    $(this).closest('.border-dashed').addClass('border-green-400 bg-green-50');
                }
            });

            // --- Product Image Upload Preview ---
            $('#product-image-upload').change(function() {
                var file = this.files[0];
                var fileName = $(this).val().split('\\').pop();
                
                if (file) {
                    // Update label text
                    $(this).parent().find('span').text(fileName);
                    $(this).closest('.border-dashed').addClass('border-green-400 bg-green-50');
                    
                    // Show preview
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#image-preview img').attr('src', e.target.result);
                        $('#image-preview').removeClass('hidden');
                    }
                    reader.readAsDataURL(file);
                }
            });

            // --- Global Variables ---
            let customUnits = [];

            // --- Toggle Simple/Complex Form ---
            $('#has_variants_checkbox').change(function() {
                console.log('Create page - Checkbox changed, checked:', $(this).is(':checked'));
                
                if ($(this).is(':checked')) {
                    // Switching to variant product - preserve simple product data
                    var simplePrice = $('#simple_price').val() || 0;
                    var simpleCost = $('#simple_cost').val() || 0;
                    var simpleStock = $('#simple_stock').val() || 0;
                    var simpleSku = $('#simple_sku').val() || '';
                    
                    console.log('Create page - Preserving simple data:', {simplePrice, simpleCost, simpleStock, simpleSku});
                    
                    $('#simple_product_section').slideUp(200);
                    $('#complex_product_section').slideDown(200);
                    $('#has_variants_input').val(1);
                    
                    // Store simple data for use in first variant
                    $('#simple_data_backup').remove();
                    $('<input type="hidden" id="simple_data_backup" name="simple_data_backup">').val(JSON.stringify({
                        price: simplePrice,
                        cost: simpleCost,
                        stock: simpleStock,
                        sku: simpleSku
                    })).appendTo('#product-form');
                    
                    console.log('Create page - Complex section should now be visible');
                    
                } else {
                    // Switching to simple product
                    $('#simple_product_section').slideDown(200);
                    $('#complex_product_section').slideUp(200);
                    $('#has_variants_input').val(0);
                    $('#simple_data_backup').remove();
                    
                    console.log('Create page - Simple section should now be visible');
                }
            });

            // --- Attributes Management ---
            function addAttributeRow() {
                const row = `
                    <div class="attribute-row flex gap-4 items-start bg-indigo-50 p-4 rounded-md border border-indigo-100 mt-2">
                        <div class="w-1/3">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Attribute Name</label>
                            <input type="text" class="attribute-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Size">
                        </div>
                        <div class="w-1/2">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Values (comma separated)</label>
                            <input type="text" class="attribute-values mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Small, Medium, Large">
                        </div>
                        <div class="pt-6">
                            <button type="button" class="remove-attribute text-red-400 hover:text-red-600 transition-colors">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>
                        </div>
                    </div>
                `;
                $('#attributes_container').append(row);
            }

            $('#add_attribute_btn').click(function() {
                addAttributeRow();
            });

            $(document).on('click', '.remove-attribute', function() {
                if ($('#attributes_container .attribute-row').length > 1) {
                    $(this).closest('.attribute-row').remove();
                } else {
                    const row = $(this).closest('.attribute-row');
                    row.find('input').val('');
                }
            });

            // --- Units Management ---
            function addUnitRow() {
                const index = $('#units_container .unit-row').length;
                const row = `
                    <div class="unit-row flex gap-4 items-start bg-purple-50 p-4 rounded-md border border-purple-100 mt-2" data-index="${index}">
                        <div class="w-1/3">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Unit Name</label>
                            <input type="text" name="product_units[${index}][name]" class="unit-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-purple-500 focus:ring-purple-500" placeholder="e.g. Case">
                        </div>
                        <div class="w-1/3">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Conversion (1 Unit = X Base)</label>
                            <input type="number" step="0.01" name="product_units[${index}][conversion_factor]" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-purple-500 focus:ring-purple-500" placeholder="e.g. 24">
                        </div>
                        <div class="w-1/4 pt-6 flex gap-4">
                            <label class="inline-flex items-center">
                                <input type="checkbox" name="product_units[${index}][is_sale]" class="form-checkbox h-4 w-4 text-purple-600 rounded focus:ring-purple-500" checked>
                                <span class="ml-2 text-xs text-gray-700">For Sale</span>
                            </label>
                        </div>
                        <div class="pt-6">
                            <button type="button" class="remove-unit text-red-400 hover:text-red-600 transition-colors">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>
                        </div>
                    </div>
                `;
                $('#units_container').append(row);
            }

            $('#add_unit_btn').click(function() {
                addUnitRow();
            });

            $(document).on('click', '.remove-unit', function() {
                $(this).closest('.unit-row').remove();
                reindexUnits();
            });

            function reindexUnits() {
                $('#units_container .unit-row').each(function(index) {
                    $(this).find('input[name^="product_units"]').each(function() {
                        const name = $(this).attr('name');
                        const newName = name.replace(/product_units\[\d+\]/, `product_units[${index}]`);
                        $(this).attr('name', newName);
                    });
                });
            }

            // --- Generate Variants ---
            function cartesian(args) {
                var r = [], max = args.length - 1;
                function helper(arr, i) {
                    for (var j = 0, l = args[i].length; j < l; j++) {
                        var a = arr.slice(0); // clone arr
                        a.push(args[i][j]);
                        if (i == max)
                            r.push(a);
                        else
                            helper(a, i + 1);
                    }
                }
                helper([], 0);
                return r;
            }

            $('#generate_variants_btn').click(function() {
                const attributes = [];
                $('#attributes_container .attribute-row').each(function() {
                    const name = $(this).find('.attribute-name').val().trim();
                    const valuesStr = $(this).find('.attribute-values').val().trim();
                    
                    if (name && valuesStr) {
                        const values = valuesStr.split(',').map(v => v.trim()).filter(v => v);
                        if (values.length > 0) {
                            attributes.push({ name: name, values: values });
                        }
                    }
                });

                if (attributes.length === 0) {
                    alert('Please define at least one attribute with values.');
                    return;
                }

                const combinations = cartesian(attributes.map(a => a.values));
                const tbody = $('#variants_table tbody');
                tbody.empty();

                if (combinations.length > 0) {
                    $('#variants_table').show();
                    $('#variants_placeholder').hide();
                } else {
                    $('#variants_table').hide();
                    $('#variants_placeholder').show();
                    return;
                }

                // Get Custom Units
                const units = [];
                $('#units_container .unit-row').each(function() {
                    const uName = $(this).find('.unit-name').val().trim();
                    if (uName) units.push(uName);
                });

                const productName = $('#product_name').val().trim();
                const skuPrefix = productName ? productName.toUpperCase().substring(0, 3) : 'PRD';
                const baseUnitName = $('#base_unit option:selected').data('name') || 'Base Unit';

                combinations.forEach((combo, vIndex) => {
                    const values = Array.isArray(combo) ? combo : [combo];
                    const variantName = values.join(' / ');
                    
                    // Generate SKU
                    const skuSuffix = values.map(v => v.toUpperCase().substring(0, 3)).join('-');
                    const sku = `${skuPrefix}-${skuSuffix}-${Math.floor(Math.random() * 1000)}`;

                    let html = `<tr class="hover:bg-gray-50 transition-colors">`;
                    
                    // Variant Name & Hidden Inputs
                    html += `<td class="py-4 pl-4 pr-3 text-sm align-top sm:pl-6">
                                <div class="font-medium text-gray-900">${variantName}</div>
                                <input type="hidden" name="variants[${vIndex}][name]" value="${variantName}">
                                <div class="text-xs text-gray-500 space-y-1 mt-1">`;
                    
                    values.forEach((val, idx) => {
                        html += `<div>
                                    <span class="font-medium text-gray-600">${attributes[idx].name}</span>: <span class="font-semibold text-gray-800">${val}</span>
                                    <input type="hidden" name="variants[${vIndex}][attributes][${idx}][name]" value="${attributes[idx].name}">
                                    <input type="hidden" name="variants[${vIndex}][attributes][${idx}][value]" value="${val}">
                                 </div>`;
                    });
                    html += `   </div>
                             </td>`;

                    // SKU
                    html += `<td class="px-3 py-4 text-sm align-top">
                                <input type="text" name="variants[${vIndex}][sku]" value="${sku}" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md">
                             </td>`;

                    // Pricing
                    html += `<td class="px-3 py-4 text-sm align-top">
                                <div class="space-y-3">
                                    <!-- Base Unit -->
                                    <div class="flex gap-2 items-center bg-gray-50 p-2 rounded border border-gray-200">
                                        <span class="text-xs font-bold w-12 text-gray-700 uppercase">${baseUnitName}</span>
                                        <input type="hidden" name="variants[${vIndex}][prices][0][unit_name]" value="${baseUnitName}">
                                        <input type="number" step="0.01" name="variants[${vIndex}][prices][0][price]" placeholder="Price" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                        <input type="number" step="0.01" name="variants[${vIndex}][prices][0][cost]" placeholder="Cost" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                    </div>`;
                    
                    // Custom Units
                    units.forEach((uName, uIndex) => {
                        const priceIndex = uIndex + 1;
                        html += `<div class="flex gap-2 items-center bg-purple-50 p-2 rounded border border-purple-100">
                                    <span class="text-xs font-bold w-12 text-purple-700 uppercase">${uName}</span>
                                    <input type="hidden" name="variants[${vIndex}][prices][${priceIndex}][unit_name]" value="${uName}">
                                    <input type="number" step="0.01" name="variants[${vIndex}][prices][${priceIndex}][price]" placeholder="Price" class="shadow-sm focus:ring-purple-500 focus:border-purple-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                    <input type="number" step="0.01" name="variants[${vIndex}][prices][${priceIndex}][cost]" placeholder="Cost" class="shadow-sm focus:ring-purple-500 focus:border-purple-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                 </div>`;
                    });

                    html += `   </div>
                             </td>`;

                    // Stock
                    html += `<td class="px-3 py-4 text-sm align-top text-center">
                                <input type="number" name="variants[${vIndex}][stock]" value="0" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 mx-auto sm:text-sm border-gray-300 rounded-md">
                             </td>`;

                    // Remove Action
                    html += `<td class="relative py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 align-top">
                                <button type="button" class="remove-variant text-red-400 hover:text-red-600 transition-colors">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </button>
                             </td>`;

                    html += `</tr>`;
                    tbody.append(html);
                });
            });

            $(document).on('click', '.remove-variant', function() {
                $(this).closest('tr').remove();
                if ($('#variants_table tbody tr').length === 0) {
                    $('#variants_table').hide();
                    $('#variants_placeholder').show();
                }
            });
        });
    </script>
</x-tenant-layout>
