/**
 * Popup System
 * Displays customizable popups based on admin settings
 */

class PopupSystem {
    constructor() {
        this.popups = [];
        this.currentPopup = null;
        this.init();
    }

    async init() {
        // Load popups from server
        await this.loadPopups();
        
        // Check and display popups
        this.checkAndDisplayPopups();
    }

    async loadPopups() {
        try {
            const response = await fetch(SITEURL + '/get_popups.php');
            const data = await response.json();
            
            if (data.success) {
                this.popups = data.popups;
            }
        } catch (error) {
            // Silent error handling
        }
    }

    checkAndDisplayPopups() {
        if (this.popups.length === 0) {
            return;
        }

        // Sort by priority
        this.popups.sort((a, b) => b.popup_priority - a.popup_priority);

        // Find first popup that should be displayed
        for (const popup of this.popups) {
            if (this.shouldShowPopup(popup)) {
                this.displayPopup(popup);
                break; // Only show one popup at a time
            }
        }
    }

    shouldShowPopup(popup) {
        // Check if popup is enabled
        if (!popup.popup_enabled) {
            return false;
        }

        // Check device targeting
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
        const deviceType = isMobile ? 'mobile' : 'desktop';
        
        if (popup.popup_device && popup.popup_device !== 'both') {
            if (popup.popup_device !== deviceType) {
                return false;
            }
        }

        // Check date range
        const now = new Date();
        if (popup.popup_start_date && new Date(popup.popup_start_date) > now) {
            return false;
        }
        if (popup.popup_end_date && new Date(popup.popup_end_date) < now) {
            return false;
        }

        // Check page restriction
        if (popup.popup_show_on_pages !== 'all') {
            const currentPage = this.getCurrentPage();
            if (popup.popup_show_on_pages !== currentPage) {
                return false;
            }
        }

        // Check frequency
        const storageKey = `popup_${popup.popup_id}_shown`;
        const versionKey = `popup_${popup.popup_id}_version`;
        const lastShown = localStorage.getItem(storageKey);
        const currentVersion = popup.popup_updated_at || popup.popup_created_at;
        const storedVersion = localStorage.getItem(versionKey);

        // If version changed, clear cache
        if (storedVersion && storedVersion !== currentVersion) {
            localStorage.removeItem(storageKey);
            sessionStorage.removeItem(storageKey);
            localStorage.setItem(versionKey, currentVersion);
        }

        switch (popup.popup_frequency) {
            case 'once':
                if (lastShown) {
                    return false;
                }
                break;
            case 'daily':
                if (lastShown) {
                    const lastDate = new Date(parseInt(lastShown));
                    const today = new Date();
                    if (lastDate.toDateString() === today.toDateString()) {
                        return false;
                    }
                }
                break;
            case 'session':
                if (sessionStorage.getItem(storageKey)) {
                    return false;
                }
                break;
            case 'always':
                break;
        }

        return true;
    }

    getCurrentPage() {
        const path = window.location.pathname;
        if (path === '/' || path.includes('index.php')) return 'home';
        if (path.includes('stores')) return 'stores';
        if (path.includes('coupons')) return 'coupons';
        if (path.includes('single')) return 'single';
        return 'other';
    }

    displayPopup(popup) {
        this.currentPopup = popup;

        // Create popup HTML
        const popupHTML = this.createPopupHTML(popup);
        
        // Add to page
        document.body.insertAdjacentHTML('beforeend', popupHTML);

        // Get popup element
        const popupEl = document.getElementById(`popup-${popup.popup_id}`);
        
        if (!popupEl) return;

        // For footer type, use slide-in animation from left
        if (popup.popup_type === 'footer') {
            // Small delay to ensure DOM is ready
            setTimeout(() => {
                popupEl.classList.add('show');
                this.trackView(popup.popup_id);
                this.markAsShown(popup);
            }, 100);
        } else {
            // Show after configured delay for other types
            setTimeout(() => {
                popupEl.classList.add('show');
                this.trackView(popup.popup_id);
                this.markAsShown(popup);
            }, parseInt(popup.popup_delay) || 0);
        }

        // Setup event listeners
        this.setupEventListeners(popup);
    }

