<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            <?php echo e(__('List New Item')); ?>

        </h2>
     <?php $__env->endSlot(); ?>

    <div class="py-6 md:py-12">
        <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
            <!-- Progress Indicator -->
            <div class="mb-8">
                <div class="flex items-center justify-center space-x-2 md:space-x-4">
                    <div class="flex items-center">
                        <div class="step-circle active" data-step="1">
                            <span class="step-number">1</span>
                            <svg class="step-check hidden" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <span class="hidden sm:block ml-2 text-sm font-medium text-gray-900">Basic Info</span>
                    </div>
                    
                    <div class="flex-1 h-0.5 bg-gray-200">
                        <div class="h-0.5 bg-blue-600 transition-all duration-300" style="width: 0%" id="progress-bar-1"></div>
                    </div>
                    
                    <div class="flex items-center">
                        <div class="step-circle" data-step="2">
                            <span class="step-number">2</span>
                            <svg class="step-check hidden" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <span class="hidden sm:block ml-2 text-sm font-medium text-gray-500">Pricing</span>
                    </div>
                    
                    <div class="flex-1 h-0.5 bg-gray-200">
                        <div class="h-0.5 bg-blue-600 transition-all duration-300" style="width: 0%" id="progress-bar-2"></div>
                    </div>
                    
                    <div class="flex items-center">
                        <div class="step-circle" data-step="3">
                            <span class="step-number">3</span>
                            <svg class="step-check hidden" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <span class="hidden sm:block ml-2 text-sm font-medium text-gray-500">Details</span>
                    </div>
                    
                    <div class="flex-1 h-0.5 bg-gray-200">
                        <div class="h-0.5 bg-blue-600 transition-all duration-300" style="width: 0%" id="progress-bar-3"></div>
                    </div>
                    
                    <div class="flex items-center">
                        <div class="step-circle" data-step="4">
                            <span class="step-number">4</span>
                            <svg class="step-check hidden" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <span class="hidden sm:block ml-2 text-sm font-medium text-gray-500">Shipping</span>
                    </div>
                    
                    <div class="flex-1 h-0.5 bg-gray-200">
                        <div class="h-0.5 bg-blue-600 transition-all duration-300" style="width: 0%" id="progress-bar-4"></div>
                    </div>
                    
                    <div class="flex items-center">
                        <div class="step-circle" data-step="5">
                            <span class="step-number">5</span>
                            <svg class="step-check hidden" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <span class="hidden sm:block ml-2 text-sm font-medium text-gray-500">Photos</span>
                    </div>
                </div>
                
                <!-- Mobile Step Labels -->
                <div class="sm:hidden mt-4 text-center">
                    <span class="text-sm font-medium text-gray-900" id="mobile-step-label">Step 1: Basic Info</span>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-4 md:p-8">
                    <form id="listing-wizard" method="POST" action="<?php echo e(route('my-items.store')); ?>" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>

                        <!-- Step 1: Basic Information -->
                        <div class="wizard-step active" data-step="1">
                            <div class="text-center mb-8">
                                <h3 class="text-2xl font-bold text-gray-900">What are you listing?</h3>
                                <p class="mt-2 text-gray-600">Let's start with the basics</p>
                            </div>

                            <div class="space-y-6 max-w-2xl mx-auto">
                                <div>
                                    <label for="title" class="block text-lg font-medium text-gray-700 mb-2">
                                        Title for your listing <span class="text-red-500">*</span>
                                    </label>
                                    <input type="text" 
                                           id="title" 
                                           name="title" 
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-lg"
                                           placeholder="e.g., Roland SH-101, etc."
                                           value="<?php echo e(old('title')); ?>"
                                           maxlength="255">
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                    <div class="mt-2 text-sm text-gray-500">
                                        <span id="title-counter">0</span>/255 characters
                                    </div>
                                </div>

                                <div>
                                    <label for="description" class="block text-lg font-medium text-gray-700 mb-2">
                                        Describe your item <span class="text-red-500">*</span>
                                    </label>
                                    <textarea id="description" 
                                              name="description" 
                                              rows="6" 
                                              class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                              placeholder="Include key details like age, condition, any accessories included, why you're selling, etc."><?php echo e(old('description')); ?></textarea>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                    <div class="mt-2 text-sm text-gray-500">Be detailed - this helps buyers understand what they're getting</div>
                                </div>

                                <div>
                                    <label for="condition" class="block text-lg font-medium text-gray-700 mb-2">
                                        What condition is it in? <span class="text-red-500">*</span>
                                    </label>
                                    <select id="condition" 
                                            name="condition" 
                                            class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                        <option value="">Select condition...</option>
                                        <option value="New" <?php echo e(old('condition') == 'New' ? 'selected' : ''); ?>>New - Never used, in original packaging</option>
                                        <option value="Like New" <?php echo e(old('condition') == 'Like New' ? 'selected' : ''); ?>>Like New - Barely used, no visible wear</option>
                                        <option value="Excellent" <?php echo e(old('condition') == 'Excellent' ? 'selected' : ''); ?>>Excellent - Light use, minor wear</option>
                                        <option value="Very Good" <?php echo e(old('condition') == 'Very Good' ? 'selected' : ''); ?>>Very Good - Normal wear, fully functional</option>
                                        <option value="Good" <?php echo e(old('condition') == 'Good' ? 'selected' : ''); ?>>Good - Obvious wear but works well</option>
                                        <option value="Fair" <?php echo e(old('condition') == 'Fair' ? 'selected' : ''); ?>>Fair - Heavy wear, some issues</option>
                                        <option value="Poor" <?php echo e(old('condition') == 'Poor' ? 'selected' : ''); ?>>Poor - Significant issues, for parts/repair</option>
                                    </select>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 2: Pricing & Listing Type -->
                        <div class="wizard-step hidden" data-step="2">
                            <div class="text-center mb-8">
                                <h3 class="text-2xl font-bold text-gray-900">How do you want to list this?</h3>
                                <p class="mt-2 text-gray-600">Choose your listing type and pricing</p>
                            </div>

                            <div class="space-y-6 max-w-2xl mx-auto">
                                <div>
                                    <label class="block text-lg font-medium text-gray-700 mb-4">
                                        Listing Type <span class="text-red-500">*</span>
                                    </label>
                                    
                                    <div class="space-y-3">
                                        <label class="flex items-start p-4 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                            <input type="radio" name="listing_type" value="sale" class="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500" <?php echo e(old('listing_type', 'sale') == 'sale' ? 'checked' : ''); ?>>
                                            <div class="ml-3">
                                                <div class="font-semibold text-gray-900">For Sale</div>
                                                <div class="text-sm text-gray-600">List item for sale with a set price</div>
                                            </div>
                                        </label>
                                        
                                        <label class="flex items-start p-4 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                            <input type="radio" name="listing_type" value="inventory_open" class="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500" <?php echo e(old('listing_type') == 'inventory_open' ? 'checked' : ''); ?>>
                                            <div class="ml-3">
                                                <div class="font-semibold text-gray-900">Personal Inventory + Open to Offers</div>
                                                <div class="text-sm text-gray-600">Show item in inventory, accept offers from interested buyers</div>
                                            </div>
                                        </label>
                                        
                                        <label class="flex items-start p-4 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                            <input type="radio" name="listing_type" value="inventory" class="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500" <?php echo e(old('listing_type') == 'inventory' ? 'checked' : ''); ?>>
                                            <div class="ml-3">
                                                <div class="font-semibold text-gray-900">Personal Inventory (Private)</div>
                                                <div class="text-sm text-gray-600">Keep private record, not visible to other users</div>
                                            </div>
                                        </label>
                                    </div>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                </div>

                                <div id="price-section" class="block">
                                    <label for="price" class="block text-lg font-medium text-gray-700 mb-2">
                                        What's your asking price? <span class="text-red-500" id="price-required">*</span>
                                    </label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span class="text-gray-500 text-lg">$</span>
                                        </div>
                                        <input type="number" 
                                               id="price" 
                                               name="price" 
                                               class="w-full pl-8 pr-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-lg"
                                               placeholder="0.00"
                                               step="0.01"
                                               min="0"
                                               value="<?php echo e(old('price')); ?>">
                                    </div>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                    <div class="mt-2 text-sm text-gray-500" id="price-help">Enter the price you want for this item</div>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div>
                                        <label for="quantity" class="block text-lg font-medium text-gray-700 mb-2">
                                            How many do you have? <span class="text-red-500">*</span>
                                        </label>
                                        <input type="number" 
                                               id="quantity" 
                                               name="quantity" 
                                               class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               value="<?php echo e(old('quantity', 1)); ?>"
                                               min="1">
                                        <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                    </div>
                                    
                                    <div class="flex items-center">
                                        <label class="flex items-start cursor-pointer">
                                            <input type="checkbox" 
                                                   name="open_to_trades" 
                                                   value="1" 
                                                   class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded mt-1"
                                                   <?php echo e(old('open_to_trades') ? 'checked' : ''); ?>>
                                            <div class="ml-3">
                                                <div class="font-medium text-gray-900">Open to trades</div>
                                                <div class="text-sm text-gray-600">Consider trade offers for this item</div>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 3: Product Details -->
                        <div class="wizard-step hidden" data-step="3">
                            <div class="text-center mb-8">
                                <h3 class="text-2xl font-bold text-gray-900">Help buyers find your item</h3>
                                <p class="mt-2 text-gray-600">Add category, manufacturer, and model details (optional but recommended)</p>
                            </div>

                            <div class="space-y-6 max-w-2xl mx-auto">
                                <div>
                                    <label for="category_id" class="block text-lg font-medium text-gray-700 mb-2">
                                        What category does this fit in?
                                    </label>
                                    <div class="flex gap-2">
                                        <select id="category_id" 
                                                name="category_id" 
                                                class="flex-1 px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                            <option value="">Choose a category...</option>
                                            <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($category->id); ?>" <?php echo e(old('category_id') == $category->id ? 'selected' : ''); ?>>
                                                    <?php echo e($category->name); ?>

                                                </option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                        <button type="button" 
                                                onclick="showAddCategoryModal()" 
                                                class="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors whitespace-nowrap">
                                            Add New
                                        </button>
                                    </div>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                </div>

                                <div>
                                    <label for="manufacturer_id" class="block text-lg font-medium text-gray-700 mb-2">
                                        Who made it?
                                    </label>
                                    <div class="flex gap-2">
                                        <select id="manufacturer_id" 
                                                name="manufacturer_id" 
                                                class="flex-1 px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                            <option value="">Choose a manufacturer...</option>
                                            <?php $__currentLoopData = $manufacturers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $manufacturer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($manufacturer->id); ?>" <?php echo e(old('manufacturer_id') == $manufacturer->id ? 'selected' : ''); ?>>
                                                    <?php echo e($manufacturer->name); ?>

                                                </option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                        <button type="button" 
                                                onclick="showAddManufacturerModal()" 
                                                class="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors whitespace-nowrap">
                                            Add New
                                        </button>
                                    </div>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                </div>

                                <div>
                                    <label for="model" class="block text-lg font-medium text-gray-700 mb-2">
                                        What's the model name or number?
                                    </label>
                                    <input type="text" 
                                           id="model" 
                                           name="model" 
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                           placeholder=""
                                           value="<?php echo e(old('model')); ?>"
                                           maxlength="255">
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 4: Shipping Options -->
                        <div class="wizard-step hidden" data-step="4">
                            <div class="text-center mb-8">
                                <h3 class="text-2xl font-bold text-gray-900">How will buyers get this item?</h3>
                                <p class="mt-2 text-gray-600">Set up your delivery and pickup options</p>
                            </div>

                            <div class="space-y-6 max-w-2xl mx-auto">
                                <div>
                                    <label class="flex items-start cursor-pointer p-4 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                                        <input type="checkbox" 
                                               name="local_pickup" 
                                               value="1" 
                                               class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded mt-1"
                                               <?php echo e(old('local_pickup') ? 'checked' : ''); ?>>
                                        <div class="ml-3">
                                            <div class="font-semibold text-gray-900">Local pickup available</div>
                                            <div class="text-sm text-gray-600">Buyers can meet you in person to pick up the item</div>
                                        </div>
                                    </label>
                                </div>

                                <div>
                                    <label class="flex items-start cursor-pointer p-4 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                                        <input type="checkbox" 
                                               id="shipping_available" 
                                               name="shipping_available" 
                                               value="1" 
                                               class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded mt-1"
                                               <?php echo e(old('shipping_available', true) ? 'checked' : ''); ?>>
                                        <div class="ml-3">
                                            <div class="font-semibold text-gray-900">Shipping available</div>
                                            <div class="text-sm text-gray-600">You can ship this item to buyers</div>
                                        </div>
                                    </label>
                                </div>

                                <div id="shipping-cost-section" class="block">
                                    <label for="shipping_cost" class="block text-lg font-medium text-gray-700 mb-2">
                                        How much for shipping?
                                    </label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span class="text-gray-500 text-lg">$</span>
                                        </div>
                                        <input type="number" 
                                               id="shipping_cost" 
                                               name="shipping_cost" 
                                               class="w-full pl-8 pr-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               placeholder="0.00"
                                               step="0.01"
                                               min="0"
                                               value="<?php echo e(old('shipping_cost')); ?>">
                                    </div>
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                    <div class="mt-2 text-sm text-gray-500">
                                        Leave blank for free shipping or if buyer pays actual shipping cost
                                    </div>
                                </div>

                                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                    <div class="flex">
                                        <svg class="h-5 w-5 text-blue-600 mt-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
