@props([
    'options' => [],
    'variants' => [],
    'selectedVariants' => [],
])
<div x-data='variationBuilder("{{ app()->getLocale() }}", @json($options), @json($variants), @json($selectedVariants))' x-id="['variation-builder']">
    <!-- Hidden inputs for form submission -->
    <input type="hidden" name="options" :value="JSON.stringify(options)">
    <input type="hidden" name="variants" :value="JSON.stringify(prepareVariantsForSubmission())">
    
    <div class="grid grid-cols-2">
        <div>
            <h2 class="mb-6 mt-6">{{ __('daylight::store.product_options') }}</h2>

            <ul x-ref="optionsContainer">
                <template x-for="(option, index) in options" :key="option.id">
                    <li :data-option-id="option.id">
                        <div class="flex items-center justify-between p-4 mb-2 border rounded">
                            <div class="flex items-center">
                                <svg class="options-handle w-4 h-4 mr-3 text-gray-400 cursor-move" data-slot="icon" fill="none"
                                     stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24"
                                     xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="M3 7.5 7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"></path>
                                </svg>

                                <div>
                                    <p class="text-sm font-semibold" x-text="option.translations[currentLocale].name"/>
                                    <p class="text-xs opacity-50" x-text="getOptionValueLine(option.optionValues)"/>
                                </div>
                            </div>

                            <div class="flex items-center gap-3">
                                <button @click.prevent="currentOption = option; isCreatingNewOption = false; showOptionSlideOver = true;"
                                        class="p-2 bg-gray-200 rounded-full hover:bg-sky-600 hover:text-white transition">
                                    <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5"
                                         stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"
                                         aria-hidden="true">
                                        <path stroke-linecap="round" stroke-linejoin="round"
                                              d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
                                    </svg>
                                </button>

                                <button @click.prevent="deleteOption(option.id)"
                                        class="p-2 bg-gray-200 rounded-full hover:bg-red-500 hover:text-white transition">
                                    <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5"
                                         stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"
                                         aria-hidden="true">
                                        <path stroke-linecap="round" stroke-linejoin="round"
                                              d="M6 18 18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </li>
                </template>
            </ul>

            <button @click.prevent="createOption" type="button"
                    class="rounded-md mt-4 w-full border border-dashed border-gray-300 hover:border-gray-700 transition text-gray-500  hover:text-gray-900 py-5 font-semibold text-sm flex items-center justify-center">
                <svg class="w-4 h-4 mr-3" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor"
                     viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round"
                          d="M12 9v6m3-3H9m12 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"></path>
                </svg>

                {{ __('daylight::store.add_new_option') }}
            </button>
        </div>

        <x-daylight::variation-builder.option-slide-over/>
    </div>

    <div class="mt-12">
        <h2 class="mb-6">{{ __('daylight::store.product_variations') }}</h2>

        <table class="-mx-2" x-show="variants.length > 0">
            <thead>
                <tr class="font-semibold">
                    <td class="text-sm px-2">{{ __('daylight::store.option') }}</td>
                    <td class="text-sm px-2">{{ __('daylight::general.sku') }}</td>
                </tr>
            </thead>
            <tbody>
                <template x-for="(variant, index) in variants" :key="index">
                    <tr>
                        <td class="text-sm px-2 w-[150px]">
                            <div class="py-2" x-text="getVariantLabel(variant)"></div>
                        </td>
                        <td class="px-2 py-2 w-[320px]">
                            <div x-data="skuInput(variant)">
                                <!-- Preview Mode -->
                                <div x-show="selectedVariant" class="flex items-center gap-3 p-2 border border-gray-300 rounded-md bg-gray-50">
                                    <div class="w-10 h-10 flex-shrink-0">
                                        <div x-show="selectedVariant && !selectedVariant.image" class="w-10 h-10 flex items-center justify-center text-gray-500 rounded border bg-gray-100">
                                            <svg class="w-4 h-4" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"></path>
                                            </svg>
                                        </div>
                                        <img x-show="selectedVariant && selectedVariant.image" :src="selectedVariant && selectedVariant.image" :alt="selectedVariant && selectedVariant.name" class="object-cover w-10 h-10 rounded border">
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-sm font-medium" x-text="selectedVariant && selectedVariant.sku"></p>
                                        <p class="text-xs text-gray-500 truncate" x-text="selectedVariant && selectedVariant.name"></p>
                                    </div>
                                    <button @click.prevent="clearSelection" type="button" class="text-gray-400 hover:text-gray-600">
                                        <svg class="w-4 h-4" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"></path>
                                        </svg>
                                    </button>
                                </div>

                                <!-- Input Mode -->
                                <div x-show="!selectedVariant" class="relative">
                                    <input 
                                        type="text" 
                                        x-model="searchQuery"
                                        @input="handleInput"
                                        @focus="handleFocus"
                                        x-ref="input"
                                        class="text-sm border w-full h-10 rounded-md pr-7"
                                        :class="{ 'border-red-500': errorMessage, 'border-gray-400': !errorMessage }"
                                        placeholder="{{ __('daylight::store.enter_sku') }}"
                                    />

                                    <div x-show="errorMessage" class="absolute top-3 right-3 text-red-600">
                                        <svg class="w-4 h-4" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"></path>
                                        </svg>
                                    </div>

                                    <!-- Autocomplete Dropdown -->
                                    <div x-show="showAutocomplete && results.length > 0" 
                                         @click.outside="showAutocomplete = false"
                                         class="absolute top-10 border bg-white z-50 max-h-64 rounded w-[300px] overflow-y-auto shadow-lg"
                                         style="display: none;">
                                        <ul>
                                            <template x-for="result in results" :key="result.id">
                                                <li>
                                                    <a href="#" 
                                                       @click.prevent="selectOption(result)" 
                                                       class="flex w-full p-3 hover:bg-gray-100 truncate whitespace-nowrap">
                                                        <div class="w-12 flex-shrink-0 min-w-12">
                                                            <div x-show="!result.image" class="w-10 h-10 flex items-center justify-center text-gray-500 rounded border mr-1 bg-gray-100">
                                                                <svg class="w-4 h-4" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"></path>
                                                                </svg>
                                                            </div>
                                                            <img x-show="result.image" :src="result.image" :alt="result.name" class="object-cover w-10 h-10 rounded border mr-1">
                                                        </div>
                                                        <div class="flex-0 truncate">
                                                            <p class="text-sm" x-text="result.sku"></p>
                                                            <p class="text-xs opacity-50 truncate" x-text="result.name"></p>
                                                        </div>
                                                    </a>
                                                </li>
                                            </template>
                                        </ul>
                                    </div>

                                    <div x-show="errorMessage" class="text-sm text-red-600 mt-1" x-text="errorMessage"></div>
                                </div>
                            </div>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>

        <div x-show="variants.length === 0" class="text-sm text-gray-500 py-8 text-center">
            {{ __('daylight::store.no_variations_message') }}
        </div>
    </div>
