@extends('admin.layouts.app')

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

@section('content')

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

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

                <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-category-modal')">
                    {{ admin_trans('add_category') }}
                </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>

        <!-- Categories Table -->
        <div class="card">
            @if ($categories->isEmpty())
                <x-empty-state icon="layout-grid" :title="admin_trans('no_categories_yet')" :description="admin_trans('start_by_adding_first_category')">
                    <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-category-modal')">
                        {{ admin_trans('add_category') }}
                    </x-button>
                </x-empty-state>
            @else
                <!-- Categories 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('icon') }}
                                </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 ($categories as $category)
                                <tr class="category-row hover:bg-primary-light transition-colors"
                                    data-id="{{ $category->id }}">

                                    <!-- Select Checkbox -->
                                    <td class="px-4 py-3 text-center">
                                        <input type="checkbox" value="{{ $category->id }}"
                                            @change="toggleItem({{ $category->id }})"
                                            :checked="selectedItems.includes({{ $category->id }})"
                                            class="checkbox category-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">{{ $category->order ?? 0 }}</span>
                                        </div>
                                    </td>

                                    <!-- Icon -->
                                    <td class="px-4 py-3 text-center">
                                        @if ($category->getFirstMediaUrl('icon'))
                                            <img src="{{ $category->getFirstMediaUrl('icon') }}" alt="Category Icon"
                                                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 = $category->translations
                                                ->where('language_id', $defaultLang->id ?? 1)
                                                ->first();
                                        @endphp
                                        <div>
                                            <span class="text-sm font-medium text-primary">
                                                {{ $translation->name ?? 'Category #' . $category->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="{{ $category->translations->count() === $languages->count() ? 'success' : 'warning' }}">
                                                {{ $category->translations->count() }}/{{ $languages->count() }}
                                            </x-badge>
                                        </div>
                                    </td>

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

                                    <!-- Status Toggle -->
                                    <td class="px-4 py-3 text-center">
                                        <form method="POST"
                                            action="{{ route('admin.categories.toggle-status', $category) }}">
                                            @csrf
                                            @method('PATCH')
                                            <x-toggle name="status_toggle_{{ $category->id }}" :checked="$category->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="editCategory({{ $category->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({{ $category->id }}, '{{ addslashes($translation->name ?? 'Category #' . $category->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 ($categories->hasPages())
                    <div class="mt-6">
                        <x-pagination :paginator="$categories" />
                    </div>
                @endif
            @endif
        </div>
    </div>

    <!-- Create Category Modal -->
    <x-modal name="create-category-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_category') }}</h3>
                <button @click="$dispatch('close-modal', 'create-category-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.categories.store') }}" enctype="multipart/form-data"
                class="space-y-6" onsubmit="saveAllEditors(); return true;">
                @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(); saveAllEditors(); setTimeout(() => { window.SecureTinyMCE.init(); }, 300);"
                                :class="activeTab === '{{ $language->code }}' ? 'text-primary bg-primary-light border-primary' : 'border-transparent text-tertiary hover:text-primary'"
                                class="flex items-center gap-2 px-4 py-2 border-b-2 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('category_name')" name="translations[{{ $language->id }}][name]"
                                        placeholder="{{ admin_trans('enter_category_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>

                <!-- Media Uploads مع Preview -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6" x-data="filePreview()">
                    <!-- Icon Upload -->
                    <div>
                        <label
                            class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('category_icon') }}</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, 'icon')">

                            <!-- Upload Area -->
                            <div x-show="!iconPreview" class="cursor-pointer" @click="$refs.iconInput.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_icon') }}</p>
                                <p class="text-xs text-tertiary mt-1">SVG, PNG, JPG (max 2MB)</p>
                            </div>

                            <!-- Preview -->
                            <div x-show="iconPreview" x-cloak class="relative">
                                <img :src="iconPreview" class="w-16 h-16 object-cover rounded-lg mx-auto border">
                                <button type="button" @click="clearPreview('icon')"
                                    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="iconInput" name="icon" accept="image/*" class="hidden"
                                @change="previewFile($event, 'icon')">
                        </div>
                    </div>

                    <!-- Cover Upload -->
                    <div>
                        <label
                            class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('cover_image') }}</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, 'cover')">

                            <!-- Upload Area -->
                            <div x-show="!coverPreview" class="cursor-pointer" @click="$refs.coverInput.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_cover') }}</p>
                                <p class="text-xs text-tertiary mt-1">PNG, JPG, WebP (max 5MB)</p>
                            </div>

                            <!-- Preview -->
                            <div x-show="coverPreview" x-cloak class="relative">
                                <img :src="coverPreview" class="w-24 h-16 object-cover rounded-lg mx-auto border">
                                <button type="button" @click="clearPreview('cover')"
                                    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="coverInput" name="cover" accept="image/*" class="hidden"
                                @change="previewFile($event, 'cover')">
                        </div>
                    </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_category')" 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-category-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 Category Modal - FIXED VERSION -->
    <x-modal name="edit-category-modal" maxWidth="2xl">
        <div class="p-6" x-data="editCategoryModal()">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_category') }}</h3>
                <button @click="$dispatch('close-modal', 'edit-category-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 && categoryData" x-cloak>
                <form :action="`/admin/categories/${categoryData?.id}`" method="POST" enctype="multipart/form-data" class="space-y-6" onsubmit="saveAllEditors(); return true;">
                    @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(); saveAllEditors(); setTimeout(() => { updateTinyMCEContent(); }, 300);" 
                                        :class="activeTab === '{{ $language->code }}' ? 'text-primary bg-primary-light border-primary' : 'border-transparent text-tertiary hover:text-primary'" 
                                        class="flex items-center gap-2 px-4 py-2 border-b-2 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('category_name')"
                                                    :name="'translations[' . $language->id . '][name]'"
                                                    placeholder="{{ admin_trans('enter_category_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 Media Display -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Icon -->
                        <div>
                            <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('current_icon') }}</label>
                            <div x-show="categoryData?.icon_url" class="mb-3">
                                <div class="relative inline-block">
                                    <img :src="categoryData?.icon_url" class="w-20 h-20 object-cover rounded-lg border">
                                    <button 
                                        type="button" 
                                        @click="removeCurrentMedia('icon')"
                                        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="!categoryData?.icon_url" class="mb-3">
                                <p class="text-sm text-tertiary">{{ admin_trans('no_icon') }}</p>
                            </div>

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

                        <!-- Cover -->
                        <div>
                            <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('current_cover') }}</label>
                            <div x-show="categoryData?.cover_url" class="mb-3">
                                <div class="relative inline-block">
                                    <img :src="categoryData?.cover_url" class="w-28 h-20 object-cover rounded-lg border">
                                    <button 
                                        type="button" 
                                        @click="removeCurrentMedia('cover')"
                                        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="!categoryData?.cover_url" class="mb-3">
                                <p class="text-sm text-tertiary">{{ admin_trans('no_cover') }}</p>
                            </div>

                            <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('new_cover') }}</label>
                            <x-file-upload :label="''" name="cover" accept="image/*" maxSize="5MB" />
                        </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" 
                            x-bind:value="categoryData?.order || 0"
                            @input="categoryData.order = $event.target.value"
                        />

                        <x-select :label="admin_trans('status')" name="status" :required="true">
                            <option value="draft" x-bind:selected="categoryData?.status === 'draft'">{{ admin_trans('draft') }}</option>
                            <option value="active" x-bind:selected="categoryData?.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="categoryData?.is_featured"
                            @change="categoryData.is_featured = $event.target.checked"
                        >
                        <label class="text-sm font-medium text-primary">
                            {{ admin_trans('featured_category') }}
                        </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-category-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-category-modal" :title="admin_trans('confirm_delete')"
        message="{{ admin_trans('delete_category_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 {
                iconPreview: null,
                coverPreview: 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 Category Modal with proper TinyMCE data loading
        function editCategoryModal() {
            return {
                loading: false,
                categoryData: null,

                async loadCategory(id) {
                    this.loading = true;
                    try {
                        const response = await fetch(`/admin/categories/${id}/edit`);
                        const result = await response.json();
                        
                        if (result.success) {
                            this.categoryData = result.data;
                            
                            console.log('📊 Category data loaded:', this.categoryData);
                            
                            // 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 category:', error);
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_loading_category") }}');
                        }
                    } finally {
                        this.loading = false;
                    }
                },

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

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

                // FIXED: Enhanced data update method for categories
                updateAllFieldsWithData() {
                    if (!this.categoryData || !this.categoryData.translations) {
                        console.warn('⚠️ No category data or translations available');
                        return;
                    }
                    
                    console.log('🔄 Updating all fields with category data');
                    
                    // Update TinyMCE editors for each language
                    this.categoryData.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);
                    });
                },

                // Method to update TinyMCE content when switching tabs
                updateTinyMCEContent() {
                    setTimeout(() => {
                        if (window.SecureTinyMCE) {
                            window.SecureTinyMCE.init();
                        }
                        this.updateAllFieldsWithData();
                    }, 200);
                },

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

                        if (response.ok) {
                            if (collection === 'icon') {
                                this.categoryData.icon_url = null;
                            } else if (collection === 'cover') {
                                this.categoryData.cover_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 Categories Page Component - FIXED
        function categoriesPage() {
            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('.category-row')).map(row => parseInt(row
                            .dataset.id));
                        document.querySelectorAll('.category-checkbox').forEach(cb => cb.checked = true);
                    } else {
                        this.selectedItems = [];
                        document.querySelectorAll('.category-checkbox').forEach(cb => cb.checked = false);
                    }
                },

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

                // FIXED: إصلاح الـ Bulk Actions - استخدام Toast بدلاً alert
                async performBulkAction(action) {
                    if (this.selectedItems.length === 0) {
                        // استخدام Toast بدلاً alert ✅
                        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/categories/bulk-action', {
                            method: 'POST',
                            body: formData
                        });

                        const result = await response.json();

                        if (result.success) {
                            // استخدام Toast بدلاً alert ✅
                            if (window.toast) {
                                toast.success(result.message);
                            }
                            setTimeout(() => window.location.reload(), 1000);
                        } else {
                            // استخدام Toast بدلاً alert ✅
                            if (window.toast) {
                                toast.error(result.message);
                            }
                        }
                    } catch (error) {
                        console.error('Bulk action error:', error);
                        // استخدام Toast بدلاً alert ✅
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_bulk_action") }}');
                        }
                    }
                }
            }
        }

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

        // Confirm Delete Function
        function confirmDelete(id, name) {
            window.addEventListener('confirm-action', function handler(e) {
                if (e.detail === 'delete-category-modal') {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = `/admin/categories/${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-category-modal'
            }));
        }

        // Sortable.js for Drag & Drop
        document.addEventListener('DOMContentLoaded', function() {
            const tbody = document.querySelector('.category-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 - إصلاح Toast
        function updateOrder() {
            const rows = document.querySelectorAll('.category-row');
            const orders = Array.from(rows).map(row => row.dataset.id);

            fetch('/admin/categories/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) {
                        // استخدام Toast بدلاً alert ✅
                        if (window.toast) {
                            toast.success('{{ admin_trans("order_updated_successfully") }}');
                        }
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        // استخدام Toast بدلاً alert ✅
                        if (window.toast) {
                            toast.error('{{ admin_trans("error_updating_order") }}');
                        }
                    }
                })
                .catch(() => {
                    // استخدام Toast بدلاً alert ✅
                    if (window.toast) {
                        toast.error('{{ admin_trans("error_updating_order") }}');
                    }
                });
        }

        // FIXED: Global function to save all TinyMCE editors before form submission
        function saveAllEditors() {
            if (window.SecureTinyMCE && typeof window.SecureTinyMCE.save === 'function') {
                window.SecureTinyMCE.save();
            }
            
            // Alternative method using global tinymce if available
            if (typeof tinymce !== 'undefined') {
                tinymce.triggerSave();
            }
        }

        // FIXED: Enhanced form submission handling
        document.addEventListener('DOMContentLoaded', function() {
            // Handle all forms with TinyMCE editors
            document.addEventListener('submit', function(e) {
                // Save all editors before any form submission
                saveAllEditors();
            });
            
            // Prevent form submission when switching tabs
            document.addEventListener('click', function(e) {
                const tabButton = e.target.closest('button[type="button"]');
                
                if (tabButton && (
                    tabButton.textContent.includes('العربية') || 
                    tabButton.textContent.includes('English') || 
                    tabButton.hasAttribute('@click') || 
                    tabButton.hasAttribute('x-on:click')
                )) {
                    // This is a tab button, prevent any potential form submission
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Save editors before tab change
                    saveAllEditors();
                }
            });
        });
    </script>
@endpush