@extends('admin.layouts.app')

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

@section('content')

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

    <!-- Header: Search & Add Button -->
    <div class="card">
        <div class="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
            
            <!-- Search -->
            <div class="flex-1 w-full max-w-lg">
                <form method="GET" action="{{ route('admin.pages.index') }}">
                    @if(request('locale_id'))<input type="hidden" name="locale_id" value="{{ request('locale_id') }}">@endif
                    @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                    
                    <x-search-input 
                        name="search" 
                        :value="request('search')" 
                        :placeholder="admin_trans('search_pages')" 
                        class="w-full"
                    />
                </form>
            </div>

            <!-- Filters Row -->
            <div class="flex flex-wrap items-center gap-4">
                
                <!-- Language Filter -->
                @if($currentCountry && $availableLocales->count() > 1)
                    <form method="GET" action="{{ route('admin.pages.index') }}" class="flex items-center gap-2">
                        @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                        @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                        
                        <label class="text-sm font-medium text-tertiary">{{ admin_trans('language') }}:</label>
                        <select name="locale_id" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                            <option value="">{{ admin_trans('all_languages') }}</option>
                            @foreach($availableLocales as $locale)
                                <option value="{{ $locale->id }}" {{ request('locale_id') == $locale->id ? 'selected' : '' }}>
                                    {{ $locale->language->name ?? $locale->name }}
                                </option>
                            @endforeach
                        </select>
                    </form>
                @endif

                <!-- Status Filter -->
                <form method="GET" action="{{ route('admin.pages.index') }}" class="flex items-center gap-2">
                    @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                    @if(request('locale_id'))<input type="hidden" name="locale_id" value="{{ request('locale_id') }}">@endif
                    
                    <label class="text-sm font-medium text-tertiary">{{ admin_trans('status') }}:</label>
                    <select name="status" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                        <option value="">{{ admin_trans('all_statuses') }}</option>
                        <option value="published" {{ request('status') === 'published' ? 'selected' : '' }}>{{ admin_trans('published') }}</option>
                        <option value="draft" {{ request('status') === 'draft' ? 'selected' : '' }}>{{ admin_trans('draft') }}</option>
                    </select>
                </form>

                <!-- Clear Filters -->
                @if(request()->hasAny(['search', 'locale_id', 'status']))
                    <x-button variant="outline" size="sm" icon="x-circle" href="{{ route('admin.pages.index') }}">
                        {{ admin_trans('clear_filters') }}
                    </x-button>
                @endif
            </div>

            <!-- Add Button -->
            <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-page-modal')">
                {{ admin_trans('add_page') }}
            </x-button>
        </div>
    </div>

    <!-- Bulk Actions -->
    <div x-show="selectedItems.length > 0" x-cloak>
        <x-alert variant="info">
            <div class="flex items-center justify-between w-full">
                <span x-text="`${selectedItems.length} {{ admin_trans('items_selected') }}`"></span>
                <div class="flex gap-2">
                    <x-button size="sm" variant="outline" @click="performBulkAction('publish')">{{ admin_trans('publish') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('draft')">{{ admin_trans('draft') }}</x-button>
                    <x-button size="sm" variant="danger" @click="performBulkAction('delete')">{{ admin_trans('delete') }}</x-button>
                    <x-button size="sm" variant="outline" @click="clearSelection()">{{ admin_trans('clear') }}</x-button>
                </div>
            </div>
        </x-alert>
    </div>

    <!-- Pages Table -->
    <x-card>
        @if ($pages->isEmpty())
            @if($currentCountry)
                <x-empty-state icon="file-text" :title="admin_trans('no_pages_yet')" :description="admin_trans('start_by_adding_first_page')">
                    <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-page-modal')">
                        {{ admin_trans('add_page') }}
                    </x-button>
                </x-empty-state>
            @else
                <x-empty-state icon="globe" :title="admin_trans('select_country_first')" :description="admin_trans('select_country_to_manage_pages')">
                    <p class="text-sm text-tertiary mt-2">{{ admin_trans('use_country_filter_navbar') }}</p>
                </x-empty-state>
            @endif
        @else
            <x-enhanced-table 
                :headers="[
                    'select' => ['text' => '', 'align' => 'center', 'width' => '50px'],
                    'title' => ['text' => admin_trans('title'), 'align' => 'left', 'width' => '300px'],
                    'languages' => ['text' => admin_trans('languages'), 'align' => 'center', 'width' => '120px'],
                    'status' => ['text' => admin_trans('status'), 'align' => 'center', 'width' => '100px'],
                    'created' => ['text' => admin_trans('created_at'), 'align' => 'center', 'width' => '150px'],
                    'actions' => ['text' => admin_trans('actions'), 'align' => 'center', 'width' => '100px']
                ]"
                :responsive="true"
                :striped="true"
            >
                @foreach ($pages as $page)
                    <tr class="page-row hover:bg-primary-light transition-colors">

                        <!-- Select -->
                        <x-table-cell type="actions">
                            <input type="checkbox" value="{{ $page->id }}" 
                                @change="toggleItem({{ $page->id }})" 
                                :checked="selectedItems.includes({{ $page->id }})" 
                                class="checkbox">
                        </x-table-cell>

                        <!-- Title -->
                        <x-table-cell type="text">
                            @php
                                $translation = $page->translations->first();
                            @endphp
                            <div>
                                <span class="text-sm font-medium text-primary">
                                    {{ $translation->title ?? 'Page #' . $page->id }}
                                </span>
                                @if ($translation && $translation->description)
                                    <div class="text-xs text-tertiary mt-1">
                                        {!! Str::limit(strip_tags($translation->description), 80) !!}
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Languages -->
                        <x-table-cell type="badge">
                            <div class="flex items-center justify-center gap-1 flex-wrap">
                                @foreach($page->translations->take(3) as $trans)
                                    <x-badge variant="info" class="text-xs">
                                        {{ $trans->locale->code ?? 'N/A' }}
                                    </x-badge>
                                @endforeach
                                @if($page->translations->count() > 3)
                                    <x-badge variant="secondary" class="text-xs">
                                        +{{ $page->translations->count() - 3 }}
                                    </x-badge>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Status -->
                        <x-table-cell type="actions">
                            <form method="POST" action="{{ route('admin.pages.toggle-status', $page) }}">
                                @csrf @method('PATCH')
                                <x-toggle name="status_toggle_{{ $page->id }}" :checked="$page->status === 'published'" size="sm" variant="success" onchange="this.form.submit()" />
                            </form>
                        </x-table-cell>

                        <!-- Created -->
                        <x-table-cell type="text">
                            <div class="text-xs text-tertiary">
                                {{ $page->created_at->format('Y-m-d') }}
                            </div>
                        </x-table-cell>

                        <!-- Actions -->
                        <x-table-cell type="actions">
                            <div class="flex items-center justify-center gap-3">
                                <button onclick="editPage({{ $page->id }})" class="p-1.5 rounded-lg hover:bg-blue-50 text-blue-600" title="{{ admin_trans('edit') }}">
                                    <i data-lucide="edit-3" class="w-4 h-4"></i>
                                </button>
                                <button onclick="confirmDelete({{ $page->id }}, '{{ addslashes($translation->title ?? 'Page #' . $page->id) }}')" class="p-1.5 rounded-lg hover:bg-red-50 text-red-600" title="{{ admin_trans('delete') }}">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </x-table-cell>
                    </tr>
                @endforeach
            </x-enhanced-table>

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

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

        @if($currentCountry && $availableLocales->count() > 0)
            <form method="POST" action="{{ route('admin.pages.store') }}" class="space-y-6" onsubmit="saveAllEditors(); return true;">
                @csrf
                
                <!-- Current Context -->
                <x-alert variant="info" icon="info">
                    <div class="flex items-center gap-3">
                        <span class="text-2xl mb-2">{{ $currentCountry->flag_emoji }}</span>
                        <div>
                            <h4 class="font-semibold">{{ admin_trans('creating_page_for') }}</h4>
                            <p class="text-sm opacity-75">{{ $currentCountry->getName() }}</p>
                        </div>
                    </div>
                </x-alert>

                <!-- Multi-language Tabs -->
                <x-tabs defaultTab="{{ $availableLocales->first()->code }}">
                    <div class="flex flex-wrap gap-2 border-b mb-4" style="border-color: var(--color-border);">
                        @foreach($availableLocales as $locale)
                            <button type="button" 
                                @click="activeTab = '{{ $locale->code }}'; $event.preventDefault(); saveAllEditors(); setTimeout(() => { window.SecureTinyMCE.init(); }, 300);"
                                :class="activeTab === '{{ $locale->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>
                                {{ $locale->language->name ?? $locale->name }}
                                @if($locale->direction === 'rtl')
                                    <span class="text-xs">(ع)</span>
                                @endif
                            </button>
                        @endforeach
                    </div>

                    @foreach($availableLocales as $locale)
                        @php
                            $isRTL = $locale->direction === 'rtl';
                        @endphp
                        <x-tab-content :tab="$locale->code">
                            <div class="space-y-4" @if($isRTL) dir="rtl" @endif>
                                <x-input 
                                    :label="admin_trans('page_title')" 
                                    name="translations[{{ $locale->id }}][title]" 
                                    placeholder="{{ admin_trans('enter_page_title') }}" 
                                    :required="$loop->first" 
                                />
                                
                                {{-- FIXED: استخدام نظام SecureTinyMCE الموحد --}}
                                <x-tinymce 
                                    name="translations[{{ $locale->id }}][description]"
                                    :height="300"
                                    placeholder="{{ admin_trans('enter_page_content') }}"
                                    :value="old('translations.' . $locale->id . '.description', '')"
                                    :required="false"
                                    :locale="$locale->code"
                                    :direction="$locale->direction"
                                    :language="$locale->direction === 'rtl' ? 'ar' : 'en'"
                                >
                                <span style="color: var(--color-text-primary) ; " class="text-sm"> {{ admin_trans('description') }} </span>

                                </x-tinymce>
                            </div>
                        </x-tab-content>
                    @endforeach
                </x-tabs>

                <!-- Status -->
                <x-select :label="admin_trans('status')" name="status" :required="true">
                    <option value="draft" {{ old('status') === 'draft' ? 'selected' : '' }}>{{ admin_trans('draft') }}</option>
                    <option value="published" {{ old('status', 'published') === 'published' ? 'selected' : '' }}>{{ admin_trans('published') }}</option>
                </x-select>

                <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-page-modal')">{{ admin_trans('cancel') }}</x-button>
                    <x-button variant="primary" type="submit" icon="check">{{ admin_trans('create') }}</x-button>
                </div>
            </form>
        @else
            <x-empty-state icon="globe" :title="admin_trans('select_country_first')" :description="admin_trans('use_country_filter_navbar')">
                <x-button variant="outline" @click="$dispatch('close-modal', 'create-page-modal')">{{ admin_trans('close') }}</x-button>
            </x-empty-state>
        @endif
    </div>
</x-modal>

<!-- Edit Modal - FIXED VERSION -->
<x-modal name="edit-page-modal" maxWidth="3xl">
    <div class="p-6" x-data="editPageModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_page') }}</h3>
            <button @click="$dispatch('close-modal', 'edit-page-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <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 && pageData" x-cloak>
            <form :action="`/admin/pages/${pageData?.id}`" method="POST" class="space-y-6" onsubmit="saveAllEditors(); return true;">
                @csrf @method('PUT')
                
                @if($availableLocales->count() > 0)
                    <x-tabs defaultTab="{{ $availableLocales->first()->code }}">
                        <div class="flex flex-wrap gap-2 border-b mb-4" style="border-color: var(--color-border);">
                            @foreach($availableLocales as $locale)
                                <button type="button" 
                                    @click="activeTab = '{{ $locale->code }}'; handleTabChange({{ $locale->id }}); $event.preventDefault();"
                                    :class="activeTab === '{{ $locale->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>
                                    {{ $locale->language->name ?? $locale->name }}
                                    @if($locale->direction === 'rtl')
                                        <span class="text-xs">(ع)</span>
                                    @endif
                                </button>
                            @endforeach
                        </div>

                        @foreach($availableLocales as $locale)
                            @php
                                $isRTL = $locale->direction === 'rtl';
                            @endphp
                            <x-tab-content :tab="$locale->code">
                                <div class="space-y-4" @if($isRTL) dir="rtl" @endif>
                                    <x-input 
                                        :label="admin_trans('page_title')" 
                                        :name="'translations[' . $locale->id . '][title]'" 
                                        placeholder="{{ admin_trans('enter_page_title') }}"
                                        x-bind:value="getTranslationValue({{ $locale->id }}, 'title')"
                                        @input="setTranslationValue({{ $locale->id }}, 'title', $event.target.value)"
                                    />
                                    
                                    {{-- FIXED: استخدام نظام TinyMCE الموحد مع ربط البيانات الصحيح --}}
                                    <div class="tinymce-edit-container" data-locale-id="{{ $locale->id }}">
                                        <x-tinymce 
                                            name="translations[{{ $locale->id }}][description]"
                                            :height="300"
                                            placeholder="{{ admin_trans('enter_page_content') }}"
                                            :value="''"
                                            :required="false"
                                            :locale="$locale->code"
                                            :direction="$locale->direction"
                                            :language="$locale->direction === 'rtl' ? 'ar' : 'en'"
                                        >
                                            {{ admin_trans('description') }}
                                        </x-tinymce>
                                    </div>
                                </div>
                            </x-tab-content>
                        @endforeach
                    </x-tabs>
                @endif

                <!-- Status -->
                <x-select :label="admin_trans('status')" name="status" :required="true">
                    <option value="draft" x-bind:selected="pageData?.status === 'draft'">{{ admin_trans('draft') }}</option>
                    <option value="published" x-bind:selected="pageData?.status === 'published'">{{ admin_trans('published') }}</option>
                </x-select>

                <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-page-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 -->
<x-confirm-modal name="delete-page-modal" :title="admin_trans('confirm_delete')" :message="admin_trans('delete_page_message')" :confirmText="admin_trans('yes_delete')" :cancelText="admin_trans('cancel')" confirmVariant="danger" icon="trash-2" iconColor="danger" />

@endsection

@push('scripts')
<script>
// Alpine.js Pages Component
function pagesPage() {
    return {
        selectedItems: [],

        init() {
            try {
                this.listenToCountryFilter();
            } catch (error) {
                console.log('Init error (safely handled):', error);
            }
        },

        listenToCountryFilter() {
            window.addEventListener('country-filter-changed', () => {
                if (window.toast) {
                    toast.info('{{ admin_trans("refreshing_pages") }}...');
                }
                setTimeout(() => window.location.reload(), 500);
            });
        },

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

        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' && !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/pages/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 Page Modal - استخدام نظام SecureTinyMCE الموحد
function editPageModal() {
    return {
        loading: false,
        pageData: null,

        async loadPage(id) {
            this.loading = true;
            try {
                const response = await fetch(`/admin/pages/${id}/edit`);
                const result = await response.json();
                
                if (result.success) {
                    this.pageData = result.data;
                    
                    console.log('📊 تم تحميل بيانات الصفحة:', this.pageData);
                    
                    // انتظار عرض النموذج
                    await this.$nextTick();
                    
                    // تحديث حقول النموذج بعد تأخير قصير
                    setTimeout(() => {
                        this.updateAllFieldsWithData();
                    }, 500);
                }
            } catch (error) {
                console.error('Error loading page:', error);
                if (window.toast) {
                    toast.error('{{ admin_trans("error_loading_page") }}');
                }
            } finally {
                this.loading = false;
            }
        },

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

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

        // FIXED: طريقة محدثة لتحديث جميع الحقول باستخدام SecureTinyMCE
        updateAllFieldsWithData() {
            if (!this.pageData || !this.pageData.translations) {
                console.warn('⚠️ No page data or translations available');
                return;
            }
            
            console.log('🔄 تحديث جميع الحقول ببيانات الصفحة');
            
            // تحديث محررات TinyMCE لكل لغة
            this.pageData.translations.forEach((translation) => {
                const localeId = translation.locale_id;
                const editorName = `translations[${localeId}][description]`;
                
                console.log(`🔍 تحديث المحرر للغة ${localeId}:`, translation.description);
                
                // البحث عن textarea بهذا الاسم
                setTimeout(() => {
                    const textareas = document.querySelectorAll(`textarea[name="${editorName}"]`);
                    
                    textareas.forEach(textarea => {
                        if (translation.description) {
                            // تعيين قيمة textarea مباشرة
                            textarea.value = translation.description;
                            textarea.dataset.originalContent = translation.description;
                            
                            console.log(`✅ تم تعيين المحتوى لـ ${textarea.id}:`, translation.description.substring(0, 50) + '...');
                            
                            // تحديث SecureTinyMCE إذا كان متاحًا
                            if (window.SecureTinyMCE) {
                                try {
                                    const editorInstance = window.SecureTinyMCE.getInstance(textarea.id);
                                    if (editorInstance && !editorInstance.destroyed) {
                                        editorInstance.setContent(translation.description, {format: 'raw'});
                                        console.log(`🎯 تم تحديث SecureTinyMCE لـ ${textarea.id}`);
                                    } else {
                                        // المحرر غير جاهز بعد، محاولة أخرى
                                        setTimeout(() => {
                                            const retryEditor = window.SecureTinyMCE.getInstance(textarea.id);
                                            if (retryEditor && !retryEditor.destroyed) {
                                                retryEditor.setContent(translation.description, {format: 'raw'});
                                                console.log(`🔄 تم تحديث SecureTinyMCE بالمحاولة الثانية لـ ${textarea.id}`);
                                            }
                                        }, 500);
                                    }
                                } catch (error) {
                                    console.warn(`⚠️ خطأ في تحديث SecureTinyMCE لـ ${textarea.id}:`, error);
                                }
                            }
                            
                            // طريقة بديلة: الوصول المباشر لـ TinyMCE
                            if (typeof tinymce !== 'undefined') {
                                try {
                                    const editor = tinymce.get(textarea.id);
                                    if (editor) {
                                        editor.setContent(translation.description, {format: 'raw'});
                                        console.log(`🎯 تحديث مباشر لـ TinyMCE ${textarea.id}`);
                                    }
                                } catch (error) {
                                    console.warn(`⚠️ خطأ TinyMCE المباشر لـ ${textarea.id}:`, error);
                                }
                            }
                        }
                    });
                }, 300);
                
                // محاولة أطول للمحررات العنيدة
                setTimeout(() => {
                    const textareas = document.querySelectorAll(`textarea[name="${editorName}"]`);
                    textareas.forEach(textarea => {
                        if (translation.description && textarea.value !== translation.description) {
                            textarea.value = translation.description;
                            
                            // إجبار تحديث TinyMCE
                            if (typeof tinymce !== 'undefined') {
                                const editor = tinymce.get(textarea.id);
                                if (editor && editor.getContent() !== translation.description) {
                                    editor.setContent(translation.description, {format: 'raw'});
                                    console.log(`🔄 تم التحديث القسري لـ TinyMCE ${textarea.id}`);
                                }
                            }
                        }
                    });
                }, 1000);
            });
        },

        // طريقة للتعامل مع تغيير التابات
        handleTabChange(localeId) {
            // حفظ المحررات قبل تغيير التاب
            if (window.SecureTinyMCE && typeof window.SecureTinyMCE.save === 'function') {
                window.SecureTinyMCE.save();
            }
            
            // تحديث محتوى المحرر للتاب النشط
            setTimeout(() => {
                this.updateTinyMCEContent();
            }, 200);
        },

        // طريقة لتحديث محتوى TinyMCE عند تبديل التابات
        updateTinyMCEContent() {
            setTimeout(() => {
                if (window.SecureTinyMCE) {
                    window.SecureTinyMCE.init();
                }
                this.updateAllFieldsWithData();
            }, 200);
        }
    }
}

// FIXED: دالة تحرير الصفحة المحسنة
function editPage(id) {
    console.log('🔧 فتح نموذج التحرير للصفحة:', id);
    
    // فتح النموذج
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-page-modal' }));
    
    // تحميل بيانات الصفحة مع التوقيت الصحيح
    setTimeout(() => {
        const modal = document.querySelector('[x-data*="editPageModal"]');
        if (modal && modal._x_dataStack && modal._x_dataStack[0]) {
            console.log('📂 تحميل بيانات الصفحة...');
            modal._x_dataStack[0].loadPage(id);
        } else {
            console.warn('⚠️ لم يتم العثور على مكون النموذج، محاولة أخرى...');
            // إعادة محاولة بعد تأخير أطول
            setTimeout(() => {
                const retryModal = document.querySelector('[x-data*="editPageModal"]');
                if (retryModal && retryModal._x_dataStack && retryModal._x_dataStack[0]) {
                    retryModal._x_dataStack[0].loadPage(id);
                }
            }, 500);
        }
    }, 100);
}

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

// FIXED: دالة عامة لحفظ جميع محررات TinyMCE قبل إرسال النموذج
function saveAllEditors() {
    if (window.SecureTinyMCE && typeof window.SecureTinyMCE.save === 'function') {
        window.SecureTinyMCE.save();
    }
    
    // طريقة بديلة باستخدام tinymce العامة
    if (typeof tinymce !== 'undefined') {
        tinymce.triggerSave();
    }
}

// FIXED: تحسين التعامل مع إرسال النماذج
document.addEventListener('DOMContentLoaded', function() {
    // تطبيق أيقونات Lucide
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
    
    // التعامل مع جميع النماذج التي تحتوي على محررات TinyMCE
    document.addEventListener('submit', function(e) {
        // حفظ جميع المحررات قبل أي إرسال نموذج
        saveAllEditors();
    });
    
    // منع إرسال النموذج عند تبديل التابات
    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')
        )) {
            // هذا زر تاب، منع أي إرسال محتمل للنموذج
            e.preventDefault();
            e.stopPropagation();
            
            // حفظ المحررات قبل تغيير التاب
            saveAllEditors();
        }
    });
});
</script>
@endpush