"use strict";

(function ($) {
    
    /**
     * Popup Service - Handles server-side popup fetching
     */
    class LinkWhisperPopupService {
        constructor() {
            // No client-side cache needed
        }

        async fetchPopups(pageSlug) {
            try {
                const response = await new Promise((resolve, reject) => {
                    $.ajax({
                        type: 'POST',
                        url: window.wpil_ajax.ajax_url,
                        data: {
                            action: 'wpil_load_popups',
                            nonce: window.wpil_ajax.popup_nonce,
                            page_slug: pageSlug
                        },
                        success: function(response) {
                            resolve(response);
                        },
                        error: function(xhr, status, error) {
                            reject(new Error(`AJAX error: ${status} - ${error}`));
                        }
                    });
                });

                if (!response.success) {
                    throw new Error(response.data || 'Failed to fetch popups');
                }

                return response.data;

            } catch (error) {
                console.error('LinkWhisper Popups: Failed to fetch popups', error);
                return { popups: [] };
            }
        }

        async dismissPopup(popupId) {
            try {
                const response = await new Promise((resolve, reject) => {
                    $.ajax({
                        type: 'POST',
                        url: window.wpil_ajax.ajax_url,
                        data: {
                            action: 'wpil_dismiss_popup',
                            nonce: window.wpil_ajax.dismiss_popup_nonce,
                            popup_id: popupId
                        },
                        success: function(response) {
                            resolve(response);
                        },
                        error: function(xhr, status, error) {
                            reject(new Error(`AJAX error: ${status} - ${error}`));
                        }
                    });
                });

                if (!response.success) {
                    throw new Error(response.data || 'Failed to dismiss popup');
                }

                return true;

            } catch (error) {
                console.error('LinkWhisper Popups: Failed to dismiss popup', error);
                return false;
            }
        }
    }

    /**
     * Popup UI Manager - Handles rendering and user interactions
     */
    class LinkWhisperPopupUI {
        constructor(popupService) {
            this.popupService = popupService;
            this.currentPopup = null;
            this.autoDismissTimeout = null;
        }

        async initializePage(pageSlug) {
            const response = await this.popupService.fetchPopups(pageSlug);
            
            if (response.popups && response.popups.length > 0) {
                // Show the first (and only) popup for this page
                this.showPopup(response.popups[0]);
            }
        }

        showPopup(popup) {
            this.currentPopup = popup;

            // Remove any existing popup
            this.hidePopup();

            // Decode description if it has excessive escaping
            let descriptionHtml = popup.description || '';
            let scriptContent = '';

            if (descriptionHtml) {
                // Remove excessive backslash escaping - do this iteratively
                let prevLength = 0;
                while (descriptionHtml.length !== prevLength) {
                    prevLength = descriptionHtml.length;
                    descriptionHtml = descriptionHtml.replace(/\\\\/g, '\\')
                                                     .replace(/\\"/g, '"')
                                                     .replace(/\\'/g, "'");
                }

                // Extract script tags (they won't execute via innerHTML)
                const scriptMatch = descriptionHtml.match(/<script[^>]*>([\s\S]*?)<\/script>/i);
                if (scriptMatch) {
                    scriptContent = scriptMatch[1];
                    // Remove script tag from HTML (we'll execute it separately)
                    descriptionHtml = descriptionHtml.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
                }
            }

            // Log popup impression event
            if (window.wpilTelemetry) {
                window.wpilTelemetry.logPopupNotificationImpression(
                    popup.id,
                    popup.priority || null,
                    popup.display_frequency || null
                );
            }

            // Create popup overlay
            const overlay = document.createElement('div');
            overlay.id = 'linkwhisper-popup-overlay';
            overlay.className = 'linkwhisper-popup-overlay';

            // Create popup container
            const container = document.createElement('div');
            container.id = 'linkwhisper-popup-container';
            container.className = 'linkwhisper-popup-container';

            // Build popup HTML
            container.innerHTML = `
                <div class="popup-content">
                    ${popup.image ? `<div class="popup-image">
                        ${this.renderMedia(popup.image, popup.title)}
                    </div>` : ''}
                    <div class="popup-body">
                        <h3 class="popup-title">${this.escapeHtml(popup.title)}</h3>
                        <div class="popup-description">${descriptionHtml}</div>
                        <div class="popup-actions">
                            ${popup.action_url ? `<a href="${this.escapeHtml(popup.action_url)}" class="popup-action-button" data-action="navigate">${this.escapeHtml(popup.action_label ?? 'Check it out')}</a>` : ''}
                            <button class="popup-dismiss-button" data-action="dismiss">Dismiss</button>
                        </div>
                    </div>
                    <button class="popup-close" data-action="dismiss" aria-label="Close">×</button>
                </div>
            `;

            // Add event listeners
            container.addEventListener('click', (e) => {
                const action = e.target.dataset.action;

                // Handle video play button click
                if (e.target.closest('.popup-video-play-btn')) {
                    e.preventDefault();
                    e.stopPropagation();
                    const videoContainer = e.target.closest('.popup-video-container');
                    if (videoContainer) {
                        this.loadVideoEmbed(videoContainer);
                    }
                    return;
                }

                if (action === 'dismiss') {
                    // Log dismiss event
                    if (window.wpilTelemetry) {
                        window.wpilTelemetry.logPopupNotificationDismissed(
                            popup.id,
                            'user_action'
                        );
                    }
                    this.dismissPopup();
                } else if (action === 'navigate' && popup.action_url) {
                    // Log CTA click event
                    if (window.wpilTelemetry) {
                        window.wpilTelemetry.logPopupNotificationCtaClicked(
                            popup.id,
                            e.target.textContent || 'Open'
                        );
                    }
                    // Navigate to action URL and dismiss
                    window.location.href = popup.action_url;
                    this.dismissPopup();
                }
            });

            // Add escape key listener
            const escapeHandler = (e) => {
                if (e.key === 'Escape') {
                    // Log dismiss via escape key
                    if (window.wpilTelemetry) {
                        window.wpilTelemetry.logPopupNotificationDismissed(
                            popup.id,
                            'escape_key'
                        );
                    }
                    this.dismissPopup();
                    document.removeEventListener('keydown', escapeHandler);
                }
            };
            document.addEventListener('keydown', escapeHandler);

            // Prevent clicks on overlay from dismissing popup
            // Only clicking the dismiss/close buttons should dismiss
            overlay.addEventListener('click', (e) => {
                // Don't dismiss - popup should only close via dismiss button or X button
                if (e.target === overlay) {
                    // Could add shake animation here if desired // neat idea, maybe something to think about.
                }
            });

            // Append to page
            overlay.appendChild(container);
            document.body.appendChild(overlay);

            // Trigger show animation
            requestAnimationFrame(() => {
                overlay.classList.add('show');
            });

            // Execute script content if present (scripts in innerHTML don't auto-execute)
            if (scriptContent) {
                try {
                    // Use Function constructor instead of eval for better scoping
                    const scriptFunc = new Function(scriptContent);
                    scriptFunc();
                } catch (error) {
                    console.error('LinkWhisper Popup: Script execution error', error);
                }
            }

            // Set up auto-dismiss if specified
            if (popup.auto_dismiss_seconds && popup.auto_dismiss_seconds > 0) {
                this.autoDismissTimeout = setTimeout(() => {
                    // Log auto-dismiss event
                    if (window.wpilTelemetry) {
                        window.wpilTelemetry.logPopupNotificationAutoDismissed(
                            popup.id,
                            popup.auto_dismiss_seconds
                        );
                    }
                    this.dismissPopup();
                }, popup.auto_dismiss_seconds * 1000);
            }

            // Debug logging
            if (window.wpil_ajax && window.wpil_ajax.debug) {
                console.log('LinkWhisper Popup: Showing popup', popup);
            }
        }

        dismissPopup() {
            if (!this.currentPopup) return;

            const popupId = this.currentPopup.id;

            // Clear auto-dismiss timeout
            if (this.autoDismissTimeout) {
                clearTimeout(this.autoDismissTimeout);
                this.autoDismissTimeout = null;
            }

            // Remove the popup right away so the interface doesn't wait on the request.
            this.hidePopup();

            this.currentPopup = null;

            // Send dismiss request to server
            this.popupService.dismissPopup(popupId).then(() => {
                // Debug logging
                if (window.wpil_ajax && window.wpil_ajax.debug) {
                    console.log('LinkWhisper Popup: Popup dismissed');
                }
            });
        }

        hidePopup() {
            const overlay = document.getElementById('linkwhisper-popup-overlay');
            if (overlay) {
                overlay.classList.add('hide');
                setTimeout(() => {
                    overlay.remove();
                }, 300); // Match CSS transition duration
            }
        }

        extractYouTubeData(url) {
            if (!url) return null;

            let videoId = null;
            let urlObj = null;

            try {
                urlObj = new URL(url);
            } catch (e) {
                return null;
            }

            // youtube.com/watch?v=VIDEO_ID
            if (urlObj.hostname.includes('youtube.com') && urlObj.searchParams.has('v')) {
                videoId = urlObj.searchParams.get('v');
            }
            // youtu.be/VIDEO_ID
            else if (urlObj.hostname === 'youtu.be') {
                videoId = urlObj.pathname.slice(1).split('?')[0];
            }
            // youtube.com/embed/VIDEO_ID
            else if (urlObj.pathname.includes('/embed/')) {
                videoId = urlObj.pathname.split('/embed/')[1].split('?')[0];
            }

            // Validate video ID format (11 characters, alphanumeric, dash, underscore)
            if (!videoId || !/^[a-zA-Z0-9_-]{11}$/.test(videoId)) {
                return null;
            }

            // Extract timestamp parameter
            let params = '';
            const timestamp = urlObj.searchParams.get('t');
            if (timestamp) {
                const seconds = this.parseYouTubeTimestamp(timestamp);
                if (seconds > 0) {
                    params = `?start=${seconds}`;
                }
            }

            return { videoId, params };
        }

        parseYouTubeTimestamp(timestamp) {
            if (!timestamp) return 0;

            // Handle formats like "30s", "1m30s", "1h2m30s", or just "90" (seconds)
            let seconds = 0;

            const hours = timestamp.match(/(\d+)h/);
            const minutes = timestamp.match(/(\d+)m/);
            const secs = timestamp.match(/(\d+)s/);

            if (hours) seconds += parseInt(hours[1]) * 3600;
            if (minutes) seconds += parseInt(minutes[1]) * 60;
            if (secs) seconds += parseInt(secs[1]);

            // If no time units, assume it's seconds
            if (!hours && !minutes && !secs && /^\d+$/.test(timestamp)) {
                seconds = parseInt(timestamp);
            }

            return seconds;
        }

        loadVideoEmbed(container) {
            const videoId = container.dataset.videoId;
            const videoParams = container.dataset.videoParams || '';

            if (!videoId) return;

            // Build embed URL with youtube-nocookie for privacy
            const embedUrl = `https://www.youtube-nocookie.com/embed/${videoId}${videoParams}`;

            // Replace thumbnail with iframe
            container.innerHTML = `
                <iframe
                    class="popup-video"
                    src="${embedUrl}"
                    frameborder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                    allowfullscreen
                    loading="eager">
                </iframe>
            `;
        }

        renderMedia(url, title) {
            const videoData = this.extractYouTubeData(url);

            if (videoData) {
                // YouTube video - render thumbnail with play button (click-to-play)
                return `<div class="popup-video-container" data-video-id="${videoData.videoId}" data-video-params="${videoData.params}">
                    <img
                        src="https://img.youtube.com/vi/${videoData.videoId}/maxresdefault.jpg"
                        alt="${this.escapeHtml(title)}"
                        class="popup-video-thumbnail"
                        onerror="this.src='https://img.youtube.com/vi/${videoData.videoId}/hqdefault.jpg'"
                    >
                    <button class="popup-video-play-btn" aria-label="Play video">
                        <svg width="68" height="48" viewBox="0 0 68 48">
                            <path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55c-2.93.78-4.63 3.26-5.42 6.19C.06 13.05 0 24 0 24s.06 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C67.94 34.95 68 24 68 24s-.06-10.95-1.48-16.26z" fill="rgb(120, 102, 255)"></path>
                            <path d="M 45,24 27,14 27,34" fill="#fff"></path>
                        </svg>
                    </button>
                </div>`;
            } else {
                // Regular image
                return `<img src="${url}" alt="${this.escapeHtml(title)}" />`;
            }
        }

        escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    }

    // Initialize popups when document is ready
    $(document).ready(function() {
        // Only initialize on LinkWhisper admin pages
        if (!window.wpil_ajax || !window.wpil_ajax.current_page) return;

        // Create popup instances
        const popupService = new LinkWhisperPopupService();
        const popupUI = new LinkWhisperPopupUI(popupService);

        // Get current page
        const currentPage = window.wpil_ajax.current_page;

        // Initialize popups for current page
        popupUI.initializePage(currentPage);

        // Debug logging
        if (window.wpil_ajax.debug) {
            console.log('LinkWhisper Popups: Initialized for page:', currentPage);
        }
    });

})(jQuery);
