@php
use App\Models\Page;

// Get the record being edited
$record = $getRecord();

// Generate preview URL
$previewUrl = $record ? route('page.show', $record->slug) : url('/');
$draftPreviewUrl = $record ? route('preview-draft.page', ['page' => $record]) : $previewUrl;
@endphp

<div class="space-y-4 page-edit-preview-wrap"
     x-data="{
        refreshing: false,
        lastSaved: null,
        lastPreviewHash: null,
        showPreview: true,
        draftPreviewBase: @js($draftPreviewUrl),
        autoPreviewTimer: null,
        autoPreviewDelayMs: 900,
        device: 'desktop',
        devices: {
            'desktop': '100%',
            'tablet': '768px',
            'mobile': '375px'
        },

        refreshPreview() {
            this.loadDraftPreview(this.$refs.previewFrame?.src || this.draftPreviewBase);
        },

        async triggerDraftPreview(force = false) {
            if (force) {
                this.$wire.previewDraftNow();
                return;
            }

            // Force the active input to queue its value to Livewire/Alpine 
            // by simulating a blur and change event (without actually losing focus).
            // We avoid doing this on SELECT elements to prevent closing dropdowns.
            const active = document.activeElement;
            const isField = active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA');
            if (isField && !active.closest('.choices, .ts-control')) { // Avoid Choice.js or TomSelect controls
                active.dispatchEvent(new Event('change', { bubbles: true }));
                active.dispatchEvent(new Event('blur', { bubbles: true }));
                // Give Alpine a tiny tick to queue the Livewire state
                await new Promise(resolve => setTimeout(resolve, 50));
            }

            // Force Livewire to sync any pending deferred wire:models to the server
            if (typeof this.$wire.$commit === 'function') {
                await this.$wire.$commit();
            }

            this.$wire.previewDraft();
        },

        queueDraftPreview(target) {
            if (!this.isEligibleEditTarget(target)) {
                return;
            }

            clearTimeout(this.autoPreviewTimer);
            this.autoPreviewTimer = setTimeout(() => {
                this.triggerDraftPreview(false);
            }, this.autoPreviewDelayMs);
        },

        isEligibleEditTarget(target) {
            if (!target || !(target instanceof Element)) {
                return false;
            }

            if (target.closest('.filepond--root')) {
                return false;
            }

            if (target.closest('.page-edit-preview-wrap')) {
                return false;
            }

            const field = target.closest('input, textarea, select, [contenteditable=true]');
            if (field) {
                return true; // Any form field change should trigger the preview
            }

            const button = target.closest('button');
            if (button) {
                return true; // Any button click (like Add Block, Delete, Toggle) should trigger the preview
            }

            return false;
        },

        loadDraftPreview(url, silent = false) {
            if (!url) return;
            if (!silent) this.refreshing = true;
            const iframe = this.$refs.previewFrame;
            const done = () => {
                if (!silent) this.refreshing = false;
                this.lastSaved = new Date().toLocaleTimeString('ar-SA');
            };
            iframe.onload = () => done();
            iframe.onerror = () => done();
            const nextUrl = new URL(url, window.location.origin);
            nextUrl.searchParams.set('_', Date.now());
            iframe.src = nextUrl.toString();
            setTimeout(done, 8000);
        },

        handleDraftPreviewUrl(event) {
            const d = event.detail;
            const payload = (Array.isArray(d) && d.length && typeof d[0] === 'object') ? d[0] : d;
            const url = (payload && typeof payload === 'object' && payload.url) ? payload.url : (typeof payload === 'string' ? payload : null);
            let hash = (payload && typeof payload === 'object' && payload.hash) ? payload.hash : null;
            const silent = !!(payload && typeof payload === 'object' && payload.silent);
            const force = !!(payload && typeof payload === 'object' && payload.force);
            if (!hash && url) {
                try { hash = (new URL(url, window.location.origin)).searchParams.get('v'); } catch (e) {}
            }
            if (!force && hash && this.lastPreviewHash === hash) return;
            if (hash) this.lastPreviewHash = hash;
            if (url) this.loadDraftPreview(url, silent);
        }
     }"
     x-init="
        const onInput = (event) => queueDraftPreview(event.target);
        const onChange = (event) => queueDraftPreview(event.target);
        const onClick = (event) => queueDraftPreview(event.target);
        window.addEventListener('input', onInput, true);
        window.addEventListener('change', onChange, true);
        window.addEventListener('click', onClick, true);
        const stopContentWatch = $wire.$watch('data.content', () => {
            clearTimeout(this.autoPreviewTimer);
            this.autoPreviewTimer = setTimeout(() => triggerDraftPreview(false), this.autoPreviewDelayMs);
        });
        $el.addEventListener('alpine:destroy', () => {
            window.removeEventListener('input', onInput, true);
            window.removeEventListener('change', onChange, true);
            window.removeEventListener('click', onClick, true);
            clearTimeout(this.autoPreviewTimer);
            if (typeof stopContentWatch === 'function') stopContentWatch();
        });
        $wire.$watch('activeLocale', () => {
            setTimeout(() => triggerDraftPreview(true), 150);
        });
     "
     @page-saved.window="refreshPreview()"
     @draft-preview-url.window="handleDraftPreviewUrl($event)"
