{{-- resources/views/admin/brands/index.blade.php - FIXED VERSION WITH PROPER TINYMCE DATA LOADING --}}

@extends('admin.layouts.app')

@section('title', admin_trans('brands'))
@section('page-title', admin_trans('brands'))

@section('content')

    <div class="space-y-6" x-data="brandsPage()">

        <!-- Header Actions -->
        <div class="card">
            <div class="flex items-center gap-3">
                <form method="GET" action="{{ route('admin.brands.index') }}" class="flex-1">
                    <x-search-input name="search" :value="request('search')" :placeholder="admin_trans('search_brands')" class="w-full" />
                </form>

                <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-brand-modal')">
                    {{ admin_trans('add_brand') }}
                </x-button>
            </div>
        </div>

        <!-- Bulk Actions Bar -->
        <div x-show="selectedItems.length > 0" x-cloak class="card bg-blue-50 border-blue-200">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <span class="text-sm font-medium text-blue-800"
                        x-text="`${selectedItems.length} {{ admin_trans('items_selected') }}`"></span>
                    <x-button size="sm" variant="outline" @click="clearSelection()">
                        {{ admin_trans('clear_selection') }}
                    </x-button>
                </div>

                <div class="flex items-center gap-2">
                    <x-button size="sm" variant="outline" @click="performBulkAction('activate')">
                        {{ admin_trans('activate') }}
                    </x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('deactivate')">
                        {{ admin_trans('deactivate') }}
                    </x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('feature')">
                        {{ admin_trans('feature') }}
                    </x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('unfeature')">
                        {{ admin_trans('unfeature') }}
                    </x-button>
                    <x-button size="sm" variant="danger" @click="performBulkAction('delete')">
                        {{ admin_trans('delete') }}
                    </x-button>
                </div>
            </div>
        </div>

        <!-- Brands Table -->
        <div class="card">
            @if ($brands->isEmpty())
                <x-empty-state icon="tag" :title="admin_trans('no_brands_yet')" :description="admin_trans('start_by_adding_first_brand')">
                    <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-brand-modal')">
                        {{ admin_trans('add_brand') }}
                    </x-button>
                </x-empty-state>
            @else
                <!-- Brands Table -->
                <div class="w-full overflow-x-auto">
                    <table class="w-full" style="border-collapse: separate; border-spacing: 0;">
                        <thead>
                            <tr style="background: var(--color-bg-secondary);">
                                <!-- Select All Checkbox -->
                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary first:rounded-tl-xl"
                                    style="width: 50px;">
                                    <input type="checkbox" @change="toggleAll($event)" class="checkbox">
                                </th>

                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary"
                                    style="width: 80px;">
                                    {{ admin_trans('order') }}
                                </th>

                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary"
                                    style="width: 60px;">
                                    {{ admin_trans('logo') }}
                                </th>

                                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-tertiary"
                                    style="width: 250px;">
                                    {{ admin_trans('name') }}
                                </th>

                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary"
                                    style="width: 120px;">
                                    {{ admin_trans('translations') }}
                                </th>

                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary"
                                    style="width: 100px;">
                                    {{ admin_trans('featured') }}
                                </th>

                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary"
                                    style="width: 100px;">
                                    {{ admin_trans('status') }}
                                </th>

                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase tracking-wider text-tertiary last:rounded-tr-xl"
                                    style="width: 140px;">
                                    {{ admin_trans('actions') }}
                                </th>
                            </tr>
                        </thead>

                        <tbody class="divide-y"
                            style="divide-color: var(--color-border-primary); background: var(--color-bg-primary);">
                            @foreach ($brands as $brand)
                                <tr class="brand-row hover:bg-primary-light transition-colors"
                                    data-id="{{ $brand->id }}">

                                    <!-- Select Checkbox -->
                                    <td class="px-4 py-3 text-center">
                                        <input type="checkbox" value="{{ $brand->id }}"
                                            @change="toggleItem({{ $brand->id }})"
                                            :checked="selectedItems.includes({{ $brand->id }})"
                                            class="checkbox brand-checkbox">
                                    </td>

                                    <!-- Order (Drag Handle) -->
                                    <td class="px-4 py-3 text-center">
                                        <div class="flex items-center justify-center gap-2">
                                            <button class="drag-handle cursor-move p-1 rounded hover:bg-primary-light">
                                                <i data-lucide="grip-vertical" class="w-3 h-3 text-tertiary"></i>
                                            </button>
                                            <span class="text-sm font-medium text-tertiary">{{ $brand->order ?? 0 }}</span>
                                        </div>
                                    </td>

                                    <!-- Logo -->
                                    <td class="px-4 py-3 text-center">
                                        @if ($brand->getFirstMediaUrl('logo'))
                                            <img src="{{ $brand->getFirstMediaUrl('logo') }}" alt="Brand Logo"
                                                class="w-8 h-8 object-cover rounded-lg border mx-auto">
                                        @else
                                            <div
                                                class="w-8 h-8 bg-gray-200 rounded-lg border flex items-center justify-center mx-auto">
                                                <i data-lucide="image" class="w-4 h-4 text-gray-400"></i>
                                            </div>
                                        @endif
                                    </td>

                                    <!-- Name & Description -->
                                    <td class="px-4 py-3 text-left">
                                        @php
                                            $defaultLang = $languages->where('is_default', true)->first();
                                            $translation = $brand->translations
                                                ->where('language_id', $defaultLang->id ?? 1)
                                                ->first();
                                        @endphp
                                        <div>
                                            <span class="text-sm font-medium text-primary">
                                                {{ $translation->name ?? 'Brand #' . $brand->id }}
                                            </span>
                                            @if ($translation && $translation->description)
                                                <div class="text-xs text-tertiary mt-1 line-clamp-2">
                                                    {!! strip_tags(Str::limit($translation->description, 60)) !!}
                                                </div>
                                            @endif
                                        </div>
                                    </td>

                                    <!-- Translations Count -->
                                    <td class="px-4 py-3 text-center">
                                        <div class="flex items-center justify-center gap-1">
                                            <x-badge
                                                variant="{{ $brand->translations->count() === $languages->count() ? 'success' : 'warning' }}">
                                                {{ $brand->translations->count() }}/{{ $languages->count() }}
                                            </x-badge>
                                        </div>
                                    </td>

                                    <!-- Featured Toggle -->
                                    <td class="px-4 py-3 text-center">
                                        <form method="POST"
                                            action="{{ route('admin.brands.toggle-featured', $brand) }}">
                                            @csrf
                                            @method('PATCH')
                                            <button type="submit"
                                                class="p-1 rounded-lg transition-colors {{ $brand->is_featured ? 'text-yellow-500 hover:bg-yellow-50' : 'text-gray-400 hover:bg-gray-50' }}"
                                                title="{{ $brand->is_featured ? admin_trans('unfeature') : admin_trans('feature') }}">
                                                <i data-lucide="star"
                                                    class="w-5 h-5 {{ $brand->is_featured ? 'fill-current' : '' }}"></i>
                                            </button>
                                        </form>
                                    </td>

                                    <!-- Status Toggle -->
                                    <td class="px-4 py-3 text-center">
                                        <form method="POST" action="{{ route('admin.brands.toggle-status', $brand) }}">
                                            @csrf
                                            @method('PATCH')
                                            <x-toggle name="status_toggle_{{ $brand->id }}" :checked="$brand->status === 'active'"
                                                size="sm" variant="success" onchange="this.form.submit()" />
                                        </form>
                                    </td>

                                    <!-- Actions -->
                                    <td class="px-4 py-3 text-center">
                                        <div class="flex items-center justify-center gap-2">
                                            <!-- Edit Button -->
                                            <button class="p-2 rounded-lg hover:bg-blue-50 text-blue-600 transition-colors"
                                                onclick="editBrand({{ $brand->id }})"
                                                title="{{ admin_trans('edit') }}">
                                                <i data-lucide="edit-3" class="w-4 h-4"></i>
                                            </button>

                                            <!-- Delete Button -->
                                            <button class="p-2 rounded-lg hover:bg-red-50 text-red-600 transition-colors"
                                                onclick="confirmDelete({{ $brand->id }}, '{{ addslashes($translation->name ?? 'Brand #' . $brand->id) }}')"
                                                title="{{ admin_trans('delete') }}">
                                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                @if ($brands->hasPages())
                    <div class="mt-6">
                        <x-pagination :paginator="$brands" />
                    </div>
                @endif
            @endif
        </div>
    </div>

    <!-- Create Brand Modal -->
    <x-modal name="create-brand-modal" maxWidth="2xl">
        <div class="p-6">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-bold text-primary">{{ admin_trans('add_brand') }}</h3>
                <button @click="$dispatch('close-modal', 'create-brand-modal')"
                    class="p-2 rounded-lg hover:bg-primary-light transition-colors">
                    <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
                </button>
            </div>

            <form method="POST" action="{{ route('admin.brands.store') }}" enctype="multipart/form-data"
                class="space-y-6">
                @csrf

                <!-- Multi-language Tabs -->
                <x-tabs defaultTab="{{ $languages->first()->code ?? 'default' }}">
                    <!-- Tab Buttons -->
                    <div class="flex flex-wrap gap-2 border-b" style="border-color: var(--color-border);">
                        @foreach ($languages as $language)
                            <button type="button"
                                @click="activeTab = '{{ $language->code }}'; $event.preventDefault();"
                                :class="activeTab === '{{ $language->code }}' ? 'text-primary bg-primary-light' : 'text-tertiary hover:text-primary'"
                                class="flex items-center gap-2 px-4 py-2 border-b transition-colors font-medium">
                                <i data-lucide="globe" class="w-4 h-4"></i>
                                {{ $language->name }}
                                <span class="text-xs opacity-75">({{ $language->native_name }})</span>
                            </button>
                        @endforeach
                    </div>

                    <!-- Tab Contents -->
                    @foreach ($languages as $language)
                        <x-tab-content :tab="$language->code" class="space-y-4">
                            <div class="p-4 rounded-lg" style="background: var(--color-bg-secondary);">
                                <h4 class="font-semibold text-primary mb-4 flex items-center gap-2">
                                    <i data-lucide="globe" class="w-4 h-4"></i>
                                    {{ admin_trans('content_in') }} {{ $language->native_name }}
                                </h4>
                                <div class="space-y-4">
                                    <x-input 
                                        :label="admin_trans('brand_name')" 
                                        name="translations[{{ $language->id }}][name]"
                                        placeholder="{{ admin_trans('enter_brand_name') }}" 
                                        :required="$language->is_default" 
                                    />

                                    <x-tinymce
                                        name="translations[{{ $language->id }}][description]"
                                        :height="200"
                                        placeholder="{{ admin_trans('enter_description') }}"
                                        :value="old('translations.' . $language->id . '.description')"
                                        :required="false"
                                        :locale="$language->code"
                                        :direction="$language->direction"
                                        :language="$language->direction === 'rtl' ? 'ar' : 'en'"
                                    >
                                        {{ admin_trans('description') }}
                                    </x-tinymce>
                                </div>
                            </div>
                        </x-tab-content>
                    @endforeach
                </x-tabs>

                <!-- Logo Upload -->
                <div x-data="filePreview()">
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('brand_logo') }}</label>
                    <div class="border-2 border-dashed rounded-xl p-4 text-center"
                        style="border-color: var(--color-border);" @dragover.prevent
                        @drop.prevent="handleDrop($event, 'logo')">
                        <!-- Upload Area -->
                        <div x-show="!logoPreview" class="cursor-pointer" @click="$refs.logoInput.click()">
                            <i data-lucide="image" class="w-8 h-8 mx-auto mb-2 text-tertiary"></i>
                            <p class="text-sm text-tertiary">{{ admin_trans('click_to_upload_logo') }}</p>
                            <p class="text-xs text-tertiary mt-1">SVG, PNG, JPG (max 2MB)</p>
                        </div>
                        <!-- Preview -->
                        <div x-show="logoPreview" x-cloak class="relative">
                            <img :src="logoPreview" class="w-16 h-16 object-cover rounded-lg mx-auto border">
                            <button type="button" @click="clearPreview('logo')"
                                class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600">
                                ×
                            </button>
                        </div>
                        <input type="file" x-ref="logoInput" name="logo" accept="image/*" class="hidden"
                            @change="previewFile($event, 'logo')">
                    </div>
                </div>

                <!-- Settings -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <x-input :label="admin_trans('order')" name="order" type="number" value="0" :hint="admin_trans('display_order')" />
                    <x-select :label="admin_trans('status')" name="status" :required="true">
                        <option value="draft">{{ admin_trans('draft') }}</option>
                        <option value="active" selected>{{ admin_trans('active') }}</option>
                    </x-select>
                </div>

                <x-toggle name="is_featured" :label="admin_trans('featured_brand')" value="1" />

                <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                    <x-button variant="outline" type="button"
                        @click="$dispatch('close-modal', 'create-brand-modal')">
                        {{ admin_trans('cancel') }}
                    </x-button>
                    <x-button variant="primary" type="submit" icon="check">
                        {{ admin_trans('create') }}
                    </x-button>
                </div>
            </form>
        </div>
    </x-modal>

    <!-- Edit Brand Modal - FIXED VERSION -->
    <x-modal name="edit-brand-modal" maxWidth="2xl">
        <div class="p-6" x-data="editBrandModal()">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_brand') }}</h3>
                <button @click="$dispatch('close-modal', 'edit-brand-modal')"
                    class="p-2 rounded-lg hover:bg-primary-light transition-colors">
                    <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
                </button>
            </div>

            <div x-show="loading">
                <x-loading text="{{ admin_trans('loading') }}..." />
            </div>

            <div x-show="!loading && brandData" x-cloak>
                <form :action="`/admin/brands/${brandData?.id}`" method="POST" enctype="multipart/form-data" class="space-y-6">
                    @csrf @method('PUT')

                    <!-- Multi-language Tabs -->
                    @if($languages->count() > 0)
                        <x-tabs defaultTab="{{ $languages->first()->code }}">
                            <div class="flex flex-wrap gap-2 border-b mb-4" style="border-color: var(--color-border);">
                                @foreach($languages as $language)
                                    <button type="button" 
                                        @click="activeTab = '{{ $language->code }}'; $event.preventDefault();" 
                                        :class="activeTab === '{{ $language->code }}' ? 'text-primary bg-primary-light' : 'text-tertiary hover:text-primary'" 
                                        class="flex items-center gap-2 px-4 py-2 border-b transition-colors font-medium">
                                        <i data-lucide="globe" class="w-4 h-4"></i>
                                        {{ $language->name }}
                                        <span class="text-xs opacity-75">({{ $language->native_name }})</span>
                                    </button>
                                @endforeach
                            </div>

                            @foreach($languages as $language)
                                @php
                                    $isRTL = $language->direction === 'rtl';
                                @endphp
                                <x-tab-content :tab="$language->code">
                                    <div class="space-y-4" @if($isRTL) dir="rtl" @endif>
                                        <div class="p-4 rounded-lg" style="background: var(--color-bg-secondary);">
                                            <h4 class="font-semibold text-primary mb-4 flex items-center gap-2">
                                                <i data-lucide="globe" class="w-4 h-4"></i>
                                                {{ admin_trans('content_in') }} {{ $language->native_name }}
                                            </h4>

                                            <div class="space-y-4">
                                                <x-input
                                                    :label="admin_trans('brand_name')"
                                                    :name="'translations[' . $language->id . '][name]'"
                                                    placeholder="{{ admin_trans('enter_brand_name') }}"
                                                    :required="$language->is_default"
                                                    x-bind:value="getTranslationValue({{ $language->id }}, 'name')"
                                                    @input="setTranslationValue({{ $language->id }}, 'name', $event.target.value)"
                                                />

                                                {{-- FIXED: TinyMCE with proper data binding --}}
                                                <div class="tinymce-edit-container" data-language-id="{{ $language->id }}">
                                                    <x-tinymce
                                                        name="translations[{{ $language->id }}][description]"
                                                        :height="200"
                                                        placeholder="{{ admin_trans('enter_description') }}"
                                                        :value="''"
                                                        :required="false"
                                                        :locale="$language->code"
                                                        :direction="$language->direction"
                                                        :language="$language->direction === 'rtl' ? 'ar' : 'en'"
                                                    >
                                                        {{ admin_trans('description') }}
                                                    </x-tinymce>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </x-tab-content>
                            @endforeach
                        </x-tabs>
                    @endif

                    <!-- Current Logo Display -->
                    <div>
                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('current_logo') }}</label>
                        <div x-show="brandData?.logo_url" class="mb-3">
                            <div class="relative inline-block">
                                <img :src="brandData?.logo_url" class="w-20 h-20 object-cover rounded-lg border">
                                <button 
                                    type="button" 
                                    @click="removeCurrentLogo()"
                                    class="absolute top-1 right-1 w-6 h-6 rounded-full flex items-center justify-center text-white text-sm hover:bg-red-600" 
                                    style="background-color: var(--color-danger-500);"
                                >
                                    ×
                                </button>
                            </div>
                        </div>
                        <div x-show="!brandData?.logo_url" class="mb-3">
                            <p class="text-sm text-tertiary">{{ admin_trans('no_logo') }}</p>
                        </div>

                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('new_logo') }}</label>
                        <x-file-upload :label="''" name="logo" accept="image/*" maxSize="2MB" />
                    </div>

                    <!-- Settings -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <x-input 
                            :label="admin_trans('order')" 
                            name="order" 
                            type="number" 
                            x-bind:value="brandData?.order || 0"
                            @input="brandData.order = $event.target.value"
                        />

                        <x-select :label="admin_trans('status')" name="status" :required="true">
                            <option value="draft" x-bind:selected="brandData?.status === 'draft'">{{ admin_trans('draft') }}</option>
                            <option value="active" x-bind:selected="brandData?.status === 'active'">{{ admin_trans('active') }}</option>
                        </x-select>
                    </div>

                    <div class="flex items-center gap-3">
                        <input 
                            type="checkbox" 
                            name="is_featured" 
                            value="1"
                            class="checkbox"
                            x-bind:checked="brandData?.is_featured"
                            @change="brandData.is_featured = $event.target.checked"
                        >
                        <label class="text-sm font-medium text-primary">
                            {{ admin_trans('featured_brand') }}
                        </label>
                    </div>

                    <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                        <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'edit-brand-modal')">
                            {{ admin_trans('cancel') }}
                        </x-button>
                        <x-button variant="primary" type="submit" icon="check">
                            {{ admin_trans('update') }}
                        </x-button>
                    </div>
                </form>
            </div>
        </div>
    </x-modal>

    <!-- Delete Confirmation Modal -->
    <x-confirm-modal name="delete-brand-modal" :title="admin_trans('confirm_delete')"
        message="{{ admin_trans('delete_brand_message') }}" :confirmText="admin_trans('yes_delete')" :cancelText="admin_trans('cancel')"
        confirmVariant="danger" icon="trash-2" iconColor="danger" />

