/**
 * PinnerPress Image Analytics Overlay Script
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/public
 * @since      1.1.0
 */

(function($) {
    'use strict';

    /**
     * Debug logging function that only logs when pinnerpressdebug=1 URL param is present
     * @param {...any} args - Arguments to log
     */
    function pinnerpressDebugLog() {
        // Check if debug URL parameter is present
        var urlParams = new URLSearchParams(window.location.search);
        var debugParam = urlParams.get('pinnerpress_debug');
        
        if (debugParam === '1') {
            console.log.apply(console, arguments);
        }
    }

    /**
     * Debug error function that only logs when pinnerpressdebug=1 URL param is present
     * @param {...any} args - Arguments to log
     */
    function pinnerpressDebugError() {
        // Check if debug URL parameter is present
        var urlParams = new URLSearchParams(window.location.search);
        var debugParam = urlParams.get('pinnerpress_debug');
        
        if (debugParam === '1') {
            console.error.apply(console, arguments);
        }
    }

    /**
     * Resolve the real image URL for lazy-loaded images.
     * @param {jQuery} $img - The image jQuery element
     * @returns {string} The resolved image URL
     */
    function resolveImageSrc($img) {
        var src = $img.attr('src') || '';
        if (src && !src.startsWith('data:') && src !== '' && src !== '#') {
            return src;
        }
        var lazyAttrs = [
            'data-lazy-src', 'data-src', 'data-original', 'data-full-src',
            'data-img-src', 'data-image', 'data-large', 'data-medium'
        ];
        for (var i = 0; i < lazyAttrs.length; i++) {
            var val = $img.attr(lazyAttrs[i]);
            if (val && !val.startsWith('data:') && val !== '' && val !== '#') {
                return val;
            }
        }
        var srcset = $img.attr('srcset') || $img.attr('data-srcset') || $img.attr('data-lazy-srcset');
        if (srcset) {
            var firstUrl = srcset.split(',')[0].trim().split(' ')[0];
            if (firstUrl && !firstUrl.startsWith('data:')) {
                return firstUrl;
            }
        }
        return src;
    }

    var PinnerPressImageAnalytics = window.PinnerPressImageAnalytics = {
        imageData: {},
        initialized: false,

        init: function() {
            if (this.initialized) return;
            this.initialized = true;

            pinnerpressDebugLog('PinnerPress Analytics: Initializing overlay');
            // Load analytics data
            this.loadAnalyticsData();

            // Listen for pin button clicks to refresh data
            this.listenForPinClicks();
        },

        listenForPinClicks: function() {
            var self = this;
            $(document).on('click', '.pinnerpress-pin-it-button', function() {
                // Wait a short moment for the click to be tracked
                setTimeout(function() {
                    pinnerpressDebugLog('PinnerPress Analytics: Refreshing data after pin click');
                    self.loadAnalyticsData();
                }, 500);
            });
        },

        loadAnalyticsData: function() {
            var self = this;

            pinnerpressDebugLog('PinnerPress Analytics: Loading data for post ID', pinnerpressAnalyticsOverlay.postId);

            // Show loading state on all images
            $('.pinnerpress-analytics-image-wrapper').each(function() {
                var $wrapper = $(this);
                $wrapper.find('.pinnerpress-analytics-badge, .pinnerpress-analytics-details, .pinnerpress-analytics-no-data').remove();
                self.addLoadingIndicator($wrapper);
            });

            $.ajax({
                url: pinnerpressAnalyticsOverlay.ajaxurl,
                type: 'POST',
                data: {
                    action: 'pinnerpress_get_post_images_analytics',
                    nonce: pinnerpressAnalyticsOverlay.nonce,
                    post_id: pinnerpressAnalyticsOverlay.postId,
                    start_date: this.getDateString(30), // Last 30 days
                    end_date: this.getDateString(0)
                },
                success: function(response) {
                    pinnerpressDebugLog('PinnerPress Analytics: AJAX response', response);
                    if (response.success && response.data) {
                        self.processAnalyticsData(response.data);
                        pinnerpressDebugLog('PinnerPress Analytics: Data refreshed successfully');
                    } else {
                        pinnerpressDebugError('Failed to load analytics data', response);
                        // Show error state on all images
                        $('.pinnerpress-analytics-image-wrapper').each(function() {
                            var $wrapper = $(this);
                            $wrapper.find('.pinnerpress-analytics-loading').remove();
                            self.addErrorIndicator($wrapper);
                        });
                    }
                },
                error: function(xhr, status, error) {
                    pinnerpressDebugError('Error loading analytics data:', status, error);
                    pinnerpressDebugError('Response:', xhr.responseText);
                    // Show error state on all images
                    $('.pinnerpress-analytics-image-wrapper').each(function() {
                        var $wrapper = $(this);
                        $wrapper.find('.pinnerpress-analytics-loading').remove();
                        self.addErrorIndicator($wrapper);
                    });
                }
            });
        },

        getDateString: function(daysAgo) {
            var date = new Date();
            date.setDate(date.getDate() - daysAgo);
            // Add one day to end date to include today's data
            if (daysAgo === 0) {
                date.setDate(date.getDate() + 1);
            }
            return date.toISOString().split('T')[0];
        },

        processAnalyticsData: function(data) {
            var self = this;
            
            pinnerpressDebugLog('PinnerPress Analytics: Processing data', data);

            // Clear existing data
            this.imageData = {};

            // Store image data by URL for quick lookup
            if (data.images && data.images.length > 0) {
                data.images.forEach(function(imageData) {
                    // Store by both full URL and relative URL
                    var fullUrl = imageData.image_url;
                    var relativeUrl = self.getRelativeUrl(fullUrl);
                    
                    self.imageData[fullUrl] = imageData;
                    if (relativeUrl !== fullUrl) {
                        self.imageData[relativeUrl] = imageData;
                    }
                });
            }

            // Remove all existing analytics overlays
            $('.pinnerpress-analytics-badge, .pinnerpress-analytics-details, .pinnerpress-analytics-no-data, .pinnerpress-analytics-loading, .pinnerpress-analytics-error').remove();

            // Now process all images in the post
            this.processPostImages();
            
            pinnerpressDebugLog('PinnerPress Analytics: Finished processing data');
        },

        getRelativeUrl: function(url) {
            // Convert absolute URL to relative if it's from the same domain
            var siteUrl = pinnerpressAnalyticsOverlay.siteUrl || window.location.origin;
            if (url.indexOf(siteUrl) === 0) {
                return url.substring(siteUrl.length);
            }
            return url;
        },

        processPostImages: function() {
            var self = this;

            // Use the same comprehensive selector logic as pin buttons
            var $images = $();
            
            // Check if we're on a single post page
            var isSinglePost = $('body').hasClass('single-post') || $('body').hasClass('single');
            
            if (isSinglePost) {
                // Method 1: Find images in common content containers
                var contentSelectors = [
                    '.entry-content',
                    '.post-content', 
                    '.content-area',
                    '.site-content',
                    'article .inside-article',
                    '.wp-block-post-content',
                    'main'
                ];
                
                // Try each content selector until we find one with images
                for (var i = 0; i < contentSelectors.length; i++) {
                    var $contentArea = $(contentSelectors[i]);
                    if ($contentArea.length > 0) {
                        // Find all img tags within the content area
                        var $foundImages = $contentArea.find('img').filter(function() {
                            var $img = $(this);
                            var src = $img.attr('src') || '';
                            
                            // Resolve real URL for lazy-loaded images
                            var realSrc = src;
                            if (!realSrc || realSrc.startsWith('data:') || realSrc === '' || realSrc === '#') {
                                var lazyAttrs = ['data-lazy-src', 'data-src', 'data-original', 'data-full-src', 'data-img-src'];
                                for (var j = 0; j < lazyAttrs.length; j++) {
                                    var val = $img.attr(lazyAttrs[j]);
                                    if (val && !val.startsWith('data:') && val !== '' && val !== '#') {
                                        realSrc = val;
                                        break;
                                    }
                                }
                            }
                            
                            // Filter out non-content images
                            if ($img.closest('#wpadminbar').length > 0) return false;
                            if ($img.closest('.admin-bar-menu').length > 0) return false;
                            if ($img.hasClass('avatar') || $img.hasClass('gravatar')) return false;
                            if ($img.hasClass('emoji')) return false;
                            if (realSrc.includes('gravatar.com') || realSrc.includes('emoji')) return false;
                            if (realSrc.split('?')[0].split('#')[0].toLowerCase().endsWith('.svg')) return false;
                            if (realSrc.startsWith('data:')) return false;
                            
                            // Include images that are likely content images
                            // Check if it's in wp-content/uploads or has wp-image class or is in a figure tag
                            var isWpImage = $img.attr('class') && $img.attr('class').includes('wp-image-');
                            var isInUploads = realSrc.includes('/wp-content/uploads/');
                            var isInFigure = $img.closest('figure').length > 0;
                            var isInBlockImage = $img.closest('.wp-block-image, .gb-block-image').length > 0;
                            var isFromCdn = realSrc.includes('imagedelivery.net') || realSrc.includes('imgix.net') || realSrc.includes('cdn.shopify.com');
                            var hasLazySrc = $img.attr('data-lazy-src') && !$img.attr('data-lazy-src').startsWith('data:');
                            
                            // Include if any of these conditions are true
                            return isWpImage || isInUploads || isInFigure || isInBlockImage || isFromCdn || hasLazySrc;
                        });
                        
                        if ($foundImages.length > 0) {
                            $images = $images.add($foundImages);
                            pinnerpressDebugLog('Found ' + $foundImages.length + ' images in ' + contentSelectors[i]);
                        }
                    }
                }
            } else if ($('article').length > 0) {
                // Fallback for archive pages or other non-single pages with articles
                $images = $('article').find('img[class*="wp-image-"], figure img, .wp-block-image img');
            }
            
            // Remove duplicates
            var uniqueImages = [];
            $images.each(function() {
                if (uniqueImages.indexOf(this) === -1) {
                    uniqueImages.push(this);
                }
            });
            $images = $(uniqueImages);
            
            pinnerpressDebugLog('PinnerPress Analytics: Found ' + $images.length + ' images to process');

            $images.each(function() {
                var $img = $(this);
                
                // Skip if already processed - check for both wrapper types
                if ($img.closest('.pinnerpress-analytics-image-wrapper').length > 0 || 
                    $img.closest('.pinnerpress-pin-it-container').find('.pinnerpress-analytics-badge, .pinnerpress-analytics-no-data').length > 0) {
                    return;
                }

                // Check if this is a gallery image
                var isGalleryImage = $img.closest('.wp-block-gallery').length > 0;
                
                // Skip small images (likely icons) - use configurable minimum size
                var minimumSize = (typeof pinnerpress_data !== 'undefined' && pinnerpress_data.minimum_image_size) 
                    ? parseInt(pinnerpress_data.minimum_image_size) : 250;
                
                // Check if we should exclude gallery images from minimum size
                var excludeGalleryMinimum = (typeof pinnerpress_data !== 'undefined' && pinnerpress_data.exclude_gallery_minimum === '1');
                
                // If this is a gallery image and we're excluding them, set minimum size to 0
                if (isGalleryImage && excludeGalleryMinimum) {
                    pinnerpressDebugLog('PinnerPress Analytics: Gallery image detected, bypassing minimum size check');
                    minimumSize = 0;
                }
                    
                // Only bypass size check when the image is still a placeholder.
                // Once loaded, apply normal size filtering.
                var isLazyPlaceholder = false;
                var currentSrc = $img.attr('src') || '';
                if (currentSrc.startsWith('data:') || currentSrc === '' || currentSrc === '#') {
                    var hasLazyUrl = $img.attr('data-lazy-src') || $img.attr('data-src') || $img.attr('data-lazy-srcset');
                    if (hasLazyUrl) {
                        isLazyPlaceholder = true;
                    }
                }

                if (!isLazyPlaceholder) {
                    // Use getBoundingClientRect() for actual rendered size
                    var rect = $img[0].getBoundingClientRect();
                    var imgWidth = rect.width;
                    var imgHeight = rect.height;

                    if (imgWidth < minimumSize || imgHeight < minimumSize) {
                        pinnerpressDebugLog('PinnerPress Analytics: Skipping small image (' + imgWidth + 'x' + imgHeight + ', minimum: ' + minimumSize + ')', $img.attr('src'));
                        return;
                    }
                }

                var imageUrl = resolveImageSrc($img);
                if (!imageUrl || imageUrl.startsWith('data:')) return;

                pinnerpressDebugLog('PinnerPress Analytics: Processing image', imageUrl);

                // Look for analytics data
                var analyticsData = self.findImageAnalytics(imageUrl);
                
                // Wrap the image
                self.wrapImage($img, analyticsData);
            });
        },

        findImageAnalytics: function(imageUrl) {
            pinnerpressDebugLog('PinnerPress Analytics: Looking for analytics data for image:', imageUrl);
            pinnerpressDebugLog('PinnerPress Analytics: Available image data:', Object.keys(this.imageData));
            
            // Try exact match first
            if (this.imageData[imageUrl]) {
                pinnerpressDebugLog('PinnerPress Analytics: Found exact match');
                return this.imageData[imageUrl];
            }

            // Try relative URL
            var relativeUrl = this.getRelativeUrl(imageUrl);
            if (this.imageData[relativeUrl]) {
                pinnerpressDebugLog('PinnerPress Analytics: Found match with relative URL:', relativeUrl);
                return this.imageData[relativeUrl];
            }

            // Try to match by filename
            var filename = imageUrl.split('/').pop().split('?')[0];
            pinnerpressDebugLog('PinnerPress Analytics: Trying to match by filename:', filename);
            
            // Remove WordPress size suffix (e.g., -150x150) from filename
            var baseFilename = filename.replace(/-\d+x\d+(\.\w+)$/, '$1');
            pinnerpressDebugLog('PinnerPress Analytics: Base filename (without size):', baseFilename);
            
            for (var url in this.imageData) {
                var dataFilename = url.split('/').pop().split('?')[0];
                var dataBaseFilename = dataFilename.replace(/-\d+x\d+(\.\w+)$/, '$1');
                
                if (dataBaseFilename === baseFilename) {
                    pinnerpressDebugLog('PinnerPress Analytics: Found match by base filename:', url);
                    return this.imageData[url];
                }
            }

            pinnerpressDebugLog('PinnerPress Analytics: No analytics data found for image');
            return null;
        },

        wrapImage: function($img, analyticsData) {
            var self = this;
            var $wrapper;

            // Check if image is already in a pinnerpress container (like gallery images)
            var $existingContainer = $img.closest('.pinnerpress-pin-it-container');
            
            if ($existingContainer.length > 0) {
                // Use the existing container for analytics
                $wrapper = $existingContainer;
                pinnerpressDebugLog('PinnerPress Analytics: Using existing container for gallery image');
            } else {
                // Create new wrapper for regular images
                $wrapper = $('<div>', {
                    'class': 'pinnerpress-analytics-image-wrapper'
                });

                // Preserve any existing wrapper classes
                if ($img.parent().is('a')) {
                    $img.parent().wrap($wrapper);
                    $wrapper = $img.parent().parent();
                } else {
                    $img.wrap($wrapper);
                    $wrapper = $img.parent();
                }
            }

            // Add analytics overlay
            if (analyticsData && analyticsData.analytics && analyticsData.analytics.total_clicks > 0) {
                this.addAnalyticsBadge($wrapper, analyticsData.analytics);
            } else {
                // Show "no data" indicator
                this.addNoDataIndicator($wrapper);
            }
        },

        getAnalyticsBadgePosition: function() {
            var pinButtonPosition = pinnerpressAnalyticsOverlay.pinButtonPosition || 'top-left';
            
            // Position analytics badge in the opposite corner to avoid conflict
            switch (pinButtonPosition) {
                case 'top-left':
                    return 'top-right';
                case 'top-right':
                    return 'top-left';
                case 'bottom-left':
                    return 'top-right';
                case 'bottom-right':
                    return 'top-left';
                case 'center':
                    return 'top-right'; // Default to top-right when pin button is centered
                default:
                    return 'top-right';
            }
        },

        addAnalyticsBadge: function($wrapper, analytics) {
            var self = this;
            var totalClicks = analytics.total_clicks || 0;
            var pinClicks = analytics.pin_button_click || 0;
            var bannerClicks = analytics.image_banner_click || 0;
            var badgePosition = this.getAnalyticsBadgePosition();

            // Create badge with click handler and dynamic positioning
            var $badge = $('<div>', {
                'class': 'pinnerpress-analytics-badge ' + badgePosition,
                'text': totalClicks + ' ' + (totalClicks === 1 ? 'click' : 'clicks'),
                'data-analytics': JSON.stringify(analytics)
            });

            // Add click event to open modal
            $badge.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                self.openAnalyticsModal(analytics);
            });

            // Create details popup (keep existing hover functionality)
            var $details = $('<div>', {
                'class': 'pinnerpress-analytics-details'
            });

            var detailsHtml = '<h4>' + pinnerpressAnalyticsOverlay.i18n.totalClicks + '</h4>';
            
            if (pinClicks > 0) {
                detailsHtml += '<div class="pinnerpress-analytics-stat">' +
                    '<span class="pinnerpress-analytics-stat-label">' + pinnerpressAnalyticsOverlay.i18n.pinButton + ':</span>' +
                    '<span class="pinnerpress-analytics-stat-value">' + pinClicks + '</span>' +
                    '</div>';
            }
            
            if (bannerClicks > 0) {
                detailsHtml += '<div class="pinnerpress-analytics-stat">' +
                    '<span class="pinnerpress-analytics-stat-label">' + pinnerpressAnalyticsOverlay.i18n.imageBanner + ':</span>' +
                    '<span class="pinnerpress-analytics-stat-value">' + bannerClicks + '</span>' +
                    '</div>';
            }

            if (analytics.first_click) {
                var firstClickDate = new Date(analytics.first_click);
                var timeAgo = self.getTimeAgo(firstClickDate);
                detailsHtml += '<div class="pinnerpress-analytics-stat" style="margin-top: 10px; font-size: 11px; color: #999;">' +
                    'First clicked ' + timeAgo +
                    '</div>';
            }

            $details.html(detailsHtml);

            // Add to wrapper
            $wrapper.append($badge);
            $wrapper.append($details);
        },

        openAnalyticsModal: function(analytics) {
            var self = this;
            
            // Remove existing modal if present
            $('.pinnerpress-analytics-modal').remove();
            
            var totalClicks = analytics.total_clicks || 0;
            var pinClicks = analytics.pin_button_click || 0;
            var bannerClicks = analytics.image_banner_click || 0;
            
            // Create modal HTML
            var modalHtml = '<div class="pinnerpress-analytics-modal">' +
                '<div class="pinnerpress-analytics-modal-overlay"></div>' +
                '<div class="pinnerpress-analytics-modal-content">' +
                    '<div class="pinnerpress-analytics-modal-header">' +
                        '<h3>PinnerPress Image Analytics Details</h3>' +
                        '<button class="pinnerpress-analytics-modal-close">&times;</button>' +
                    '</div>' +
                    '<div class="pinnerpress-analytics-modal-body">' +
                        '<div class="pinnerpress-analytics-modal-stat-grid">' +
                            '<div class="pinnerpress-analytics-modal-stat-card total">' +
                                '<div class="stat-number">' + totalClicks + '</div>' +
                                '<div class="stat-label">Total Clicks</div>' +
                            '</div>' +
                            '<div class="pinnerpress-analytics-modal-stat-card pin">' +
                                '<div class="stat-number">' + pinClicks + '</div>' +
                                '<div class="stat-label">Pin It Clicks</div>' +
                                '<div class="stat-percentage">' + (totalClicks > 0 ? Math.round((pinClicks / totalClicks) * 100) : 0) + '%</div>' +
                            '</div>' +
                            '<div class="pinnerpress-analytics-modal-stat-card banner">' +
                                '<div class="stat-number">' + bannerClicks + '</div>' +
                                '<div class="stat-label">Banner Clicks</div>' +
                                '<div class="stat-percentage">' + (totalClicks > 0 ? Math.round((bannerClicks / totalClicks) * 100) : 0) + '%</div>' +
                            '</div>' +
                        '</div>';
            
            // Add timeline info if available
            if (analytics.first_click) {
                var firstClickDate = new Date(analytics.first_click);
                var timeAgo = self.getTimeAgo(firstClickDate);
                modalHtml += '<div class="pinnerpress-analytics-modal-timeline">' +
                    '<h4>Timeline</h4>' +
                    '<p>First clicked <strong>' + timeAgo + '</strong></p>' +
                    '<p>Date: ' + firstClickDate.toLocaleDateString() + '</p>' +
                    '</div>';
            }
            
            modalHtml += '</div>' +
                    '<div class="pinnerpress-analytics-modal-footer">' +
                        '<small>Analytics data for the last 30 days</small>' +
                    '</div>' +
                '</div>' +
            '</div>';
            
            // Add modal to page
            $('body').append(modalHtml);
            
            // Add event handlers
            $('.pinnerpress-analytics-modal-close').on('click', function() {
                self.closeAnalyticsModal();
            });
            
            // Handle overlay click by clicking on the modal container (not overlay div)
            $('.pinnerpress-analytics-modal').on('click', function(e) {
                if (e.target === this) {
                    self.closeAnalyticsModal();
                }
            });
            
            // Prevent modal content click from closing modal
            $('.pinnerpress-analytics-modal-content').on('click', function(e) {
                e.stopPropagation();
            });
            
            // Add ESC key handler
            $(document).on('keydown.pinnerpress-modal', function(e) {
                if (e.keyCode === 27) { // ESC key
                    self.closeAnalyticsModal();
                }
            });
            
            // Show modal with animation
            setTimeout(function() {
                $('.pinnerpress-analytics-modal').addClass('show');
            }, 10);
        },

        closeAnalyticsModal: function() {
            $('.pinnerpress-analytics-modal').removeClass('show');
            $(document).off('keydown.pinnerpress-modal');
            
            // Remove after animation
            setTimeout(function() {
                $('.pinnerpress-analytics-modal').remove();
            }, 300);
        },

        getTimeAgo: function(date) {
            var now = new Date();
            var diff = now - date;
            var seconds = Math.floor(diff / 1000);
            var minutes = Math.floor(seconds / 60);
            var hours = Math.floor(minutes / 60);
            var days = Math.floor(hours / 24);
            var months = Math.floor(days / 30);
            var years = Math.floor(days / 365);

            if (seconds < 60) {
                return 'just now';
            } else if (minutes < 60) {
                return minutes + ' minute' + (minutes === 1 ? '' : 's') + ' ago';
            } else if (hours < 24) {
                return hours + ' hour' + (hours === 1 ? '' : 's') + ' ago';
            } else if (days === 0) {
                return 'today';
            } else if (days === 1) {
                return 'yesterday';
            } else if (days < 30) {
                return days + ' day' + (days === 1 ? '' : 's') + ' ago';
            } else if (months < 12) {
                return months + ' month' + (months === 1 ? '' : 's') + ' ago';
            } else {
                return years + ' year' + (years === 1 ? '' : 's') + ' ago';
            }
        },

        addNoDataIndicator: function($wrapper) {
            var badgePosition = this.getAnalyticsBadgePosition();
            var $indicator = $('<div>', {
                'class': 'pinnerpress-analytics-no-data ' + badgePosition,
                'text': pinnerpressAnalyticsOverlay.i18n.noData
            });

            $wrapper.append($indicator);
        },

        addLoadingIndicator: function($wrapper) {
            var badgePosition = this.getAnalyticsBadgePosition();
            var $loading = $('<div>', {
                'class': 'pinnerpress-analytics-loading ' + badgePosition
            });

            $wrapper.append($loading);
        },

        addErrorIndicator: function($wrapper) {
            var badgePosition = this.getAnalyticsBadgePosition();
            var $error = $('<div>', {
                'class': 'pinnerpress-analytics-error ' + badgePosition,
                'text': pinnerpressAnalyticsOverlay.i18n.error
            });

            $wrapper.append($error);
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        // Check if body has the required single-post class
        if (!$('body').hasClass('single-post')) {
            pinnerpressDebugLog('PinnerPress Analytics: Analytics overlays only display on pages with single-post body class.');
            return;
        }
        
        // Only initialize if we're on a single post with analytics enabled
        if (typeof pinnerpressAnalyticsOverlay !== 'undefined' && pinnerpressAnalyticsOverlay.postId) {
            PinnerPressImageAnalytics.init();
        }
    });

})(jQuery); 