>
    {{-- When preview hidden: show bar to expand --}}
    <div x-show="!showPreview" x-transition class="flex items-center justify-between bg-gray-100 p-2 rounded-lg border border-gray-200">
        <span class="text-sm text-gray-600">المعاينة مخفية</span>
        <button type="button" @click="showPreview = true" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100">
            إظهار المعاينة
        </button>
    </div>

    {{-- Preview panel (can hide) --}}
    <div x-show="showPreview" x-transition class="space-y-4">
    {{-- Header with controls --}}
    <div class="flex items-center justify-between bg-white p-3 rounded-lg border border-gray-200">
        <div class="flex items-center gap-3">
            <span class="text-sm font-medium text-gray-700">معاينة مباشرة</span>
            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                <span class="w-1.5 h-1.5 bg-green-500 rounded-full mr-1 animate-pulse"></span>
                تحديث تلقائي
            </span>
            <span x-show="lastSaved" x-transition class="text-xs text-gray-400">
                آخر تحديث: <span x-text="lastSaved"></span>
            </span>
        </div>
        
        <div class="flex items-center gap-2 flex-wrap">
            {{-- Device Toggles --}}
            <div class="flex items-center bg-gray-100 rounded-lg p-1 mr-2">
                <button type="button" @click="device = 'desktop'" :class="device === 'desktop' ? 'bg-white shadow-sm text-primary-600' : 'text-gray-500 hover:text-gray-700'" class="p-1.5 rounded-md transition-all" title="Desktop">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-2 1h10l-2-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                </button>
                <button type="button" @click="device = 'tablet'" :class="device === 'tablet' ? 'bg-white shadow-sm text-primary-600' : 'text-gray-500 hover:text-gray-700'" class="p-1.5 rounded-md transition-all" title="Tablet">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path></svg>
                </button>
                <button type="button" @click="device = 'mobile'" :class="device === 'mobile' ? 'bg-white shadow-sm text-primary-600' : 'text-gray-500 hover:text-gray-700'" class="p-1.5 rounded-md transition-all" title="Mobile">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path></svg>
                </button>
            </div>

            {{-- Hide preview --}}
            <button type="button" @click="showPreview = false" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200">
                إخفاء المعاينة
            </button>
            {{-- Manual preview (no save); id used so auto-preview can trigger it --}}
            <button 
                id="preview-draft-trigger"
                type="button"
                wire:click="previewDraftNow"
                wire:loading.attr="disabled"
                wire:target="previewDraftNow"
                class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50"
            >
                <span wire:loading.remove wire:target="previewDraftNow">معاينة الآن</span>
                <span wire:loading wire:target="previewDraftNow">جاري التحميل...</span>
            </button>
            {{-- Refresh (saved version) --}}
            <button 
                type="button"
                @click="refreshPreview()"
                :disabled="refreshing"
                class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50"
            >
                <svg :class="refreshing ? 'animate-spin' : ''" class="w-3.5 h-3.5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
                <span x-text="refreshing ? 'جاري التحديث...' : 'تحديث'"></span>
            </button>
            
            {{-- Open in New Tab --}}
            <a href="{{ $previewUrl }}" target="_blank" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100 transition-colors">
                فتح
                <svg class="w-3.5 h-3.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path>
                </svg>
            </a>
        </div>
    </div>
    
    {{-- Preview Frame --}}
    <div class="iframe-view-wrapper flex justify-center bg-gray-200 py-4 rounded-xl border-2 border-dashed border-gray-300 overflow-hidden" style="height: min(900px, 85vh); overflow-y: auto;">
        <div 
            class="iframe-container bg-white shadow-2xl transition-all duration-500 ease-in-out mx-auto overflow-hidden relative"
            :style="'width: ' + devices[device] + '; height: 100%;'"
        >
            <iframe 
                x-ref="previewFrame"
                src="{{ $draftPreviewUrl }}?preview=1" 
                class="w-full h-full min-w-0"
                style="min-height: 100%; border: none;"
                sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
            ></iframe>
            
            {{-- Loading Overlay --}}
            <div x-show="refreshing" x-transition class="absolute inset-0 bg-white/80 flex items-center justify-center z-10">
                <div class="flex flex-col items-center gap-3">
                    <svg class="w-10 h-10 text-primary-500 animate-spin" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <span class="text-sm text-gray-600 font-medium">جاري تحديث المعاينة...</span>
                </div>
            </div>
        </div>
    </div>
    
    {{-- Quick Tips --}}
    <div class="flex items-center gap-2 text-xs text-gray-500 bg-blue-50 p-3 rounded-lg border border-blue-100">
        <svg class="w-4 h-4 text-blue-500 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <span>المعاينة تتحدث تلقائياً عند التحرير (بدون حفظ). الحفظ يتم فقط عند النقر على «حفظ التغييرات» أسفل الصفحة.</span>
    </div>
    </div>