</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('variationBuilder', (currentLocale, options, serverVariants = [], selectedVariants = []) => ({
            options,
            currentLocale,
            showOptionSlideOver: false,
            isCreatingNewOption: false,
            optionsSortableInstance: null,
            variants: [],
            serverVariants,
            selectedVariants,

            currentOption: {
                id: null,
                order: null,
                translations: @json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales()->mapWithKeys(function($locale) { return [$locale => ['name' => '']]; })),
                type: 'buttons',
                optionValues: []
            },

            init() {
                // Sort options once on initial load
                this.options.sort((a, b) => {
                    const orderA = a.order !== null && a.order !== undefined ? a.order : 0;
                    const orderB = b.order !== null && b.order !== undefined ? b.order : 0;
                    return orderA - orderB;
                });

                this.$nextTick(() => {
                    if (this.$refs.optionsContainer) {
                        this.optionsSortableInstance = new Sortable(this.$refs.optionsContainer, {
                            animation: 150,
                            handle: '.options-handle',
                            dataIdAttr: 'data-option-id',
                        });
                    }
                });

                // Generate variants on init
                this.generateVariants();

                // Watch for changes in options to regenerate variants
                this.$watch('options', () => {
                    this.generateVariants();
                }, { deep: true });
            },

            generateVariants() {
                if (!this.options || this.options.length === 0) {
                    this.variants = [];
                    return;
                }

                // Filter options that have at least one option value
                const validOptions = this.options.filter(opt => opt.optionValues && opt.optionValues.length > 0);

                if (validOptions.length === 0) {
                    this.variants = [];
                    return;
                }

                // Generate all combinations
                const combinations = this.generateCombinations(validOptions);
                
                // Merge with existing variants to preserve SKU data
                this.variants = combinations.map(combo => {
                    // Try to find existing variant with same combination from current variants
                    const existingCurrent = this.variants.find(v => 
                        v.optionValues && JSON.stringify(v.optionValues) === JSON.stringify(combo.optionValues)
                    );
                    
                    // Try to find variant from server (on initial load) using serverVariants
                    const serverVariant = this.serverVariants.find(sv => {
                        if (!sv.optionValues || sv.optionValues.length !== combo.optionValues.length) {
                            return false;
                        }
                        
                        // Check if all option values match
                        return combo.optionValues.every(ov => 
                            sv.optionValues.some(sov => 
                                sov.option_id == ov.option_id && sov.option_value_id == ov.option_value_id
                            )
                        );
                    });
                    
                    // Find the full variant data from selectedVariants if we have a match
                    let variantData = null;
                    if (serverVariant && serverVariant.sku) {
                        variantData = this.selectedVariants.find(sv => sv.sku === serverVariant.sku);
                    }
                    
                    // Priority: current variant data > server variant > empty
                    if (existingCurrent && existingCurrent.sku) {
                        return existingCurrent;
                    } else if (serverVariant) {
                        return {
                            optionValues: combo.optionValues,
                            sku: serverVariant.sku || '',
                            variantData: variantData || null
                        };
                    } else {
                        return {
                            optionValues: combo.optionValues,
                            sku: '',
                            variantData: null
                        };
                    }
                });
            },

            generateCombinations(options, index = 0, current = []) {
                if (index === options.length) {
                    return [{ optionValues: [...current], sku: '' }];
                }

                const option = options[index];
                const results = [];

                for (const optionValue of option.optionValues) {
                    const combinations = this.generateCombinations(
                        options, 
                        index + 1, 
                        [...current, {
                            option_id: option.id,
                            option_value_id: optionValue.id,
                            option_name: option.translations[this.currentLocale].name,
                            value_name: optionValue.translations[this.currentLocale].name
                        }]
                    );
                    results.push(...combinations);
                }

                return results;
            },

            getVariantLabel(variant) {
                return variant.optionValues
                    .map(ov => ov.value_name)
                    .join(' / ');
            },

            syncOptionsArrayWithDOM() {
                if (this.optionsSortableInstance) {
                    const newOrder = this.optionsSortableInstance.toArray();
                    
                    const reordered = newOrder.map((id, index) => {
                        const opt = this.options.find(o => o.id == id);
                        if (opt) {
                            opt.order = index;
                        }
                        return opt;
                    }).filter(Boolean);
                    
                    this.options.length = 0;
                    this.options.push(...reordered);
                }
            },

            getOptionValueLine(optionValues) {
                return optionValues.map(optionValue => {
                    return optionValue.translations[currentLocale].name
                }).join(' / ')
            },

            createOption() {
                // Find the highest order value
                const maxOrder = this.options.reduce((max, opt) => {
                    return Math.max(max, opt.order || 0);
                }, -1);

                this.currentOption = {
                    id: 'option_' + Date.now(),
                    order: maxOrder + 1,
                    translations: @json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales()->mapWithKeys(function($locale) { return [$locale => ['name' => '']]; })),
                    type: 'buttons',
                    optionValues: []
                };

                this.isCreatingNewOption = true;
                this.showOptionSlideOver = true;
            },

            deleteOption(id) {
                const index = this.options.findIndex(o => o.id == id);
                
                if (index !== -1) {
                    this.options.splice(index, 1);
                    
                    // Update order for remaining items
                    this.options.forEach((opt, idx) => {
                        opt.order = idx;
                    });
                }
            },

            close() {
                this.showOptionSlideOver = false;
                this.isCreatingNewOption = false;

                setTimeout(() => {
                    this.resetCurrentOption();
                }, 300);
            },

            resetCurrentOption() {
                this.currentOption = {
                    id: null,
                    order: null,
                    translations: @json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales()->mapWithKeys(function($locale) { return [$locale => ['name' => '']]; })),
                    type: 'buttons',
                    optionValues: []
                };
            },

            prepareVariantsForSubmission() {
                return this.variants.map(variant => ({
                    sku: variant.sku || '',
                    optionValues: variant.optionValues.map(ov => ({
                        option_id: ov.option_id,
                        option_value_id: ov.option_value_id
                    }))
                }));
            },

            validateOptions() {
                const errors = [];

                // Check if there are options
                if (!this.options || this.options.length === 0) {
                    errors.push('{{ __("daylight::store.at_least_one_option_required") }}');
                    return errors;
                }

                // Validate each option
                this.options.forEach((option, index) => {
                    // Check option name
                    const hasName = Object.values(option.translations).some(t => t.name && t.name.trim());
                    if (!hasName) {
                        errors.push(`{{ __("daylight::store.option_name_required") }} #${index + 1}`);
                    }

                    // Check if option has values
                    if (!option.optionValues || option.optionValues.length === 0) {
                        errors.push(`{{ __("daylight::store.option_values_required") }} "${option.translations[this.currentLocale]?.name || index + 1}"`);
                    } else {
                        // Validate option values
                        option.optionValues.forEach((ov, ovIndex) => {
                            const hasOvName = Object.values(ov.translations).some(t => t.name && t.name.trim());
                            if (!hasOvName) {
                                errors.push(`{{ __("daylight::store.option_value_name_required") }} #${ovIndex + 1} {{ __("daylight::general.in") }} "${option.translations[this.currentLocale]?.name || index + 1}"`);
                            }
                        });
                    }
                });

                return errors;
            },

            validateVariants() {
                const errors = [];

                // Check if variants exist
                if (!this.variants || this.variants.length === 0) {
                    errors.push('{{ __("daylight::store.no_variants_generated") }}');
                    return errors;
                }

                // Collect SKUs to check for duplicates
                const skus = [];

                // Validate each variant
                this.variants.forEach((variant, index) => {
                    const label = this.getVariantLabel(variant);
                    
                    // Check if SKU is provided
                    if (!variant.sku || !variant.sku.trim()) {
                        errors.push(`{{ __("daylight::store.sku_required_for_variant") }}: ${label}`);
                    } else {
                        // Check for duplicate SKUs
                        if (skus.includes(variant.sku)) {
                            errors.push(`{{ __("daylight::store.duplicate_sku") }}: ${variant.sku} (${label})`);
                        }
                        skus.push(variant.sku);
                    }
                });

                return errors;
            },

            validate() {
                const optionErrors = this.validateOptions();
                const variantErrors = this.validateVariants();
                
                return [...optionErrors, ...variantErrors];
            }
        }))

        Alpine.data('optionValueBuilder', (currentOption) => ({
            showOptionValueSlideOver: false,
            currentOption,
            sortableInstance: null,
            isCreatingNew: false,

            currentOptionValue: {
                id: null,
                color: null,
                order: null,
                translations: @json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales()->mapWithKeys(function($locale) { return [$locale => ['name' => '']]; })),
            },

            init() {
                // Sort the array once on initial load based on order field
                this.option.optionValues.sort((a, b) => {
                    const orderA = a.order !== null && a.order !== undefined ? a.order : 0;
                    const orderB = b.order !== null && b.order !== undefined ? b.order : 0;
                    return orderA - orderB;
                });

                this.$watch('option.optionValues', (newValue) => {
                    this.$dispatch('optionValues:sorted', newValue);
                });

                this.$nextTick(() => {
                    if (this.$refs.sortableContainer) {
                        this.sortableInstance = new Sortable(this.$refs.sortableContainer, {
                            animation: 150,
                            handle: '.sortable-handle',
                            dataIdAttr: 'data-option-value-id',
                            // Don't update array during drag - just let Sortable handle the DOM
                        });
                    }
                });
            },

            syncArrayWithDOM() {
                // Sync the array order with current DOM order (called before save)
                if (this.sortableInstance) {
                    const newOrder = this.sortableInstance.toArray();
                    
                    const reordered = newOrder.map((id, index) => {
                        const ov = this.option.optionValues.find(v => v.id == id);
                        if (ov) {
                            ov.order = index;
                        }
                        return ov;
                    }).filter(Boolean);
                    
                    // Clear and repopulate to maintain array reference
                    this.option.optionValues.length = 0;
                    this.option.optionValues.push(...reordered);
                }
            },

            updateOrder() {
                // This method is no longer needed
            },

            deleteOptionValue(id) {
                const index = this.option.optionValues.findIndex(ov => ov.id == id);
                
                if (index !== -1) {
                    this.option.optionValues.splice(index, 1);
                    
                    // Update order for remaining items
                    this.option.optionValues.forEach((ov, idx) => {
                        ov.order = idx;
                    });
                }
            },

            createOptionValue() {
                // Find the highest order value and add 1
                const maxOrder = this.option.optionValues.reduce((max, ov) => {
                    return Math.max(max, ov.order || 0);
                }, -1);

                this.currentOptionValue = {
                    id: 'option_value_' + Date.now(),
                    color: null,
                    order: maxOrder + 1,
                    translations: @json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales()->mapWithKeys(function($locale) { return [$locale => ['name' => '']]; })),
                };

                this.isCreatingNew = true;
                this.showOptionValueSlideOver = true;
            },

            saveOptionValue() {
                if (this.isCreatingNew) {
                    // Add new option value to array
                    this.option.optionValues.push({...this.currentOptionValue});
                } else {
                    // Update existing option value
                    this.option.optionValues = this.option.optionValues.map(ov => 
                        ov.id === this.currentOptionValue.id ? {...this.currentOptionValue} : ov
                    );
                }
                
                this.closeOpenValueSlideOver();
            },

            closeOpenValueSlideOver() {
                this.showOptionValueSlideOver = false;
                this.isCreatingNew = false;

                setTimeout(() => {
                    this.resetCurrentOptionValue();
                }, 300);
            },

            resetCurrentOptionValue() {
                this.currentOptionValue = {
                    id: null,
                    color: null,
                    order: null,
                    translations: @json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales()->mapWithKeys(function($locale) { return [$locale => ['name' => '']]; })),
                };
            }
        }))

        Alpine.data('skuInput', (variant) => ({
            variant,
            searchQuery: '',
            showAutocomplete: false,
            results: [],
            selectedVariant: null,
            errorMessage: null,
            searchTimer: null,

            init() {
                // Check if variant already has data (after refresh)
                if (this.variant.variantData) {
                    this.selectedVariant = this.variant.variantData;
                }
                
                // Initialize search query from variant.sku if exists
                if (this.variant.sku && !this.selectedVariant) {
                    this.searchQuery = this.variant.sku;
                }
            },

            handleInput() {
                this.errorMessage = null;
                
                const value = this.searchQuery;

                if (!value || value.length <= 2) {
                    this.showAutocomplete = false;
                    this.variant.sku = value;
                    return;
                }

                // Check if value matches an already selected result to prevent re-opening
                if (this.results.some(r => r.sku === value)) {
                    this.showAutocomplete = false;
                    return;
                }

                // Debounce search
                if (this.searchTimer) {
                    clearTimeout(this.searchTimer);
                }

                this.searchTimer = setTimeout(() => {
                    this.search(value);
                }, 300);
            },

            handleFocus() {
                // Re-show autocomplete if we have results and query is long enough
                if (this.results.length > 0 && this.searchQuery.length > 2) {
                    this.showAutocomplete = true;
                }
            },

            async search(sku) {
                try {
                    const response = await fetch(`${window.daylight.apiBase}/variants/search`, {
                        method: 'POST',
                        body: JSON.stringify({
                            searchQuery: sku
                        }),
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        },
                    });

                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }

                    const data = await response.json();

                    // Handle exact match
                    if (data.exactMatch) {
                        this.selectOption(data.exactMatch);
                        return;
                    }

                    // Show results
                    this.results = data.variants || [];

                    if (this.results.length > 0) {
                        this.showAutocomplete = true;
                    } else {
                        this.showAutocomplete = false;
                        // Update variant.sku even if no results
                        this.variant.sku = sku;
                    }
                } catch (error) {
                    console.error('Error searching for variants:', error);
                    this.errorMessage = 'Error searching for variants';
                }
            },

            selectOption(result) {
                this.selectedVariant = result;
                this.variant.sku = result.sku;
                this.variant.variantData = result;
                this.searchQuery = '';
                this.showAutocomplete = false;
                this.results = [];
                
                // Dispatch event for compatibility with existing code
                document.dispatchEvent(new CustomEvent('variant-selected', {
                    detail: [{
                        variant: result
                    }]
                }));
            },

            clearSelection() {
                this.selectedVariant = null;
                this.variant.sku = '';
                this.variant.variantData = null;
                this.searchQuery = '';
                this.$nextTick(() => {
                    this.$refs.input?.focus();
                });
            }
        }))
    })
</script>