/**
 * Enhanced Preview System for Instant Popup Builder
 * Provides accurate frontend-like previews in the admin area
 */

(function($) {
    'use strict';

    // Enhanced Preview Manager
    const EnhancedPreview = {
        init: function() {
            this.loadFrontendCSS();
            this.setupPreviewContainers();
            this.bindEvents();
        },

        // Load frontend CSS for accurate previews
        loadFrontendCSS: function() {
            const frontendCSS = `
                <link id="enhanced-preview-frontend-css" rel="stylesheet" href="${instant_popup_admin.ajaxurl.replace('admin-ajax.php', '')}wp-content/plugins/instant-popup-builder/public/css/instant-popup-builder-public.css" type="text/css" media="all" />
                <style id="enhanced-preview-styles">
                    /* Enhanced Preview Modal Styles */
                    .enhanced-preview-modal {
                        position: fixed !important;
                        top: 0 !important;
                        left: 0 !important;
                        width: 100% !important;
                        height: 100% !important;
                        background: rgba(15, 23, 42, 0.82) !important;
                        backdrop-filter: blur(6px) !important;
                        z-index: 999999 !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        padding: 76px 24px 24px !important;
                        box-sizing: border-box !important;
                    }

                    .enhanced-preview-content {
                        position: relative !important;
                        width: min(1180px, 94vw) !important;
                        height: min(760px, calc(100vh - 108px)) !important;
                        max-width: 94vw !important;
                        max-height: calc(100vh - 108px) !important;
                        background: #e2e8f0 !important;
                        border: 1px solid rgba(255, 255, 255, 0.35) !important;
                        border-radius: 18px !important;
                        overflow: hidden !important;
                        box-shadow: 0 28px 80px rgba(2, 6, 23, 0.45) !important;
                    }

                    .enhanced-preview-close {
                        position: absolute !important;
                        top: 14px !important;
                        right: 14px !important;
                        width: 34px !important;
                        height: 34px !important;
                        background: #ffffff !important;
                        border-radius: 9px !important;
                        border: 1px solid #cbd5e1 !important;
                        cursor: pointer !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        font-size: 18px !important;
                        color: #475569 !important;
                        z-index: 1000000 !important;
                        transition: all 0.2s ease !important;
                    }

                    .enhanced-preview-close:hover {
                        background: #f8fafc !important;
                        color: #0f172a !important;
                        transform: translateY(-1px) !important;
                    }

                    /* Preview Device Sizes */
                    .preview-device-selector {
                        position: absolute !important;
                        top: 18px !important;
                        left: 50% !important;
                        transform: translateX(-50%) !important;
                        z-index: 1000000 !important;
                        background: rgba(255, 255, 255, 0.95) !important;
                        border: 1px solid rgba(226, 232, 240, 0.9) !important;
                        border-radius: 12px !important;
                        padding: 5px !important;
                        box-shadow: 0 8px 24px rgba(15, 23, 42, 0.22) !important;
                    }

                    .preview-device-btn {
                        background: #f3f4f6 !important;
                        border: 0 !important;
                        padding: 8px 14px !important;
                        margin: 0 !important;
                        border-radius: 8px !important;
                        cursor: pointer !important;
                        font-size: 12px !important;
                        color: #374151 !important;
                        transition: all 0.2s ease !important;
                    }

                    .preview-device-btn.active {
                        background: #2563eb !important;
                        color: #fff !important;
                        box-shadow: 0 2px 8px rgba(37, 99, 235, 0.28) !important;
                    }

                    .preview-device-btn:hover {
                        background: #e5e7eb !important;
                    }

                    .preview-device-btn.active:hover {
                        background: #2563eb !important;
                    }

                    /* Device-specific preview sizes */
                    .preview-content-wrapper {
                        width: 100% !important;
                        height: 100% !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        padding: 42px !important;
                        overflow: auto !important;
                        box-sizing: border-box !important;
                        background-color: #f8fafc !important;
                        background-image:
                            linear-gradient(45deg, #edf2f7 25%, transparent 25%),
                            linear-gradient(-45deg, #edf2f7 25%, transparent 25%),
                            linear-gradient(45deg, transparent 75%, #edf2f7 75%),
                            linear-gradient(-45deg, transparent 75%, #edf2f7 75%) !important;
                        background-size: 22px 22px !important;
                        background-position: 0 0, 0 11px, 11px -11px, -11px 0 !important;
                    }

                    .preview-mobile .enhanced-preview-content {
                        width: 375px !important;
                        height: min(720px, calc(100vh - 108px)) !important;
                    }

                    .preview-tablet .enhanced-preview-content {
                        width: 768px !important;
                        height: min(720px, calc(100vh - 108px)) !important;
                    }

                    .preview-desktop .enhanced-preview-content {
                        width: min(1180px, 94vw) !important;
                    }

                    /* Ensure frontend styles are applied */
                    .enhanced-preview-modal .instant_popup-front {
                        display: block !important;
                        position: static !important;
                    }

                    .enhanced-preview-modal .instant_overlay {
                        position: static !important;
                        background: transparent !important;
                        padding: 0 !important;
                        height: auto !important;
                        width: auto !important;
                    }

                    .enhanced-preview-modal .instant-popup-content {
                        top: auto !important;
                        transform: none !important;
                        box-shadow: 0 20px 55px rgba(15, 23, 42, 0.22) !important;
                    }

                    .enhanced-preview-modal .intant-popup-type-text .inner_content > :first-child {
                        margin-top: 0 !important;
                    }

                    .enhanced-preview-modal .intant-popup-type-text .inner_content > :last-child {
                        margin-bottom: 0 !important;
                    }

                    @media (max-width: 600px) {
                        .enhanced-preview-modal {
                            padding: 72px 10px 10px !important;
                        }
                        .preview-device-btn {
                            padding: 7px 9px !important;
                        }
                        .preview-content-wrapper {
                            padding: 22px !important;
                        }
                    }
                </style>
            `;

            if (!$('#enhanced-preview-styles').length) {
                $('head').append(frontendCSS);
            }
        },

        // Setup enhanced preview containers
        setupPreviewContainers: function() {
            // Handle enhanced preview triggers
            $('body').on('click', '.enhanced-preview-trigger', function(e) {
                e.preventDefault();
                const popupType = $(this).closest('form').find('[name="popup_temp_type"]').val();
                const content = EnhancedPreview.getPreviewContent(popupType);
                EnhancedPreview.showEnhancedPreview(content, popupType);
            });
        },

        // Get preview content based on popup type
        getPreviewContent: function(popupType) {
            let content = '';

            switch(popupType) {
                case 'popup_text':
                    // Sync TinyMCE content before getting it
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('popup_type_value')) {
                        tinyMCE.get('popup_type_value').save();
                    }
                    content = $('#popup_type_value').val() || '<p>Enter your text content here...</p>';
                    break;
                case 'popup_html':
                    content = $('#popup_type_value').val() || '<p>Enter your HTML content here...</p>';
                    break;
                case 'popup_image':
                    const imageUrl = $('#popu_image_url').val() || $('#popup_image_url').val();
                    content = imageUrl ? `<img src="${imageUrl}" style="width:100%; max-width:500px; height:auto; border-radius:8px;" alt="Preview Image" />` : '<p>Upload an image to see preview...</p>';
                    break;
                case 'popup_subscription':
                    content = EnhancedPreview.generateSubscriptionPreview();
                    break;
                default:
                    content = $('#popup_type_value').val() || '<p>Content preview...</p>';
            }

            return content;
        },

        // Get server-side preview content for better accuracy
        getServerPreviewContent: function(popupType, contentData) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: instant_popup_admin.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'generate_enhanced_preview',
                        popup_type: popupType,
                        content_data: contentData,
                        nonce: instant_popup_admin.enhanced_preview_nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve(response.data.preview_content);
                        } else {
                            reject('Failed to generate preview');
                        }
                    },
                    error: function() {
                        reject('AJAX error');
                    }
                });
            });
        },

        // Generate subscription popup preview
        generateSubscriptionPreview: function() {
            const title = $('#popup_title').val() || 'Subscribe to Our Newsletter';
            const description = 'Get the latest updates and news delivered to your inbox.';

            return `
                <div class="basic-newsletter-container">
                    <div class="newsletter-content-section">
                        <div class="content-wrapper">
                            <div class="newsletter-header">
                                <h2 class="newsletter-title">${title}</h2>
                                <p class="newsletter-description">${description}</p>
                            </div>
                            <form class="newsletter-form">
                                <div class="form-row">
                                    <label class="form-label" for="preview_first_name">Full Name</label>
                                    <input type="text" id="preview_first_name" name="first_name" placeholder="Enter your full name" class="form-input" readonly>
                                </div>
                                <div class="form-row">
                                    <label class="form-label" for="preview_email">Email Address</label>
                                    <input type="email" id="preview_email" name="email_address" placeholder="Enter your email address" class="form-input" readonly>
                                </div>
                                <div class="form-row privacy-row">
                                    <label class="privacy-label">
                                        <input type="checkbox" class="privacy-checkbox" disabled>
                                        <span class="checkbox-custom"></span>
                                        <span class="privacy-text">I agree to the <a href="#" target="_blank">Privacy Policy</a></span>
                                    </label>
                                </div>
                                <div class="form-row submit-row">
                                    <button type="button" class="newsletter-submit-btn" disabled>Subscribe Now</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
        },

        // Generate fallback content when server-side fails
        generateFallbackContent: function(popupType, contentData) {
            switch(popupType) {
                case 'popup_text':
                    return this.generateTextFallback(contentData);
                case 'popup_html':
                    return this.generateHtmlFallback(contentData);
                case 'popup_image':
                    return this.generateImageFallback(contentData);
                case 'popup_subscription':
                    return this.generateSubscriptionPreview();
                default:
                    return this.generateDefaultFallback(contentData);
            }
        },

        // Generate text popup fallback
        generateTextFallback: function(data) {
            const content = data.content || '<p>Enter your text content here...</p>';
            const bgColor = data.background_color || '#ffffff';
            const textColor = data.text_color || '#333333';
            const padding = [
                data.text_padding_top ?? 20,
                data.text_padding_right ?? 25,
                data.text_padding_bottom ?? 20,
                data.text_padding_left ?? 25
            ].join('px ') + 'px';

            return `
                <div class="intant-popup-type-text instant-popup-content ipb-text-custom-styled ipb-close-at-right" style="background-color:${bgColor};color:${textColor};padding:${padding};border-radius:${data.text_border_radius ?? 12}px;font-size:${data.text_font_size || 16}px;line-height:${data.text_line_height || 1.5};height:auto;max-height:${data.design_height > 0 ? Math.min(data.design_height, window.innerHeight * 0.85) + 'px' : '85vh'};max-width:95vw;margin:0 auto;">
                    <button type="button" class="instant-cross" aria-label="Close preview popup"><i class="fa-solid fa-xmark" aria-hidden="true"></i></button>
                    <div class="inner_content" style="overflow:auto;max-height:100%;scrollbar-width:none;">${content}</div>
                </div>
            `;
        },

        // Generate HTML popup fallback
        generateHtmlFallback: function(data) {
            const content = data.content || '<p>Enter your HTML content here...</p>';

            return `
                <div class="instant-popup-content" style="background: transparent; padding: 0; max-width: 90vw; max-height: 90vh;">
                    <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #666; z-index: 1000;">
                        <i class="fa-solid fa-circle-xmark"></i>
                    </div>
                    <div class="inner_content" style="overflow: visible;">${content}</div>
                </div>
            `;
        },

        // Generate image popup fallback
        generateImageFallback: function(data) {
            const imageUrl = data.image_url || '';

            if (!imageUrl) {
                return `
                    <div class="instant-popup-content" style="background: #f5f5f5; padding: 50px; text-align: center; border-radius: 8px; max-width: 500px; margin: 0 auto;">
                        <p>Upload an image to see preview...</p>
                    </div>
                `;
            }

            return `
                <div class="instant-popup-content" style="background: transparent; padding: 0; max-width: 90vw; max-height: 90vh;">
                    <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #fff; z-index: 1000; background: rgba(0,0,0,0.5); border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                        <i class="fa-solid fa-times"></i>
                    </div>
                    <img src="${imageUrl}" style="width: 100%; max-width: 800px; height: auto; border-radius: 8px; display: block; margin: 0 auto;" alt="Preview Image" />
                </div>
            `;
        },

        // Generate default fallback
        generateDefaultFallback: function(data) {
            const content = data.content || '<p>Content preview...</p>';

            return `
                <div class="instant-popup-content" style="background: #ffffff; padding: 30px; border-radius: 8px; max-width: 500px; margin: 0 auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);">
                    <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #666;">
                        <i class="fa-solid fa-circle-xmark"></i>
                    </div>
                    <div class="inner_content">${content}</div>
                </div>
            `;
        },

        // Show enhanced preview modal - only enhanced preview
        showEnhancedPreview: function(content, popupType) {
            // Get server-side preview for accuracy
            const contentData = this.gatherContentData(popupType);

            this.getServerPreviewContent(popupType, contentData).then(serverContent => {
                this.displayPreviewModal(serverContent, popupType);
            }).catch(() => {
                // Fallback to client-side content generation
                const fallbackContent = this.generateFallbackContent(popupType, contentData);
                this.displayPreviewModal(fallbackContent, popupType);
            });
        },

        // Gather content data for server-side preview generation
        gatherContentData: function(popupType) {
            const data = {
                content: $('#popup_type_value').val() || '',
                title: $('#popup_title').val() || '',
                background_selection: $('#background_enabled').is(':checked') ? ($('#background_selection').val() || 'color') : '',
                background_color: $('input[name="background_color"]').val() || '#ffffff',
                background_image: $('#background_image_url').val() || '',
                background_size: $('#back_image_size').val() || 'cover',
                background_opacity: ($('#background_selection').val() === 'image' ? $('#backimage_opacity').val() : $('#backcolor_opacity').val()) || 1,
                text_color: $('input[name="text_color"]').val() || '#333333',
                text_padding_top: $('input[name="text_padding_top"]').val() || 20,
                text_padding_right: $('input[name="text_padding_right"]').val() || 25,
                text_padding_bottom: $('input[name="text_padding_bottom"]').val() || 20,
                text_padding_left: $('input[name="text_padding_left"]').val() || 25,
                text_border_radius: $('input[name="text_border_radius"]').val() || 12,
                text_font_size: $('input[name="text_font_size"]').val() || 16,
                text_line_height: $('input[name="text_line_height"]').val() || 1.5,
                border_enabled: $('input[name="border_enabled"]').is(':checked') ? 'yes' : 'no',
                border_width: $('input[name="border_width"]').val() || 1,
                border_color: $('input[name="border_color"]').val() || '#111827',
                design_width: $('input[name="design_width"]').val() || 0,
                design_height: $('input[name="design_height"]').val() || 0,
                design_percentage: $('input[name="design_percentage"]').val() || 50,
                design_percentage_toggle: $('#design_percentage_toggle').val() || 'yes',
                button_text: $('input[name="button_text"]').val() || 'Subscribe Now',
                button_color: $('input[name="button_color"]').val() || '#3b82f6',
                image_url: $('#popu_image_url').val() || $('#popup_image_url').val() || '',
                image_position: $('input[name="image_position"]:checked').val() || 'right'
            };

            return data;
        },

        // Display the preview modal
        displayPreviewModal: function(content, popupType) {
            const modal = $(`
                <div class="enhanced-preview-modal">
                    <div class="preview-device-selector">
                        <button class="preview-device-btn active" data-device="desktop">Desktop</button>
                        <button class="preview-device-btn" data-device="tablet">Tablet</button>
                        <button class="preview-device-btn" data-device="mobile">Mobile</button>
                    </div>
                    <div class="enhanced-preview-content">
                        <div class="enhanced-preview-close">
                            <i class="fa-solid fa-times"></i>
                        </div>
                        <div class="preview-content-wrapper">
                            ${content}
                        </div>
                    </div>
                </div>
            `);

            $('body').append(modal);
            $('body').addClass('preview-desktop');

            // Bind close events
            modal.find('.enhanced-preview-close').on('click', function() {
                modal.remove();
                $('body').removeClass('preview-mobile preview-tablet preview-desktop');
            });

            // Bind device selector events
            modal.find('.preview-device-btn').on('click', function() {
                const device = $(this).data('device');
                modal.find('.preview-device-btn').removeClass('active');
                $(this).addClass('active');
                $('body').removeClass('preview-mobile preview-tablet preview-desktop').addClass('preview-' + device);
            });

            // Close on escape key
            $(document).on('keydown.enhanced-preview', function(e) {
                if (e.keyCode === 27) { // Escape key
                    modal.remove();
                    $('body').removeClass('preview-mobile preview-tablet preview-desktop');
                    $(document).off('keydown.enhanced-preview');
                }
            });

            // Close on backdrop click
            modal.on('click', function(e) {
                if (e.target === this) {
                    modal.remove();
                    $('body').removeClass('preview-mobile preview-tablet preview-desktop');
                    $(document).off('keydown.enhanced-preview');
                }
            });
        },

        // Bind events for real-time updates
        bindEvents: function() {
            // TinyMCE editor updates for text popups
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('popup_type_value')) {
                tinyMCE.get('popup_type_value').on('change', function() {
                    tinyMCE.get('popup_type_value').save();
                });
            }

            // HTML editor updates
            if (typeof ace !== 'undefined') {
                $(document).on('ace-editor-ready', function() {
                    const editor = ace.edit("editor");
                    editor.getSession().on('change', function() {
                        const htmlCode = editor.getValue();
                        $('#popup_type_value').val(htmlCode);
                    });
                });
            }

            // Image / background updates (Media Library sets #background_image_url)
            $(document).on('change', '#background_image_url, #background_image, #popup_image', function() {
                setTimeout(function() {
                    const imageUrl = $('#popu_image_url').val() || $('#popup_image_url').val() || $('#background_image_url').val();
                    if (imageUrl) {
                        $('.preview-content-wrapper img').attr('src', imageUrl);
                    }
                }, 1000);
            });
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        EnhancedPreview.init();

        // Dashboard list: Preview uses saved row data + same overlay as edit-screen enhanced preview (not legacy inline modal).
        $(document).on('click', '.instant_popup .popup_lists a.prev_btn', function(e) {
            var ptype = ($(this).attr('data-popup-type') || '').toLowerCase();
            if (!ptype || $.inArray(ptype, ['text', 'image', 'html', 'subscription']) === -1) {
                return;
            }
            e.preventDefault();
            e.stopImmediatePropagation();
            var $a = $(this);
            var href = $a.attr('href') || '';
            var m = href.match(/#popup_preview_(\d+)/);
            var popupId = m ? m[1] : ($a.attr('data-popup-id') || '');
            if (!popupId || typeof instant_popup_admin === 'undefined' || !instant_popup_admin.ajaxurl) {
                return;
            }
            $.ajax({
                url: instant_popup_admin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'ipb_dashboard_popup_preview',
                    popup_id: popupId,
                    nonce: instant_popup_admin.enhanced_preview_nonce
                }
            }).done(function(res) {
                if (!res || !res.success || !res.data) {
                    return;
                }
                if (res.data.fallback_modal && res.data.modal_id) {
                    var $el = $('#' + res.data.modal_id);
                    if ($el.length && typeof $el.modal === 'function') {
                        $el.modal();
                    }
                    return;
                }
                if (res.data.preview_content && window.EnhancedPreview && typeof EnhancedPreview.displayPreviewModal === 'function') {
                    EnhancedPreview.displayPreviewModal(res.data.preview_content, res.data.popup_type || 'popup_text');
                }
            });
        });
    });

    // Make EnhancedPreview globally available
    window.EnhancedPreview = EnhancedPreview;

})(jQuery);