</div>

<style>
    /* Smooth scrollbar */
    iframe::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }
    iframe::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
    iframe::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
    }
    iframe::-webkit-scrollbar-thumb:hover {
        background: #a1a1a1;
    }
    
    /* Floating Save Button - Fixed Bottom Right */
    .fi-form-actions {
        position: fixed !important;
        bottom: 24px !important;
        right: 24px !important;
        left: auto !important;
        top: auto !important;
        z-index: 9999 !important;
        background: white !important;
        padding: 12px 20px !important;
        border-radius: 16px !important;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08) !important;
        border: 1px solid rgba(0, 0, 0, 0.06) !important;
        flex-direction: row !important;
        gap: 12px !important;
        animation: slideUp 0.3s ease-out;
    }
    
    @keyframes slideUp {
        from {
            transform: translateY(100px);
            opacity: 0;
        }
        to {
            transform: translateY(0);
            opacity: 1;
        }
    }
    
    .fi-form-actions button[type="submit"] {
        background: linear-gradient(135deg, #00A0B0 0%, #2D9CDB 100%) !important;
        color: white !important;
        font-weight: 600 !important;
        padding: 12px 28px !important;
        border-radius: 50px !important;
        border: none !important;
        box-shadow: 0 4px 15px rgba(0, 160, 176, 0.35) !important;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        display: inline-flex !important;
        align-items: center !important;
        gap: 8px !important;
    }
    
    .fi-form-actions button[type="submit"]:hover {
        transform: translateY(-2px) scale(1.02) !important;
        box-shadow: 0 8px 25px rgba(0, 160, 176, 0.45) !important;
    }
    
    .fi-form-actions button[type="submit"]:active {
        transform: translateY(0) scale(0.98) !important;
    }
    
    /* Cancel button */
    .fi-form-actions button[type="button"] {
        padding: 12px 24px !important;
        border-radius: 50px !important;
        font-weight: 500 !important;
        transition: all 0.2s ease !important;
    }
    
    /* Add padding to page content so save button doesn't cover anything */
    .fi-main {
        padding-bottom: 120px !important;
    }
    
    /* RTL Support for floating button */
    [dir="rtl"] .fi-form-actions {
        right: auto !important;
        left: 24px !important;
    }
</style>