@endsection

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    <script>
        // File Preview Component
        function filePreview() {
            return {
                logoPreview: null,

                previewFile(event, type) {
                    const file = event.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            this[type + 'Preview'] = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                },

                clearPreview(type) {
                    this[type + 'Preview'] = null;
                    const input = this.$refs[type + 'Input'];
                    if (input) input.value = '';
                },

                handleDrop(event, type) {
                    const files = event.dataTransfer.files;
                    if (files.length > 0) {
                        const file = files[0];
                        if (file.type.startsWith('image/')) {
                            this.$refs[type + 'Input'].files = files;
                            this.previewFile({
                                target: {
                                    files: [file]
                                }
                            }, type);
                        }
                    }
                }
            }
        }

        // FIXED: Enhanced Edit Brand Modal with proper TinyMCE data loading
        function editBrandModal() {
            return {
                loading: false,
                brandData: null,

                async loadBrand(id) {
                    this.loading = true;
                    try {
                        const response = await fetch(`/admin/brands/${id}/edit`);
                        const result = await response.json();
                        
                        if (result.success) {
                            this.brandData = result.data;
                            
                            console.log('📊 Brand data loaded:', this.brandData);
                            
                            // Wait for modal to be fully rendered
                            await this.$nextTick();
                            
                            // Update the form fields after a short delay
                            setTimeout(() => {
                                this.updateAllFieldsWithData();
                            }, 500);
                        }
                    } catch (error) {
                        console.error('Error loading brand:', error);
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_loading_brand") }}');
                        }
                    } finally {
                        this.loading = false;
                    }
                },

                getTranslationValue(languageId, field) {
                    const translation = this.brandData?.translations?.find(t => t.language_id == languageId);
                    return translation ? translation[field] || '' : '';
                },

                setTranslationValue(languageId, field, value) {
                    if (!this.brandData || !this.brandData.translations) return;
                    let translation = this.brandData.translations.find(t => t.language_id == languageId);
                    if (!translation) {
                        translation = { language_id: languageId };
                        this.brandData.translations.push(translation);
                    }
                    translation[field] = value;
                },

                // FIXED: Enhanced data update method
                updateAllFieldsWithData() {
                    if (!this.brandData || !this.brandData.translations) {
                        console.warn('⚠️ No brand data or translations available');
                        return;
                    }
                    
                    console.log('🔄 Updating all fields with brand data');
                    
                    // Update TinyMCE editors for each language
                    this.brandData.translations.forEach((translation) => {
                        const languageId = translation.language_id;
                        const editorName = `translations[${languageId}][description]`;
                        
                        console.log(`📝 Updating editor for language ${languageId}:`, translation.description);
                        
                        // Find all textareas with this name
                        setTimeout(() => {
                            const textareas = document.querySelectorAll(`textarea[name="${editorName}"]`);
                            
                            textareas.forEach(textarea => {
                                if (translation.description) {
                                    // Set the textarea value directly
                                    textarea.value = translation.description;
                                    textarea.dataset.originalContent = translation.description;
                                    
                                    console.log(`✅ Set content for ${textarea.id}:`, translation.description.substring(0, 50) + '...');
                                    
                                    // Update TinyMCE if available
                                    if (window.SecureTinyMCE) {
                                        try {
                                            const editorInstance = window.SecureTinyMCE.getInstance(textarea.id);
                                            if (editorInstance && !editorInstance.destroyed) {
                                                editorInstance.setContent(translation.description, {format: 'raw'});
                                                console.log(`🎯 TinyMCE updated for ${textarea.id}`);
                                            } else {
                                                // Editor not ready yet, try alternative method
                                                setTimeout(() => {
                                                    const retryEditor = window.SecureTinyMCE.getInstance(textarea.id);
                                                    if (retryEditor && !retryEditor.destroyed) {
                                                        retryEditor.setContent(translation.description, {format: 'raw'});
                                                        console.log(`🔄 TinyMCE updated on retry for ${textarea.id}`);
                                                    }
                                                }, 500);
                                            }
                                        } catch (error) {
                                            console.warn(`⚠️ Error updating TinyMCE for ${textarea.id}:`, error);
                                        }
                                    }
                                    
                                    // Alternative: Direct TinyMCE access
                                    if (typeof tinymce !== 'undefined') {
                                        try {
                                            const editor = tinymce.get(textarea.id);
                                            if (editor) {
                                                editor.setContent(translation.description, {format: 'raw'});
                                                console.log(`🎯 Direct TinyMCE update for ${textarea.id}`);
                                            }
                                        } catch (error) {
                                            console.warn(`⚠️ Direct TinyMCE error for ${textarea.id}:`, error);
                                        }
                                    }
                                }
                            });
                        }, 300);
                        
                        // Also try with a longer delay for stubborn editors
                        setTimeout(() => {
                            const textareas = document.querySelectorAll(`textarea[name="${editorName}"]`);
                            textareas.forEach(textarea => {
                                if (translation.description && textarea.value !== translation.description) {
                                    textarea.value = translation.description;
                                    
                                    // Force TinyMCE update
                                    if (typeof tinymce !== 'undefined') {
                                        const editor = tinymce.get(textarea.id);
                                        if (editor && editor.getContent() !== translation.description) {
                                            editor.setContent(translation.description, {format: 'raw'});
                                            console.log(`🔄 Force updated TinyMCE for ${textarea.id}`);
                                        }
                                    }
                                }
                            });
                        }, 1000);
                    });
                },

                async removeCurrentLogo() {
                    if (!this.brandData || !this.brandData.id) return;
                    
                    try {
                        const response = await fetch(`/admin/brands/${this.brandData.id}/media/logo`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                            }
                        });

                        if (response.ok) {
                            this.brandData.logo_url = null;
                            if (window.toast) {
                                toast.success('{{ admin_trans("media_removed_successfully") }}');
                            }
                        } else {
                            if (window.toast) {
                                toast.error('{{ admin_trans("error_removing_media") }}');
                            }
                        }
                    } catch (error) {
                        console.error('Error removing media:', error);
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_removing_media") }}');
                        }
                    }
                }
            }
        }

        // Alpine.js Brands Page Component
        function brandsPage() {
            return {
                selectedItems: [],

                toggleItem(id) {
                    const index = this.selectedItems.indexOf(id);
                    if (index > -1) {
                        this.selectedItems.splice(index, 1);
                    } else {
                        this.selectedItems.push(id);
                    }
                },

                toggleAll(event) {
                    if (event.target.checked) {
                        this.selectedItems = Array.from(document.querySelectorAll('.brand-row')).map(row => parseInt(row
                            .dataset.id));
                        document.querySelectorAll('.brand-checkbox').forEach(cb => cb.checked = true);
                    } else {
                        this.selectedItems = [];
                        document.querySelectorAll('.brand-checkbox').forEach(cb => cb.checked = false);
                    }
                },

                clearSelection() {
                    this.selectedItems = [];
                    document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
                },

                async performBulkAction(action) {
                    if (this.selectedItems.length === 0) {
                        if (window.toast) {
                            toast.warning('{{ admin_trans("please_select_items") }}');
                        }
                        return;
                    }

                    if (action === 'delete') {
                        if (!confirm('{{ admin_trans("confirm_bulk_delete") }}')) {
                            return;
                        }
                    }

                    try {
                        const formData = new FormData();
                        formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);
                        formData.append('action', action);

                        this.selectedItems.forEach(id => {
                            formData.append('selected[]', id);
                        });

                        const response = await fetch('/admin/brands/bulk-action', {
                            method: 'POST',
                            body: formData
                        });

                        const result = await response.json();

                        if (result.success) {
                            if (window.toast) {
                                toast.success(result.message);
                            }
                            setTimeout(() => window.location.reload(), 1000);
                        } else {
                            if (window.toast) {
                                toast.error(result.message);
                            }
                        }
                    } catch (error) {
                        console.error('Bulk action error:', error);
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_bulk_action") }}');
                        }
                    }
                }
            }
        }

        // FIXED: Enhanced edit brand function
        function editBrand(id) {
            console.log('🔧 Opening edit modal for brand:', id);
            
            // Open the modal
            window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-brand-modal' }));
            
            // Load brand data with proper timing
            setTimeout(() => {
                const modal = document.querySelector('[x-data*="editBrandModal"]');
                if (modal && modal._x_dataStack && modal._x_dataStack[0]) {
                    console.log('📂 Loading brand data...');
                    modal._x_dataStack[0].loadBrand(id);
                } else {
                    console.warn('⚠️ Modal component not found, retrying...');
                    // Retry after a longer delay
                    setTimeout(() => {
                        const retryModal = document.querySelector('[x-data*="editBrandModal"]');
                        if (retryModal && retryModal._x_dataStack && retryModal._x_dataStack[0]) {
                            retryModal._x_dataStack[0].loadBrand(id);
                        }
                    }, 500);
                }
            }, 100);
        }

        // Confirm Delete Function
        function confirmDelete(id, name) {
            window.addEventListener('confirm-action', function handler(e) {
                if (e.detail === 'delete-brand-modal') {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = `/admin/brands/${id}`;
                    form.innerHTML = `
                        @csrf
                        @method('DELETE')
                    `;
                    document.body.appendChild(form);
                    form.submit();
                    window.removeEventListener('confirm-action', handler);
                }
            });

            window.dispatchEvent(new CustomEvent('open-modal', {
                detail: 'delete-brand-modal'
            }));
        }

        // Sortable.js for Drag & Drop
        document.addEventListener('DOMContentLoaded', function() {
            const tbody = document.querySelector('.brand-row')?.parentElement;

            if (tbody) {
                new Sortable(tbody, {
                    handle: '.drag-handle',
                    animation: 150,
                    ghostClass: 'opacity-50',
                    onEnd: updateOrder
                });
            }

            // Initialize Lucide icons
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        });

        // Update Order via AJAX
        function updateOrder() {
            const rows = document.querySelectorAll('.brand-row');
            const orders = Array.from(rows).map(row => row.dataset.id);

            fetch('/admin/brands/update-order', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({
                        orders
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (window.toast) {
                            toast.success('{{ admin_trans("order_updated_successfully") }}');
                        }
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_updating_order") }}');
                        }
                    }
                })
                .catch(() => {
                    if (window.toast) {
                        toast.error('{{ admin_trans("error_updating_order") }}');
                    }
                });
        }
    </script>
@endpush