<!--                                        <div class="ml-3 text-sm text-blue-800">
                                            <strong>Tip:</strong> Offering both pickup and shipping gives buyers more options and can help your item sell faster. 
                                        </div>-->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 5: Photos -->
                        <div class="wizard-step hidden" data-step="5">
                            <div class="text-center mb-8">
                            <h3 class="text-2xl font-bold text-gray-900">Add images</h3>
			    <p class="mt-2 text-gray-600">Add photos to help buyers see what they're getting</p>
                            </div>

                            <div class="space-y-6 max-w-3xl mx-auto">
                                <div>
                                    <!-- File Input (Hidden) -->
                                    <input id="photos" type="file" name="photos[]" multiple accept=".jpeg,.jpg,.png,.gif" class="hidden" onchange="handleImageUpload(event)">
                                    
                                    <!-- Upload Area -->
                                    <div id="upload-area" class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors cursor-pointer" onclick="document.getElementById('photos').click()">
                                        <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                                            <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="mt-4">
                                            <p class="text-lg font-medium text-gray-900">Add photos of your item</p>
                                            <p class="mt-2 text-sm text-gray-600">
                                                Drag and drop images here, or click to browse
                                            </p>
                                            <p class="mt-1 text-xs text-gray-500">
                                                PNG, JPG, GIF up to 2MB each
                                            </p>
                                        </div>
                                    </div>
                                    
                                    <!-- Image Preview Grid -->
                                    <div id="image-preview-grid" class="mt-6 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 hidden">
                                        <!-- Previews will be inserted here -->
                                    </div>
                                    
                                    <div class="error-message hidden mt-2 text-red-600 text-sm"></div>
                                    <div class="mt-4 text-sm text-gray-600">
                                        <strong>Required:</strong> At least 1 photo needed to publish your listing. The first photo will be your main image.
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Navigation Buttons -->
                        <div class="mt-8 pt-6 border-t border-gray-200">
                            <div class="flex justify-between items-center">
                                <button type="button" 
                                        id="prev-btn" 
                                        class="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors hidden">
                                    Previous
                                </button>
                                
                                <div class="flex space-x-3">
                                    <button type="button" 
                                            id="save-draft-btn" 
                                            class="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                                            onclick="saveDraftWithLoading(event)">
                                        <span id="draft-btn-text">Save as Draft</span>
                                        <svg id="draft-btn-spinner" class="hidden animate-spin -ml-1 mr-3 h-5 w-5 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                    </button>
                                    
                                    <button type="button" 
                                            id="next-btn" 
                                            class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                        Continue
                                    </button>
                                    
                                    <button type="submit" 
                                            id="publish-btn" 
                                            class="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors hidden"
                                            onclick="showCreatingListing(event)">
                                        <span id="publish-btn-text">List Item</span>
                                        <svg id="publish-btn-spinner" class="hidden animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="loading-overlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" style="display: none;">
        <div class="bg-white rounded-lg p-8 max-w-sm mx-4 text-center">
            <div class="flex justify-center mb-4">
                <svg class="animate-spin h-12 w-12 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
            </div>
            <h3 id="loading-title" class="text-lg font-semibold text-gray-900 mb-2">Creating listing...</h3>
            <p id="loading-message" class="text-sm text-gray-600">Processing your photos and creating your listing. This may take a moment.</p>
        </div>
    </div>

    <!-- Add Category Modal -->
    <div id="addCategoryModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50" style="display: none;">
        <div class="bg-white rounded-lg p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">Add New Category</h3>
                <button type="button" onclick="hideAddCategoryModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label for="newCategoryName" class="block text-sm font-medium text-gray-700">Category Name</label>
                    <input type="text" id="newCategoryName" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="Enter category name">
                    <div id="categoryError" class="text-red-600 text-sm mt-1"></div>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="hideAddCategoryModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300">
                        Cancel
                    </button>
                    <button type="button" onclick="addCategory()" class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-md hover:bg-green-700">
                        Add Category
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Manufacturer Modal -->
    <div id="addManufacturerModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50" style="display: none;">
        <div class="bg-white rounded-lg p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">Add New Manufacturer</h3>
                <button type="button" onclick="hideAddManufacturerModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label for="newManufacturerName" class="block text-sm font-medium text-gray-700">Manufacturer Name</label>
                    <input type="text" id="newManufacturerName" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="Enter manufacturer name">
                    <div id="manufacturerError" class="text-red-600 text-sm mt-1"></div>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="hideAddManufacturerModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300">
                        Cancel
                    </button>
                    <button type="button" onclick="addManufacturer()" class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-md hover:bg-green-700">
                        Add Manufacturer
                    </button>
                </div>
            </div>
        </div>
    </div>

    <style>
    .step-circle {
        @apply w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-all duration-300;
        @apply border-2 border-gray-300 bg-white text-gray-500;
    }
    
    .step-circle.active {
        @apply border-blue-600 bg-blue-600 text-white;
    }
    
    .step-circle.completed {
        @apply border-green-600 bg-green-600 text-white;
    }
    
    .step-circle .step-number {
        @apply block;
    }
    
    .step-circle .step-check {
        @apply hidden w-4 h-4;
    }
    
    .step-circle.completed .step-number {
        @apply hidden;
    }
    
    .step-circle.completed .step-check {
        @apply block;
    }
    
    .wizard-step {
        @apply transition-all duration-300;
    }
    
    .wizard-step.hidden {
        @apply opacity-0 pointer-events-none absolute inset-0;
    }
    
    .wizard-step.active {
        @apply opacity-100 relative;
    }
    
    /* Custom focus styles for better mobile experience */
    input:focus, textarea:focus, select:focus {
        @apply outline-none ring-2 ring-blue-500 ring-offset-2;
    }
    
    /* Better tap targets for mobile */
    @media (max-width: 768px) {
        input, textarea, select, button {
            @apply text-base;
        }
        
        .step-circle {
            @apply w-10 h-10 text-base;
        }
    }
    </style>

    <script>
    const WIZARD_HAS_SERVER_VALIDATION_ERRORS = <?php echo json_encode($errors->any(), 15, 512) ?>;
    </script>

    <script>
    // Wizard State
    let currentStep = 1;
    const totalSteps = 5;
    let uploadedImages = [];
    const stepLabels = {
        1: 'Step 1: Basic Info',
        2: 'Step 2: Pricing', 
        3: 'Step 3: Details',
        4: 'Step 4: Shipping',
        5: 'Step 5: Photos'
    };

    // Initialize wizard
    document.addEventListener('DOMContentLoaded', function() {
        updateWizardUI();
        setupFormValidation();
        setupListingTypeHandlers();
        setupShippingHandlers();
        setupCharacterCounters();

        // Navigation button handlers
        document.getElementById('next-btn').addEventListener('click', nextStep);
        document.getElementById('prev-btn').addEventListener('click', prevStep);

        // Debounced save on input/change
        let wizardSaveTimer = null;
        function debouncedSave() {
            clearTimeout(wizardSaveTimer);
            wizardSaveTimer = setTimeout(wizardSaveState, 800);
        }
        document.querySelectorAll('#listing-wizard input, #listing-wizard textarea, #listing-wizard select').forEach(function(el) {
            el.addEventListener('input', debouncedSave);
            el.addEventListener('change', debouncedSave);
        });
    });

    function nextStep() {
        if (validateCurrentStep()) {
            if (currentStep < totalSteps) {
                wizardSaveState();
                currentStep++;
                updateWizardUI();
            }
        }
    }

    function prevStep() {
        if (currentStep > 1) {
            wizardSaveState();
            currentStep--;
            updateWizardUI();
        }
    }

    function updateWizardUI() {
        // Update step visibility
        document.querySelectorAll('.wizard-step').forEach((step, index) => {
            const stepNum = index + 1;
            if (stepNum === currentStep) {
                step.classList.remove('hidden');
                step.classList.add('active');
            } else {
                step.classList.add('hidden');
                step.classList.remove('active');
            }
        });

        // Update progress indicators
        document.querySelectorAll('.step-circle').forEach((circle, index) => {
            const stepNum = index + 1;
            circle.classList.remove('active', 'completed');
            
            if (stepNum < currentStep) {
                circle.classList.add('completed');
            } else if (stepNum === currentStep) {
                circle.classList.add('active');
            }
        });

        // Update progress bars
        for (let i = 1; i <= totalSteps - 1; i++) {
            const progressBar = document.getElementById(`progress-bar-${i}`);
            if (progressBar) {
                const width = currentStep > i ? '100%' : currentStep === i ? '50%' : '0%';
                progressBar.style.width = width;
            }
        }

        // Update navigation buttons
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const publishBtn = document.getElementById('publish-btn');

        prevBtn.classList.toggle('hidden', currentStep === 1);
        nextBtn.classList.toggle('hidden', currentStep === totalSteps);
        publishBtn.classList.toggle('hidden', currentStep !== totalSteps);

        // Update mobile step label
        const mobileLabel = document.getElementById('mobile-step-label');
        if (mobileLabel) {
            mobileLabel.textContent = stepLabels[currentStep];
        }

        // Focus first input in current step
        setTimeout(() => {
            const activeStep = document.querySelector('.wizard-step.active');
            const firstInput = activeStep?.querySelector('input, textarea, select');
            if (firstInput && window.innerWidth > 768) {
                firstInput.focus();
            }
        }, 100);
    }

    function validateCurrentStep() {
        const activeStep = document.querySelector('.wizard-step.active');
        let isValid = true;

        // Clear previous error messages
        activeStep.querySelectorAll('.error-message').forEach(msg => {
            msg.classList.add('hidden');
            msg.textContent = '';
        });

        switch(currentStep) {
            case 1:
                isValid = validateBasicInfo();
                break;
            case 2:
                isValid = validatePricing();
                break;
            case 3:
                // Details are optional
                isValid = true;
                break;
            case 4:
                isValid = validateShipping();
                break;
            case 5:
                isValid = validatePhotos();
                break;
        }

        return isValid;
    }

    function validateBasicInfo() {
        let isValid = true;
        
        // Title validation
        const title = document.getElementById('title');
        if (!title.value.trim()) {
            showError('title', 'Please enter a title for your item');
            isValid = false;
        } else if (title.value.length > 255) {
            showError('title', 'Title must be 255 characters or less');
            isValid = false;
        }

        // Description validation
        const description = document.getElementById('description');
        if (!description.value.trim()) {
            showError('description', 'Please add a description of your item');
            isValid = false;
        }

        // Condition validation
        const condition = document.getElementById('condition');
        if (!condition.value) {
            showError('condition', 'Please select the condition of your item');
            isValid = false;
        }

        return isValid;
    }

    function validatePricing() {
        let isValid = true;
        
        // Listing type validation
        const listingType = document.querySelector('input[name="listing_type"]:checked');
        if (!listingType) {
            showError('listing_type', 'Please select a listing type');
            isValid = false;
        }

        // Price validation (required for sale listings)
        const price = document.getElementById('price');
        if (listingType && listingType.value === 'sale' && !price.value) {
            showError('price', 'Price is required for sale listings');
            isValid = false;
        }

        // Quantity validation
        const quantity = document.getElementById('quantity');
        if (!quantity.value || quantity.value < 1) {
            showError('quantity', 'Please enter a valid quantity');
            isValid = false;
        }

        return isValid;
    }

    function validateShipping() {
        const localPickup = document.querySelector('input[name="local_pickup"]').checked;
        const shippingAvailable = document.getElementById('shipping_available').checked;
        
        if (!localPickup && !shippingAvailable) {
            showError('shipping_available', 'Please select at least one delivery option');
            return false;
        }
        
        return true;
    }

    function validatePhotos() {
        if (uploadedImages.length === 0) {
            showError('photos', 'Please add at least one photo of your item');
            return false;
        }
        return true;
    }

    function showError(fieldName, message) {
        const field = document.getElementById(fieldName) || document.querySelector(`[name="${fieldName}"]`);
        if (field) {
            const errorDiv = field.closest('.space-y-6, .space-y-3, div')?.querySelector('.error-message') ||
                           field.parentNode?.querySelector('.error-message');
            if (errorDiv) {
                errorDiv.textContent = message;
                errorDiv.classList.remove('hidden');
            }
            
            // Add error styling to field
            field.classList.add('border-red-300', 'focus:border-red-500', 'focus:ring-red-500');
            field.classList.remove('border-gray-300', 'focus:border-blue-500', 'focus:ring-blue-500');
            
            // Remove error styling when user starts typing
            const removeErrorStyling = () => {
                field.classList.remove('border-red-300', 'focus:border-red-500', 'focus:ring-red-500');
                field.classList.add('border-gray-300', 'focus:border-blue-500', 'focus:ring-blue-500');
                if (errorDiv) {
                    errorDiv.classList.add('hidden');
                }
                field.removeEventListener('input', removeErrorStyling);
                field.removeEventListener('change', removeErrorStyling);
            };
            
            field.addEventListener('input', removeErrorStyling);
            field.addEventListener('change', removeErrorStyling);
        }
    }

    function setupFormValidation() {
        // Real-time validation as user types
        const inputs = document.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            input.addEventListener('blur', () => {
                // Only validate current step fields
                const activeStep = document.querySelector('.wizard-step.active');
                if (activeStep.contains(input)) {
                    validateCurrentStep();
                }
            });
        });
    }

    function setupListingTypeHandlers() {
        const listingTypeInputs = document.querySelectorAll('input[name="listing_type"]');
        listingTypeInputs.forEach(input => {
            input.addEventListener('change', function() {
                const priceSection = document.getElementById('price-section');
                const priceInput = document.getElementById('price');
                const priceRequired = document.getElementById('price-required');
                const priceHelp = document.getElementById('price-help');
                
                if (this.value === 'sale') {
                    priceRequired.style.display = 'inline';
                    priceInput.required = true;
                    priceHelp.textContent = 'Enter the price you want for this item';
                } else if (this.value === 'inventory_open') {
                    priceRequired.style.display = 'none';
                    priceInput.required = false;
                    priceHelp.textContent = 'Optional: Set a reference price for offers';
                } else {
                    priceRequired.style.display = 'none';
                    priceInput.required = false;
                    priceHelp.textContent = 'Optional: For your own records';
                }
            });
        });
    }

    function setupShippingHandlers() {
        const shippingCheckbox = document.getElementById('shipping_available');
        const shippingCostSection = document.getElementById('shipping-cost-section');
        
        shippingCheckbox.addEventListener('change', function() {
            if (this.checked) {
                shippingCostSection.classList.remove('hidden');
            } else {
                shippingCostSection.classList.add('hidden');
                document.getElementById('shipping_cost').value = '';
            }
        });
    }

    function setupCharacterCounters() {
        const titleInput = document.getElementById('title');
        const titleCounter = document.getElementById('title-counter');
        
        titleInput.addEventListener('input', function() {
            titleCounter.textContent = this.value.length;
            if (this.value.length > 255) {
                titleCounter.parentNode.classList.add('text-red-600');
                titleCounter.parentNode.classList.remove('text-gray-500');
            } else {
                titleCounter.parentNode.classList.remove('text-red-600');
                titleCounter.parentNode.classList.add('text-gray-500');
            }
        });
    }

    function saveDraft() {
        const form = document.getElementById('listing-wizard');
        const draftInput = document.createElement('input');
        draftInput.type = 'hidden';
        draftInput.name = 'save_as_draft';
        draftInput.value = '1';
        form.appendChild(draftInput);
        wizardClearState();
        form.submit();
    }

    function saveDraftWithLoading(event) {
        event.preventDefault();
        
        // Show button loading state
        const draftBtn = document.getElementById('save-draft-btn');
        const draftBtnText = document.getElementById('draft-btn-text');
        const draftBtnSpinner = document.getElementById('draft-btn-spinner');
        
        draftBtn.disabled = true;
        draftBtn.classList.add('opacity-75', 'cursor-not-allowed');
        draftBtnText.textContent = 'Saving...';
        draftBtnSpinner.classList.remove('hidden');
        
        // Show loading overlay
        showLoadingOverlay('Saving draft...', 'Your draft is being saved.');
        
        // Disable other buttons
        disableAllButtons();
        
        // Submit form
        setTimeout(() => {
            saveDraft();
        }, 100);
    }

    function showCreatingListing(event) {
        // Only show loading if validation passes
        if (currentStep === 5 && validateCurrentStep()) {
            event.preventDefault();

            // Show button loading state
            const publishBtn = document.getElementById('publish-btn');
            const publishBtnText = document.getElementById('publish-btn-text');
            const publishBtnSpinner = document.getElementById('publish-btn-spinner');

            publishBtn.disabled = true;
            publishBtn.classList.add('opacity-75', 'cursor-not-allowed');
            publishBtnText.textContent = 'Creating...';
            publishBtnSpinner.classList.remove('hidden');

            // Show loading overlay
            showLoadingOverlay('Creating listing...', 'Processing your photos and creating your listing. This may take a moment.');

            // Disable all buttons
            disableAllButtons();

            // Submit form after a short delay to allow UI updates
            setTimeout(() => {
                wizardClearState();
                document.getElementById('listing-wizard').submit();
            }, 100);
        }
    }

    function showLoadingOverlay(title, message) {
        const overlay = document.getElementById('loading-overlay');
        const titleElement = document.getElementById('loading-title');
        const messageElement = document.getElementById('loading-message');
        
        titleElement.textContent = title;
        messageElement.textContent = message;
        overlay.style.display = 'flex';
        
        // Prevent page scrolling while loading
        document.body.style.overflow = 'hidden';
    }

    function hideLoadingOverlay() {
        const overlay = document.getElementById('loading-overlay');
        overlay.style.display = 'none';
        document.body.style.overflow = 'auto';
        
        // Re-enable buttons
        enableAllButtons();
    }

    function disableAllButtons() {
        const buttons = document.querySelectorAll('button');
        buttons.forEach(btn => {
            btn.disabled = true;
            btn.classList.add('opacity-75', 'cursor-not-allowed');
        });
    }

    function enableAllButtons() {
        const buttons = document.querySelectorAll('button');
        buttons.forEach(btn => {
            btn.disabled = false;
            btn.classList.remove('opacity-75', 'cursor-not-allowed');
        });

        // Reset button states
        const publishBtn = document.getElementById('publish-btn');
        const publishBtnText = document.getElementById('publish-btn-text');
        const publishBtnSpinner = document.getElementById('publish-btn-spinner');

        publishBtnText.textContent = 'List Item';
        publishBtnSpinner.classList.add('hidden');

        const draftBtn = document.getElementById('save-draft-btn');
        const draftBtnText = document.getElementById('draft-btn-text');
        const draftBtnSpinner = document.getElementById('draft-btn-spinner');

        draftBtnText.textContent = 'Save as Draft';
        draftBtnSpinner.classList.add('hidden');
    }

    // ============================================================================
    // localStorage State Persistence Module
    // ============================================================================

    /**
     * wizardSaveState() — reads all field values from DOM, writes JSON to localStorage
     */
    function wizardSaveState() {
        try {
            const state = {
                title: document.getElementById('title')?.value || '',
                description: document.getElementById('description')?.value || '',
                condition: document.getElementById('condition')?.value || '',
                listing_type: document.querySelector('input[name="listing_type"]:checked')?.value || '',
                price: document.getElementById('price')?.value || '',
                quantity: document.getElementById('quantity')?.value || '',
                open_to_trades: document.querySelector('input[name="open_to_trades"]')?.checked || false,
                category_id: document.getElementById('category_id')?.value || '',
                manufacturer_id: document.getElementById('manufacturer_id')?.value || '',
                model: document.getElementById('model')?.value || '',
                local_pickup: document.querySelector('input[name="local_pickup"]')?.checked || false,
                shipping_available: document.getElementById('shipping_available')?.checked || false,
                shipping_cost: document.getElementById('shipping_cost')?.value || '',
                step: currentStep,
                savedAt: Date.now()
            };
            localStorage.setItem('xeek_wizard_draft', JSON.stringify(state));
        } catch (e) {
            // localStorage unavailable (private browsing, quota exceeded, etc.) — fail gracefully
            console.warn('localStorage unavailable:', e);
        }
    }

    /**
     * wizardLoadState() — reads and validates saved state
     */
    function wizardLoadState() {
        try {
            if (WIZARD_HAS_SERVER_VALIDATION_ERRORS) {
                return null;
            }

            const saved = localStorage.getItem('xeek_wizard_draft');
            if (!saved) {
                return null;
            }

            const state = JSON.parse(saved);

            // Discard data older than 7 days
            if (state.savedAt && (Date.now() - state.savedAt) > 7 * 24 * 60 * 60 * 1000) {
                wizardClearState();
                return null;
            }

            return state;
        } catch (e) {
            console.warn('Error loading wizard state:', e);
            return null;
        }
    }

    /**
     * wizardClearState() — removes saved state from localStorage
     */
    function wizardClearState() {
        try {
            localStorage.removeItem('xeek_wizard_draft');
        } catch (e) {
            console.warn('Error clearing wizard state:', e);
        }
    }

    /**
     * wizardRestoreState(state) — applies saved field values to the DOM
     */
    function wizardRestoreState(state) {
        if (!state) return;

        // Simple inputs and textareas
        const titleInput = document.getElementById('title');
        if (titleInput && state.title) {
            titleInput.value = state.title;
            // Update character counter
            const titleCounter = document.getElementById('title-counter');
            if (titleCounter) {
                titleCounter.textContent = state.title.length;
                if (state.title.length > 255) {
                    titleCounter.parentNode?.classList.add('text-red-600');
                    titleCounter.parentNode?.classList.remove('text-gray-500');
                } else {
                    titleCounter.parentNode?.classList.remove('text-red-600');
                    titleCounter.parentNode?.classList.add('text-gray-500');
                }
            }
        }

        const descriptionInput = document.getElementById('description');
        if (descriptionInput && state.description) {
            descriptionInput.value = state.description;
        }

        const conditionInput = document.getElementById('condition');
        if (conditionInput && state.condition) {
            conditionInput.value = state.condition;
        }

        const modelInput = document.getElementById('model');
        if (modelInput && state.model) {
            modelInput.value = state.model;
        }

        const priceInput = document.getElementById('price');
        if (priceInput && state.price) {
            priceInput.value = state.price;
        }

        const quantityInput = document.getElementById('quantity');
        if (quantityInput && state.quantity) {
            quantityInput.value = state.quantity;
        }

        const shippingCostInput = document.getElementById('shipping_cost');
        if (shippingCostInput && state.shipping_cost) {
            shippingCostInput.value = state.shipping_cost;
        }

        // Radio group (listing_type)
        if (state.listing_type) {
            const listingTypeRadio = document.querySelector(`input[name="listing_type"][value="${state.listing_type}"]`);
            if (listingTypeRadio) {
                listingTypeRadio.checked = true;
                listingTypeRadio.dispatchEvent(new Event('change', { bubbles: true }));
            }
        }

        // Checkboxes
        const openToTradesCheckbox = document.querySelector('input[name="open_to_trades"]');
        if (openToTradesCheckbox) {
            openToTradesCheckbox.checked = state.open_to_trades || false;
        }

        const localPickupCheckbox = document.querySelector('input[name="local_pickup"]');
        if (localPickupCheckbox) {
            localPickupCheckbox.checked = state.local_pickup || false;
        }

        const shippingAvailableCheckbox = document.getElementById('shipping_available');
        if (shippingAvailableCheckbox) {
            shippingAvailableCheckbox.checked = state.shipping_available || false;
            shippingAvailableCheckbox.dispatchEvent(new Event('change', { bubbles: true }));
        }

        // Choices.js selects (only if Choices instances exist)
        if (typeof categoryChoice !== 'undefined' && state.category_id) {
            try {
                categoryChoice.setChoiceByValue(String(state.category_id));
            } catch (e) {
                console.warn('Could not restore category:', e);
            }
        }

        if (typeof manufacturerChoice !== 'undefined' && state.manufacturer_id) {
            try {
                manufacturerChoice.setChoiceByValue(String(state.manufacturer_id));
            } catch (e) {
                console.warn('Could not restore manufacturer:', e);
            }
        }

        // Restore step
        currentStep = state.step || 1;
        updateWizardUI();
    }

    /**
     * wizardShowResumeBanner(state) — inserts a dismissible blue notice
     */
    function wizardShowResumeBanner(state) {
        if (!state) return;

        const stepName = stepLabels[state.step] || 'Step ' + state.step;

        const bannerHTML = `
            <div id="wizard-resume-banner" class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg relative">
                <button id="banner-close-btn" type="button" class="absolute top-2 right-2 text-gray-400 hover:text-gray-600">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                </button>
                <div class="flex items-start">
                    <svg class="w-5 h-5 text-blue-500 mt-0.5 mr-3 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M18 5v8a2 2 0 01-2 2h-5l-5 4v-4H4a2 2 0 01-2-2V5a2 2 0 012-2h12a2 2 0 012 2zm-11-1a1 1 0 100-2H7a1 1 0 000 2h1zm3 0a1 1 0 100-2h-1a1 1 0 000 2h1zm3 0a1 1 0 100-2h-1a1 1 0 000 2h1z" clip-rule="evenodd" />
                    </svg>
                    <div>
                        <p class="text-sm text-blue-800">
                            <strong>Your previous listing has been restored (${stepName}).</strong> Photos need to be re-added.
                            <a href="#" id="start-fresh-link" class="font-semibold underline hover:text-blue-700">Start fresh</a>
                        </p>
                    </div>
                </div>
            </div>
        `;

        const wizardForm = document.getElementById('listing-wizard');
        wizardForm?.insertAdjacentHTML('beforebegin', bannerHTML);

        // Attach event listeners to the banner
        const closeBtn = document.getElementById('banner-close-btn');
        if (closeBtn) {
            closeBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const banner = document.getElementById('wizard-resume-banner');
                banner?.remove();
            });
        }

        const startFreshLink = document.getElementById('start-fresh-link');
        if (startFreshLink) {
            startFreshLink.addEventListener('click', function(e) {
                e.preventDefault();
                wizardStartFresh();
            });
        }
    }

    /**
     * wizardStartFresh() — clears state and reloads the page
     */
    function wizardStartFresh() {
        wizardClearState();
        location.reload();
    }

    // Image handling functions (preserved from original)
    function compressImage(file, maxWidth = 1200, maxHeight = 1200, quality = 0.8) {
        return new Promise((resolve) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();
            
            img.onload = function() {
                let { width, height } = img;
                
                if (width > maxWidth || height > maxHeight) {
                    const ratio = Math.min(maxWidth / width, maxHeight / height);
                    width = width * ratio;
                    height = height * ratio;
                }
                
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                
                canvas.toBlob(function(blob) {
                    const compressedFile = new File([blob], file.name, {
                        type: file.type,
                        lastModified: Date.now()
                    });
                    resolve(compressedFile);
                }, file.type, quality);
            };
            
            img.src = URL.createObjectURL(file);
        });
    }

    async function handleImageUpload(event) {
        const files = Array.from(event.target.files);
        
        for (let [index, file] of files.entries()) {
            if (file.type.startsWith('image/')) {
                const compressedFile = await compressImage(file);
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const imageData = {
                        file: compressedFile,
                        src: e.target.result,
                        id: Date.now() + index,
                        rotation: 0
                    };
                    uploadedImages.push(imageData);
                    renderImagePreviews();
                    updateFileInput();
                };
                reader.readAsDataURL(compressedFile);
            }
        }
    }

    function renderImagePreviews() {
        const grid = document.getElementById('image-preview-grid');
        const uploadArea = document.getElementById('upload-area');
        
        if (uploadedImages.length === 0) {
            grid.classList.add('hidden');
            uploadArea.classList.remove('hidden');
            return;
        }
        
        grid.classList.remove('hidden');
        uploadArea.classList.add('hidden');
        
        const imageHTML = uploadedImages.map((image, index) => `
            <div class="relative group border-2 border-gray-200 rounded-lg overflow-hidden bg-gray-50 aspect-square" 
                 draggable="true" 
                 ondragstart="dragStart(event, ${index})" 
                 ondragover="dragOver(event)" 
                 ondrop="dragDrop(event, ${index})">
                <img src="${image.src}" 
                     alt="Preview ${index + 1}" 
                     class="w-full h-full object-cover transition-transform duration-200">
                
                ${index === 0 ? '<div class="absolute top-2 left-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">Main</div>' : ''}
                
                <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-opacity duration-200 flex items-center justify-center opacity-0 group-hover:opacity-100">
                    <div class="flex space-x-2">
                        <button type="button" onclick="rotateImage(${index})" class="p-2 bg-white rounded-full hover:bg-gray-100 transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                        </button>
                        <button type="button" onclick="removeImage(${index})" class="p-2 bg-white rounded-full hover:bg-gray-100 transition-colors text-red-600">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <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>
        `).join('');
        
        grid.innerHTML = imageHTML + `
            <div class="border-2 border-dashed border-gray-300 rounded-lg aspect-square flex items-center justify-center cursor-pointer hover:border-gray-400 transition-colors" onclick="document.getElementById('photos').click()">
                <div class="text-center text-gray-500">
                    <svg class="mx-auto h-8 w-8 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                    </svg>
                    <span class="text-sm">Add More</span>
                </div>
            </div>
        `;
    }

    function rotateImage(index) {
        const imageData = uploadedImages[index];
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        
        img.onload = function() {
            canvas.width = img.height;
            canvas.height = img.width;
            
            ctx.save();
            ctx.translate(canvas.width / 2, canvas.height / 2);
            ctx.rotate(Math.PI / 2);
            ctx.drawImage(img, -img.width / 2, -img.height / 2);
            ctx.restore();
            
            canvas.toBlob(function(blob) {
                const rotatedFile = new File([blob], imageData.file.name, {
                    type: imageData.file.type,
                    lastModified: Date.now()
                });
                
                imageData.file = rotatedFile;
                imageData.src = canvas.toDataURL();
                
                updateFileInput();
                renderImagePreviews();
            }, imageData.file.type, 0.9);
        };
        
        img.src = imageData.src;
    }

    function removeImage(index) {
        uploadedImages.splice(index, 1);
        updateFileInput();
        renderImagePreviews();
    }

    function updateFileInput() {
        const fileInput = document.getElementById('photos');
        const dataTransfer = new DataTransfer();
        
        uploadedImages.forEach(imageData => {
            dataTransfer.items.add(imageData.file);
        });
        
        fileInput.files = dataTransfer.files;
    }

    let draggedIndex = null;

    function dragStart(event, index) {
        draggedIndex = index;
        event.dataTransfer.effectAllowed = 'move';
    }

    function dragOver(event) {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'move';
    }

    function dragDrop(event, targetIndex) {
        event.preventDefault();
        
        if (draggedIndex !== null && draggedIndex !== targetIndex) {
            const draggedItem = uploadedImages.splice(draggedIndex, 1)[0];
            uploadedImages.splice(targetIndex, 0, draggedItem);
            
            updateFileInput();
            renderImagePreviews();
        }
        
        draggedIndex = null;
    }

    // Modal functions
    function showAddCategoryModal() {
        document.getElementById('addCategoryModal').style.display = 'flex';
    }

    function hideAddCategoryModal() {
        document.getElementById('addCategoryModal').style.display = 'none';
        document.getElementById('newCategoryName').value = '';
        document.getElementById('categoryError').textContent = '';
    }

    async function addCategory() {
        const name = document.getElementById('newCategoryName').value.trim();
        const errorDiv = document.getElementById('categoryError');
        
        if (!name) {
            errorDiv.textContent = 'Category name is required.';
            return;
        }

        try {
            const response = await fetch('<?php echo e(route("categories.store")); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({ name: name })
            });

            const data = await response.json();

            if (data.success) {
                // Add new option to select
                const select = document.getElementById('category_id');
                const option = new Option(data.category.name, data.category.id);
                select.add(option);
                select.value = data.category.id;
                
                hideAddCategoryModal();
            } else {
                errorDiv.textContent = data.message || 'Failed to create category.';
            }
        } catch (error) {
            errorDiv.textContent = 'An error occurred. Please try again.';
        }
    }

    function showAddManufacturerModal() {
        document.getElementById('addManufacturerModal').style.display = 'flex';
    }

    function hideAddManufacturerModal() {
        document.getElementById('addManufacturerModal').style.display = 'none';
        document.getElementById('newManufacturerName').value = '';
        document.getElementById('manufacturerError').textContent = '';
    }

    async function addManufacturer() {
        const name = document.getElementById('newManufacturerName').value.trim();
        const errorDiv = document.getElementById('manufacturerError');
        
        if (!name) {
            errorDiv.textContent = 'Manufacturer name is required.';
            return;
        }

        try {
            const response = await fetch('<?php echo e(route("manufacturers.store")); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({ name: name })
            });

            const data = await response.json();

            if (data.success) {
                // Add new option to select
                const select = document.getElementById('manufacturer_id');
                const option = new Option(data.manufacturer.name, data.manufacturer.id);
                select.add(option);
                select.value = data.manufacturer.id;
                
                hideAddManufacturerModal();
            } else {
                errorDiv.textContent = data.message || 'Failed to create manufacturer.';
            }
        } catch (error) {
            errorDiv.textContent = 'An error occurred. Please try again.';
        }
    }

    // Enhanced Choices.js functionality for searchable dropdowns
    let categoryChoice, manufacturerChoice;
    
    function initChoicesJS() {
        console.log('Initializing Choices.js for searchable dropdowns...');
        
        // Check if Choices is available
        if (typeof Choices === 'undefined') {
            console.error('Choices.js not loaded! Retrying in 100ms...');
            setTimeout(initChoicesJS, 100);
            return;
        }
        
        // Initialize enhanced category dropdown
        console.log('Initializing category dropdown...');
        categoryChoice = new Choices('#category_id', {
            searchEnabled: true,
            searchChoices: true,
            addItems: true,
            addItemFilter: (value) => value && value.length > 2,
            searchPlaceholderValue: 'Start typing to search categories...',
            noChoicesText: 'Press Enter to add this category',
            itemSelectText: '',
            shouldSort: false
        });

        // Initialize enhanced manufacturer dropdown  
        console.log('Initializing manufacturer dropdown...');
        manufacturerChoice = new Choices('#manufacturer_id', {
            searchEnabled: true,
            searchChoices: true,
            addItems: true,
            addItemFilter: (value) => value && value.length > 2,
            searchPlaceholderValue: 'Start typing to search manufacturers...',
            noChoicesText: 'Press Enter to add this manufacturer',
            itemSelectText: '',
            shouldSort: false
        });

        // Listen for new items being added to manufacturer dropdown
        manufacturerChoice.passedElement.element.addEventListener('addItem', function(event) {
            console.log('New manufacturer item added:', event.detail);
            const value = event.detail.value;
            
            // Check if this is a newly typed value (not an existing option)
            const existingOptions = Array.from(document.getElementById('manufacturer_id').options);
            const isExisting = existingOptions.some(option => option.value === value);
            
            if (!isExisting && value && value.length > 2) {
                console.log('Creating new manufacturer:', value);
                createNewManufacturer(value);
            }
        });

        // Listen for new items being added to category dropdown
        categoryChoice.passedElement.element.addEventListener('addItem', function(event) {
            console.log('New category item added:', event.detail);
            const value = event.detail.value;
            
            // Check if this is a newly typed value (not an existing option)
            const existingOptions = Array.from(document.getElementById('category_id').options);
            const isExisting = existingOptions.some(option => option.value === value);
            
            if (!isExisting && value && value.length > 2) {
                console.log('Creating new category:', value);
                createNewCategory(value);
            }
        });

        // Restore saved wizard state
        const savedWizardState = wizardLoadState();
        if (savedWizardState) {
            wizardRestoreState(savedWizardState);
            wizardShowResumeBanner(savedWizardState);
        }

        console.log('Choices.js initialization complete');
    }

    // Function to create new category via API
    function createNewCategory(name) {
        console.log('Creating new category:', name);
        fetch('/api/categories', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ name: name })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Category creation response:', data);
            if (data.success) {
                // Remove the temporary text option and add the real category
                categoryChoice.removeActiveItems();
                categoryChoice.setChoices([{
                    value: data.category.id,
                    label: data.category.name,
                    selected: true
                }], 'value', 'label', true);
            } else {
                alert('Error creating category: ' + (data.message || 'Unknown error'));
                categoryChoice.removeActiveItems();
            }
        })
        .catch(error => {
            console.error('Error creating category:', error);
            alert('Error creating category');
            categoryChoice.removeActiveItems();
        });
    }

    // Function to create new manufacturer via API
    function createNewManufacturer(name) {
        console.log('Creating new manufacturer:', name);
        fetch('/api/manufacturers', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ name: name })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Manufacturer creation response:', data);
            if (data.success) {
                // Remove the temporary text option and add the real manufacturer
                manufacturerChoice.removeActiveItems();
                manufacturerChoice.setChoices([{
                    value: data.manufacturer.id,
                    label: data.manufacturer.name,
                    selected: true
                }], 'value', 'label', true);
            } else {
                alert('Error creating manufacturer: ' + (data.message || 'Unknown error'));
                manufacturerChoice.removeActiveItems();
            }
        })
        .catch(error => {
            console.error('Error creating manufacturer:', error);
            alert('Error creating manufacturer');
            manufacturerChoice.removeActiveItems();
        });
    }

    // Initialize Choices.js when wizard is ready
    const originalDOMContentLoaded = document.addEventListener;
    document.addEventListener('DOMContentLoaded', function() {
        // Wait a bit for the wizard to initialize first
        setTimeout(initChoicesJS, 500);
    });
    </script>

    <!-- Load Choices.js directly here to ensure it loads before our script -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?><?php /**PATH /var/www/html/resources/views/items/create-wizard.blade.php ENDPATH**/ ?>