    createPopupHTML(popup) {
        const positionClass = `popup-${popup.popup_position}`;
        const typeClass = popup.popup_type === 'footer' ? 'popup-footer-type' : '';
        const imageHTML = popup.popup_image ? 
            `<div class="popup-image"><img src="${IMAGES_FOLDER}/${popup.popup_image}" alt="${popup.popup_title}"></div>` : '';
        
        // For footer type popups, don't show overlay
        const showOverlay = popup.popup_type !== 'footer';
        
        // Newsletter popup gets special form
        const isNewsletter = popup.popup_type === 'newsletter';
        
        let contentHTML = '';
        
        if (isNewsletter) {
            contentHTML = `
                <div class="popup-newsletter-container">
                    <div class="popup-newsletter-left">
                        <div class="popup-newsletter-icon">📧</div>
                        <h2>Join Our Newsletter</h2>
                        <p>Get exclusive deals, coupons, and updates delivered straight to your inbox.</p>
                        <div class="popup-newsletter-benefits">
                            <div class="popup-newsletter-benefit">Exclusive discount codes</div>
                            <div class="popup-newsletter-benefit">Early access to sales</div>
                            <div class="popup-newsletter-benefit">Weekly deal roundups</div>
                        </div>
                    </div>
                    <div class="popup-newsletter-right">
                        <div class="popup-newsletter-content">
                            ${popup.popup_content}
                        </div>
                        <form class="popup-newsletter-form" id="newsletter-form-${popup.popup_id}" onsubmit="return false;">
                            <div class="popup-newsletter-input-group">
                                <input type="email" 
                                       id="newsletter-email-${popup.popup_id}"
                                       class="popup-newsletter-input" 
                                       placeholder="Enter your email address" 
                                       required>
                                <span class="popup-newsletter-input-icon">✉</span>
                            </div>
                            <button type="submit" 
                                    class="popup-newsletter-button"
                                    onclick="window.popupSystem.subscribeNewsletter(${popup.popup_id})">
                                Subscribe Now
                            </button>
                            <div class="popup-newsletter-privacy">
                                By subscribing, you agree to our <a href="#">Privacy Policy</a>
                            </div>
                        </form>
                        <div class="popup-newsletter-error" id="newsletter-error-${popup.popup_id}" style="display: none;"></div>
                    </div>
                    <div class="popup-newsletter-success" id="newsletter-success-${popup.popup_id}" style="display: none;">
                        <div class="success-icon">✓</div>
                        <h3>Successfully Subscribed!</h3>
                        <p>Thank you for joining our newsletter. Check your email for a special welcome offer!</p>
                        <div class="popup-newsletter-success-features">
                            <div class="popup-newsletter-success-feature">
                                <div class="popup-newsletter-success-feature-icon">🎁</div>
                                <div class="popup-newsletter-success-feature-text">Welcome Gift</div>
                            </div>
                            <div class="popup-newsletter-success-feature">
                                <div class="popup-newsletter-success-feature-icon">💰</div>
                                <div class="popup-newsletter-success-feature-text">Exclusive Deals</div>
                            </div>
                            <div class="popup-newsletter-success-feature">
                                <div class="popup-newsletter-success-feature-icon">⚡</div>
                                <div class="popup-newsletter-success-feature-text">Early Access</div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        } else {
            contentHTML = `
                <div class="popup-body">
                    ${popup.popup_content}
                </div>
                ${popup.popup_button_text ? `
                    <div class="popup-footer">
                        <a href="${popup.popup_button_link || '#'}" 
                           class="popup-button" 
                           data-popup-id="${popup.popup_id}">
                            ${popup.popup_button_text}
                        </a>
                    </div>
                ` : ''}
            `;
        }
        
        return `
            <div id="popup-${popup.popup_id}" class="custom-popup ${positionClass} ${typeClass}" style="max-width: ${popup.popup_width}">
                ${showOverlay ? '<div class="popup-overlay"></div>' : ''}
                <div class="popup-content">
                    <button class="popup-close" data-popup-id="${popup.popup_id}" title="Close">
                        <span>&times;</span>
                    </button>
                    ${imageHTML}
                    ${contentHTML}
                </div>
            </div>
        `;
    }

    setupEventListeners(popup) {
        const popupEl = document.getElementById(`popup-${popup.popup_id}`);
        if (!popupEl) return;

        // Close button
        const closeBtn = popupEl.querySelector('.popup-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.closePopup(popup.popup_id));
        }

        // Overlay click
        const overlay = popupEl.querySelector('.popup-overlay');
        if (overlay) {
            overlay.addEventListener('click', () => this.closePopup(popup.popup_id));
        }

        // Button click
        const button = popupEl.querySelector('.popup-button');
        if (button) {
            button.addEventListener('click', () => {
                this.trackClick(popup.popup_id);
                this.closePopup(popup.popup_id);
            });
        }

        // ESC key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closePopup(popup.popup_id);
            }
        });
    }

    closePopup(popupId) {
        const popupEl = document.getElementById(`popup-${popupId}`);
        if (popupEl) {
            popupEl.classList.remove('show');
            
            // Wait for animation to complete before removing
            setTimeout(() => {
                popupEl.remove();
            }, 500); // Match CSS transition duration
        }
    }

    markAsShown(popup) {
        const storageKey = `popup_${popup.popup_id}_shown`;
        const versionKey = `popup_${popup.popup_id}_version`;
        const now = Date.now();
        const currentVersion = popup.popup_updated_at || popup.popup_created_at;

        // Check if popup was updated - if so, clear old cache
        const storedVersion = localStorage.getItem(versionKey);
        if (storedVersion !== currentVersion) {
            // Popup was updated, clear old cache
            localStorage.removeItem(storageKey);
            sessionStorage.removeItem(storageKey);
            localStorage.setItem(versionKey, currentVersion);
        }

        if (popup.popup_frequency === 'session') {
            sessionStorage.setItem(storageKey, now);
        } else {
            localStorage.setItem(storageKey, now);
        }
    }

    async trackView(popupId) {
        try {
            await fetch(SITEURL + '/track_popup.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ popup_id: popupId, action: 'view' })
            });
        } catch (error) {
            // Silent error handling
        }
    }

    async trackClick(popupId) {
        try {
            await fetch(SITEURL + '/track_popup.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ popup_id: popupId, action: 'click' })
            });
        } catch (error) {
            // Silent error handling
        }
    }

    async subscribeNewsletter(popupId) {
        const emailInput = document.getElementById(`newsletter-email-${popupId}`);
        const form = document.getElementById(`newsletter-form-${popupId}`);
        const successDiv = document.getElementById(`newsletter-success-${popupId}`);
        const errorDiv = document.getElementById(`newsletter-error-${popupId}`);
        
        if (!emailInput || !emailInput.value) {
            this.showNewsletterError(popupId, 'Please enter your email address');
            return false;
        }
        
        const email = emailInput.value.trim();
        
        // Validate email
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            this.showNewsletterError(popupId, 'Please enter a valid email address');
            return false;
        }
        
        // Show loading state
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = 'Subscribing...';
        submitBtn.disabled = true;
        
        try {
            const response = await fetch(SITEURL + '/subscribe_newsletter.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email: email })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Hide form, left panel, and error
                form.style.display = 'none';
                errorDiv.style.display = 'none';
                
                const leftPanel = document.querySelector(`#popup-${popupId} .popup-newsletter-left`);
                const rightPanel = document.querySelector(`#popup-${popupId} .popup-newsletter-right`);
                
                if (leftPanel) leftPanel.style.display = 'none';
                if (rightPanel) rightPanel.style.display = 'none';
                
                // Show success message
                successDiv.style.display = 'block';
                
                // Track as click
                this.trackClick(popupId);
                
                // Auto close after 4 seconds
                setTimeout(() => {
                    this.closePopup(popupId);
                }, 4000);
            } else {
                this.showNewsletterError(popupId, data.message || 'Subscription failed. Please try again.');
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }
        } catch (error) {
            this.showNewsletterError(popupId, 'An error occurred. Please try again later.');
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
        }
        
        return false;
    }
    
    showNewsletterError(popupId, message) {
        const errorDiv = document.getElementById(`newsletter-error-${popupId}`);
        if (errorDiv) {
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            
            // Hide after 5 seconds
            setTimeout(() => {
                errorDiv.style.display = 'none';
            }, 5000);
        }
    }
}

// Initialize popup system when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.popupSystem = new PopupSystem();
});
