/**
 * PinnerPress Pinterest JavaScript (pinit.js) implementation
 * 
 * Initializes Pinterest buttons using pinit.js as described in Pinterest documentation
 */
(function($) {
    'use strict';
    
    /**
     * Debug logging function that only logs when debug is enabled AND 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 (typeof pinnerpress_data !== 'undefined' && pinnerpress_data.debug_enabled && debugParam === '1') {
            console.log.apply(console, arguments);
        }
    }
    
    /**
     * Track analytics event
     * @param {string} eventType - The type of event to track
     * @param {object} eventData - Additional data for the event
     */
    function pinnerpressTrackEvent(eventType, eventData) {
        // Check if analytics is enabled
        if (typeof pinnerpress_data === 'undefined' || pinnerpress_data.analytics_enabled !== '1') {
            return;
        }

        // Prepare data for AJAX request
        var data = {
            action: 'pinnerpress_track_event',
            nonce: pinnerpress_data.analytics_nonce,
            event_type: eventType,
            event_data: eventData || {},
            post_id: pinnerpress_data.post_id
        };

        // Send AJAX request
        $.post(pinnerpress_data.ajaxurl, data, function(response) {
            if (response.success) {
                pinnerpressDebugLog('PinnerPress Analytics: Event tracked successfully', eventType, eventData);
            } else {
                pinnerpressDebugLog('PinnerPress Analytics: Failed to track event', response);
            }
        }).fail(function() {
            pinnerpressDebugLog('PinnerPress Analytics: AJAX request failed');
        });
    }
    
    // Make the tracking function available globally for external use
    window.pinnerpressTrackEvent = pinnerpressTrackEvent;
    
    // Initialize when DOM is ready
    $(document).ready(function() {
        initializePinitJs();
    });
    
    // Also listen for Pinterest events in case pinit.js is loaded by another script
    $(window).on('load', function() {
        if (typeof window.PinUtils !== 'undefined') {
            pinnerpressDebugLog('PinnerPress: Detected Pinterest PinUtils already loaded, initializing with existing script');
            addCustomPinButtons();
        }
    });
    
    /**
     * Initialize Pinterest's pinit.js functionality
     */
    function initializePinitJs() {
        // First check if Pin Button is enabled in the settings
        if (typeof pinnerpress_data !== 'undefined' && pinnerpress_data.pin_button_status === 'off') {
            pinnerpressDebugLog('PinnerPress: Pin Button is disabled in settings.');
            return;
        }
        
        // Check if we need to load pinit.js
        if (typeof window.PinUtils === 'undefined') {
            pinnerpressDebugLog('PinnerPress: Loading Pinterest pinit.js');
            loadPinitJs();
        } else {
            pinnerpressDebugLog('PinnerPress: Pinterest pinit.js already loaded');
            // If already loaded, call the build function
            if (window.PinUtils && typeof window.PinUtils.build === 'function') {
                window.PinUtils.build();
            }
        }
        
        // Add Pin buttons to content images
        addCustomPinButtons();
    }
    
    /**
     * Load Pinterest's pinit.js script
     */
    function loadPinitJs() {
        // Create script element
        var script = document.createElement('script');
        script.async = true;
        script.defer = true;
        script.src = '//assets.pinterest.com/js/pinit.js';
        script.setAttribute('data-pin-build', 'deferFirstButton');
        
        // Add script to document
        document.body.appendChild(script);
    }
    
    /**
     * Add custom Pinterest Pin It buttons to all eligible images
     */
    function addCustomPinButtons() {
        // Check if body has the required single-post class
        if (!$('body').hasClass('single-post')) {
            pinnerpressDebugLog('PinnerPress: Pin Buttons only display on pages with single-post body class.');
            return;
        }

        var $images;

        // Check if custom selectors are enabled
        if (typeof pinnerpress_data !== 'undefined' && pinnerpress_data.pin_button_custom_selectors_enabled === '1') {
            var customSelectors = pinnerpress_data.pin_button_custom_selectors;

            if (customSelectors && customSelectors.trim() !== '') {
                // Split selectors by newline and clean them
                var selectors = customSelectors.split('\n').map(function(s) {
                    return s.trim();
                }).filter(function(s) {
                    return s !== '';
                });

                if (selectors.length > 0) {
                    if (pinnerpress_data.pin_button_find_images_in_selectors === '1') {
                        // Find all images inside the specified selectors
                        $images = $();
                        selectors.forEach(function(selector) {
                            try {
                                $images = $images.add($(selector).find('img'));
                            } catch (e) {
                                pinnerpressDebugLog('PinnerPress: Invalid selector:', selector, e);
                            }
                        });
                    } else {
                        // Use selectors directly (they should point to images)
                        var combinedSelector = selectors.join(', ');
                        try {
                            $images = $(combinedSelector);
                        } catch (e) {
                            pinnerpressDebugLog('PinnerPress: Invalid custom selectors:', e);
                            $images = $();
                        }
                    }

                    pinnerpressDebugLog('PinnerPress: Using custom selectors, found', $images.length, 'images');
                } else {
                    pinnerpressDebugLog('PinnerPress: Custom selectors enabled but no valid selectors provided');
                    $images = $();
                }
            } else {
                pinnerpressDebugLog('PinnerPress: Custom selectors enabled but empty');
                $images = $();
            }
        } else {
            // Default behavior: Block editor images in single post - use multiple selectors for theme compatibility
            $images = $('.entry-content .wp-block-image img[class*="wp-image"], .post-content .wp-block-image img[class*="wp-image"], article .wp-block-image img[class*="wp-image"], .site-main .wp-block-image img[class*="wp-image"], main article .wp-block-image img[class*="wp-image"], .content .wp-block-image img[class*="wp-image"], .hentry .wp-block-image img[class*="wp-image"]');
        }

        $images.each(function() {
            var $img = $(this);

            // Skip images that already have pin buttons or are too small
            if ($img.closest('.pinnerpress-pin-it-container').length || $img.hasClass('pinnerpress-no-pin')) {
                return;
            }

            // Check if pinning is disabled for this image via data attribute
            if ($img.attr('data-pin-nopin') === 'true') {
                return;
            }

            // Skip images inside <aside> elements (sidebars, widgets, etc.)
            if ($img.closest('aside').length || $img.closest('[role="complementary"]').length) {
                return;
            }

            // Skip images inside widgets and sidebar areas
            if ($img.closest('.widget').length || $img.closest('.sidebar').length || $img.closest('[class*="sidebar"]').length) {
                return;
            }

			// Skip admin bar, navigation, avatar, and other non-content images
			// Check for specific non-content areas (more restrictive)
			if ($img.closest('#wpadminbar').length ||
				$img.closest('.admin-bar-menu').length ||
				$img.hasClass('avatar') ||
				$img.hasClass('gravatar') ||
				$img.hasClass('emoji') ||
				($img.attr('src') && ($img.attr('src').includes('gravatar.com') || $img.attr('src').includes('emoji')))) {
				return;
			}
            
            // Get image URL, page URL and description
            var imgUrl = $img.attr('src');
            var pageUrl = window.location.href;
            var description = '';
            var title = '';
            
            // Use a priority order for description
            // 1. Custom Pinterest description from block editor has highest priority
            if ($img.attr('data-pin-description')) {
                description = $img.attr('data-pin-description');
                pinnerpressDebugLog('PinnerPress: Using custom Pinterest description:', description);
            }
            // 2. If no custom Pinterest description, fall back to standard attributes
            else if ($img.attr('alt')) {
                description = $img.attr('alt');
            } else if ($img.attr('title')) {
                description = $img.attr('title');
            } else {
                description = document.title;
            }
            
            // Check for custom Pinterest title
            if ($img.attr('data-pin-title')) {
                title = $img.attr('data-pin-title');
                pinnerpressDebugLog('PinnerPress: Using custom Pinterest title:', title);
            }
            
            // Create a container for the image
            var $container = $('<div class="pinnerpress-pin-it-container"></div>');
            $container.css({
                'position': 'relative',
                'display': 'inline-block',
                'max-width': '100%',
                'font-size': '0' // Eliminate whitespace
            });
            
            // Move the image into the container
            $img.wrap($container);

            // Create the pin button using pinit.js approach
            createPinitButton($img.parent(), imgUrl, pageUrl, description, title);
        });

        // Handle image banners separately if custom selectors are enabled for banners
        if (typeof pinnerpress_data !== 'undefined' && pinnerpress_data.banner_status === 'on') {
            var $bannerImages;

            // Check if banner custom selectors are enabled
            if (pinnerpress_data.banner_custom_selectors_enabled === '1') {
                var bannerCustomSelectors = pinnerpress_data.banner_custom_selectors;

                if (bannerCustomSelectors && bannerCustomSelectors.trim() !== '') {
                    // Split selectors by newline and clean them
                    var bannerSelectors = bannerCustomSelectors.split('\n').map(function(s) {
                        return s.trim();
                    }).filter(function(s) {
                        return s !== '';
                    });

                    if (bannerSelectors.length > 0) {
                        if (pinnerpress_data.banner_find_images_in_selectors === '1') {
                            // Find all images inside the specified selectors
                            $bannerImages = $();
                            bannerSelectors.forEach(function(selector) {
                                try {
                                    $bannerImages = $bannerImages.add($(selector).find('img'));
                                } catch (e) {
                                    pinnerpressDebugLog('PinnerPress: Invalid banner selector:', selector, e);
                                }
                            });
                        } else {
                            // Use selectors directly (they should point to images)
                            var combinedBannerSelector = bannerSelectors.join(', ');
                            try {
                                $bannerImages = $(combinedBannerSelector);
                            } catch (e) {
                                pinnerpressDebugLog('PinnerPress: Invalid banner custom selectors:', e);
                                $bannerImages = $();
                            }
                        }

                        pinnerpressDebugLog('PinnerPress: Using custom selectors for banners, found', $bannerImages.length, 'images');
                    } else {
                        $bannerImages = $();
                    }
                } else {
                    $bannerImages = $();
                }
            } else {
                // Use the same images as pin buttons (already processed)
                $bannerImages = $images;
            }

            // Add banners to the selected images
            $bannerImages.each(function() {
                var $img = $(this);
                var $container = $img.closest('.pinnerpress-pin-it-container');

                // If image is not in a container yet, create one
                if ($container.length === 0) {
                    $container = $('<div class="pinnerpress-pin-it-container"></div>');
                    $container.css({
                        'position': 'relative',
                        'display': 'inline-block',
                        'max-width': '100%',
                        'font-size': '0'
                    });
                    $img.wrap($container);
                    $container = $img.parent();
                }

                // Get image data
                var imgUrl = $img.attr('src');
                var pageUrl = window.location.href;
                var description = $img.attr('data-pin-description') || $img.attr('alt') || $img.attr('title') || document.title;
                var title = $img.attr('data-pin-title') || '';

                // Create banner
                createImageBanner($container, imgUrl, pageUrl, description, title);
            });
        }
    }
    
    /**
     * Create a Pinterest Pin It button using pinit.js approach
     * @param {jQuery} $container - The container element to append the button to
     * @param {string} imgUrl - The URL of the image
     * @param {string} pageUrl - The URL of the current page
     * @param {string} description - The description to use for the pin
     * @param {string} title - The title to use for the pin (optional)
     */
    function createPinitButton($container, imgUrl, pageUrl, description, title) {
        // Get button settings from localized data (if available) or use defaults
        var position = 'top-right'; // Default position
        var shape = 'rectangular'; // Default shape
        var size = 'medium'; // Default size
        var color = '#E60023'; // Default Pinterest red
        var textColor = '#FFFFFF'; // Default white text
        var showText = true; // Default to showing text
        var buttonText = 'Pin It'; // Default text
        var imageShadow = false; // Default - no shadow
        
        // If we have localized data from WordPress, use those settings
        if (typeof pinnerpress_data !== 'undefined') {
            position = pinnerpress_data.position || position;
            shape = pinnerpress_data.shape || shape;
            size = pinnerpress_data.size || size;
            color = pinnerpress_data.color || color;
            textColor = pinnerpress_data.text_color || textColor;
            showText = pinnerpress_data.button_style === 'default';
            buttonText = pinnerpress_data.custom_button_text || buttonText;
            imageShadow = pinnerpress_data.image_shadow === '1'; // Convert to boolean
        }
        
        // Determine size-related styles
        var iconSize, fontSize, padding, verticalAlign;
        switch(size) {
            case 'small':
                iconSize = '0.85em';
                fontSize = '12px';
                padding = '6px 10px';
                verticalAlign = '-0.1em'; // Adjusted for small button size
                break;
            case 'large':
                iconSize = '1.2em';
                fontSize = '16px';
                padding = '10px 15px';
                verticalAlign = '-0.15em'; // Slightly adjusted for large buttons
                break;
            default: // medium
                iconSize = '1em';
                fontSize = '14px';
                padding = '8px 12px';
                verticalAlign = '-0.125em'; // Default alignment
        }
        
        // Determine border-radius based on shape
        var borderRadius = shape === 'round' ? '20px' : '3px';
        
        // Create button wrapper with positioning
        var $wrapper = $('<div class="pinnerpress-pin-it-button-wrapper"></div>');
        $wrapper.css({
            'position': 'absolute',
            'z-index': '10'
        });
        
        // Set position
        var offset = '10px';
        switch(position) {
            case 'top-left':
                $wrapper.css({
                    'top': offset,
                    'left': offset
                });
                break;
            case 'top-right':
                $wrapper.css({
                    'top': offset,
                    'right': offset
                });
                break;
            case 'center':
                $wrapper.css({
                    'top': '50%',
                    'left': '50%',
                    'transform': 'translate(-50%, -50%)'
                });
                break;
            case 'bottom-left':
                $wrapper.css({
                    'bottom': offset,
                    'left': offset
                });
                break;
            case 'bottom-right':
                $wrapper.css({
                    'bottom': offset,
                    'right': offset
                });
                break;
        }
        
        // Create the button itself - with pinit.js attributes
        var $button = $('<a class="pinnerpress-pin-it-button" data-pinnerpress-button="true"></a>');
        
        // Set Pinterest pinit.js attributes
        $button.attr({
            'href': '#', // Will be overridden by pinit.js
            'data-pin-do': 'buttonPin',
            'data-pin-custom': 'true',
            'data-pin-media': imgUrl,
            'data-pin-url': pageUrl,
            'data-pin-description': description
        });
        
        // Add title parameter if available
        if (title) {
            $button.attr('data-pin-title', title);
        }
        
        // Check for repin ID
        var repinId = $container.find('img').attr('data-pin-id');
        if (repinId) {
            $button.attr('data-pin-id', repinId);
        }
        
        // Apply button styles
        var buttonStyles = {
            'display': 'inline-flex',
            'align-items': 'center',
            'font-size': fontSize,
            'font-weight': '500',
            'padding': padding,
            'background-color': color,
            'color': textColor,
            'border-radius': borderRadius,
            'text-decoration': 'none',
            'cursor': 'pointer'
        };
        
        // Add shadow if enabled
        if (imageShadow) {
            buttonStyles['box-shadow'] = '0 2px 4px rgba(0,0,0,0.15)';
        }
        
        $button.css(buttonStyles);
        
        // Add Pinterest icon (SVG)
        var iconHtml = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="pinnerpress-pin-icon" style="width: 1em; height: 1em; vertical-align: -0.125em; margin-right: 0.3em; fill: currentColor; shape-rendering: geometricPrecision; text-rendering: optimizeLegibility; image-rendering: optimizeQuality;"><path d="M12 0C5.373 0 0 5.373 0 12c0 4.99 3.657 9.132 8.48 10.099-.118-.859-.224-2.178.045-3.116.244-.834 1.577-5.313 1.577-5.313s-.402-.803-.402-1.986c0-1.863 1.08-3.254 2.42-3.254 1.142 0 1.693.859 1.693 1.89 0 1.151-.733 2.87-1.11 4.467-.318 1.322.672 2.401 1.99 2.401 2.388 0 4.224-2.516 4.224-6.14 0-3.204-2.303-5.442-5.581-5.442-3.803 0-6.037 2.849-6.037 5.794 0 1.148.438 2.382 1.054 3.049.117.13.134.244.099.377-.109.427-.354 1.35-.398 1.539-.062.248-.2.302-.461.182-1.723-.796-2.797-3.294-2.797-5.301 0-4.33 3.141-8.306 9.067-8.306 4.754 0 8.442 3.384 8.442 7.917 0 4.715-2.969 8.502-7.085 8.502-1.381 0-2.681-.712-3.123-1.557l-.847 3.216c-.306 1.156-1.14 2.6-1.699 3.487C9.19 23.414 10.573 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"></path></svg>';
        
        $button.html(iconHtml);
        
        // Add button text if showText is true
        if (showText) {
            $button.append(document.createTextNode(buttonText));
        }
        
        // Add click handler to dynamically update image URL and show follow box
        $button.on('click', function(e) {
            pinnerpressDebugLog('PIN BUTTON CLICKED');

            // Get the image element and its current src
            var $img = $container.find('img');
            var currentImgUrl = $img.attr('src') || imgUrl; // Use current src or fallback to original

            // Enhanced image URL detection for mobile and various lazy loading scenarios
            pinnerpressDebugLog('Initial currentImgUrl for pinit:', currentImgUrl);
            
            // Handle data URLs, empty URLs, or invalid URLs from lazy loading
            if (!currentImgUrl || currentImgUrl.startsWith('data:') || currentImgUrl === '' || currentImgUrl === '#') {
                pinnerpressDebugLog('Detected data/empty URL in pinit, searching for actual image URL...');
                
                // Extended list of lazy loading attributes (mobile plugins often use different ones)
                var lazyAttributes = [
                    'data-src', 'data-lazy-src', 'data-original', 'data-full-src', 
                    'data-srcset', 'data-lazy-srcset', 'data-orig', 'data-echo',
                    'data-thumb', 'data-img-src', 'data-image', 'data-large',
                    'data-medium', 'data-mobile-src', 'data-desktop-src'
                ];
                
                // Try each lazy loading attribute
                for (var i = 0; i < lazyAttributes.length; i++) {
                    var attrValue = $img.attr(lazyAttributes[i]);
                    if (attrValue && !attrValue.startsWith('data:') && attrValue !== '' && attrValue !== '#') {
                        currentImgUrl = attrValue;
                        pinnerpressDebugLog('Found valid URL in pinit', lazyAttributes[i], ':', currentImgUrl);
                        break;
                    }
                }
                
                // If still no valid URL, try to get from srcset
                if (!currentImgUrl || currentImgUrl.startsWith('data:') || currentImgUrl === '' || currentImgUrl === '#') {
                    var srcset = $img.attr('srcset') || $img.attr('data-srcset');
                    if (srcset) {
                        // Extract first URL from srcset
                        var srcsetUrls = srcset.split(',');
                        if (srcsetUrls.length > 0) {
                            var firstUrl = srcsetUrls[0].trim().split(' ')[0];
                            if (firstUrl && !firstUrl.startsWith('data:')) {
                                currentImgUrl = firstUrl;
                                pinnerpressDebugLog('Found valid URL in pinit srcset:', currentImgUrl);
                            }
                        }
                    }
                }
                
                // If we still don't have a valid URL, use the original fallback
                if (!currentImgUrl || currentImgUrl.startsWith('data:') || currentImgUrl === '' || currentImgUrl === '#') {
                    currentImgUrl = imgUrl; // Use original URL passed to function
                    pinnerpressDebugLog('Using original fallback URL in pinit:', currentImgUrl);
                }
            }
            
            // Update the data-pin-media attribute with the current image URL
            $button.attr('data-pin-media', currentImgUrl);
            
            // Extract image identification data
            var imageId = null;
            var attachmentId = null;
            
            // Try to extract attachment ID from WordPress image classes (wp-image-123)
            var classNames = $img.attr('class') || '';
            var wpImageMatch = classNames.match(/wp-image-(\d+)/);
            if (wpImageMatch) {
                attachmentId = parseInt(wpImageMatch[1]);
            }
            
            // Generate image ID from URL if not found
            if (!imageId) {
                imageId = generateImageId(currentImgUrl);
            }
            
            // Track analytics event
            pinnerpressTrackEvent('pin_button_click', {
                image_url: currentImgUrl,
                image_id: imageId,
                attachment_id: attachmentId,
                page_url: pageUrl,
                description: description,
                title: title,
                button_position: position,
                button_size: size,
                button_shape: shape
            });
            
            // The actual Pinterest save will be handled by pinit.js
            // We just need to schedule the follow box to show
            setTimeout(function() {
                showFollowBoxIfEnabled();
            }, 100);
        });
        
        // Append button to wrapper, then wrapper to container
        $wrapper.append($button);
        $container.append($wrapper);
    }
    
    /**
     * Create an Image Banner overlay for an image that uses pinit.js
     * @param {jQuery} $container - The container element to append the banner to
     * @param {string} imgUrl - The URL of the image
     * @param {string} pageUrl - The URL of the current page
     * @param {string} description - The description to use for the pin
     * @param {string} title - The title to use for the pin (optional)
     */
    function createImageBanner($container, imgUrl, pageUrl, description, title) {
        // Get banner settings from localized data or use defaults
        var bgColor = 'rgba(255, 255, 255, 0.5)';
        var textColor = '#BD081C';
        var bannerText = 'Pin this';
        var opacity = '50';
        
        // If we have localized data from WordPress, use those settings
        if (typeof pinnerpress_data !== 'undefined') {
            bgColor = pinnerpress_data.banner_bg_color || bgColor;
            textColor = pinnerpress_data.banner_text_color || textColor;
            bannerText = pinnerpress_data.banner_text || bannerText;
            opacity = pinnerpress_data.banner_opacity || opacity;
        }
        
        // Convert opacity to decimal for CSS
        var opacityDecimal = parseInt(opacity) / 100;
        
        // Apply opacity to background color
        if (bgColor.indexOf('rgba') === -1) {
            // Convert hex or rgb to rgba
            var rgbColor = bgColor;
            if (bgColor.indexOf('rgb') === -1) {
                // Convert hex to rgb
                rgbColor = hexToRgb(bgColor);
            }
            // Extract the rgb values
            var rgbMatch = rgbColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
            if (rgbMatch) {
                var r = rgbMatch[1];
                var g = rgbMatch[2];
                var b = rgbMatch[3];
                // Create rgba with new opacity
                bgColor = 'rgba(' + r + ', ' + g + ', ' + b + ', ' + opacityDecimal + ')';
            }
        } else {
            // It's already rgba, just update the opacity
            bgColor = bgColor.replace(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*[\d\.]+\)/, 'rgba($1, $2, $3, ' + opacityDecimal + ')');
        }
        
        // Create banner wrapper as a link - with pinit.js attributes
        var $banner = $('<a class="pinnerpress-image-banner"></a>');
        
        // Set Pinterest pinit.js attributes
        $banner.attr({
            'href': '#', // Will be overridden by pinit.js
            'data-pin-do': 'buttonPin',
            'data-pin-custom': 'true',
            'data-pin-media': imgUrl,
            'data-pin-url': pageUrl,
            'data-pin-description': description
        });
        
        // Add title parameter if available
        if (title) {
            $banner.attr('data-pin-title', title);
        }
        
        // Check for repin ID
        var repinId = $container.find('img').attr('data-pin-id');
        if (repinId) {
            $banner.attr('data-pin-id', repinId);
        }
        
        $banner.css({
            'position': 'absolute',
            'bottom': '0',
            'left': '0',
            'right': '0',
            'background-color': bgColor,
            'color': textColor,
            'padding': '8px 15px',
            'font-size': '22px',
            'font-weight': '500',
            'display': 'flex',
            'align-items': 'center',
            'justify-content': 'center',
            'text-align': 'center',
            'text-decoration': 'none',
            'cursor': 'pointer',
            'z-index': '9'
        });
        
        // Create Pinterest icon (SVG)
        var iconHtml = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="pinnerpress-banner-icon" style="width: 1em; height: 1em; vertical-align: -0.125em; margin-right: 0.4em; fill: currentColor;">' +
                       '<path d="M12 0C5.373 0 0 5.373 0 12c0 4.99 3.657 9.132 8.48 10.099-.118-.859-.224-2.178.045-3.116.244-.834 1.577-5.313 1.577-5.313s-.402-.803-.402-1.986c0-1.863 1.08-3.254 2.42-3.254 1.142 0 1.693.859 1.693 1.89 0 1.151-.733 2.87-1.11 4.467-.318 1.322.672 2.401 1.99 2.401 2.388 0 4.224-2.516 4.224-6.14 0-3.204-2.303-5.442-5.581-5.442-3.803 0-6.037 2.849-6.037 5.794 0 1.148.438 2.382 1.054 3.049.117.13.134.244.099.377-.109.427-.354 1.35-.398 1.539-.062.248-.2.302-.461.182-1.723-.796-2.797-3.294-2.797-5.301 0-4.33 3.141-8.306 9.067-8.306 4.754 0 8.442 3.384 8.442 7.917 0 4.715-2.969 8.502-7.085 8.502-1.381 0-2.681-.712-3.123-1.557l-.847 3.216c-.306 1.156-1.14 2.6-1.699 3.487C9.19 23.414 10.573 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"></path></svg>';
        
        // Add the text content
        var contentHtml = '<span>' + bannerText + '</span>';
        
        // Add content to banner
        $banner.html(iconHtml + contentHtml);
        
        // Add click handler to show follow box modal after pin (if enabled)
        $banner.on('click', function() {
            pinnerpressDebugLog('IMAGE BANNER CLICKED');

            // Extract image identification data
            var imageId = null;
            var attachmentId = null;
            
            // Try to extract attachment ID from WordPress image classes (wp-image-123)
            var $img = $container.find('img');
            var classNames = $img.attr('class') || '';
            var wpImageMatch = classNames.match(/wp-image-(\d+)/);
            if (wpImageMatch) {
                attachmentId = parseInt(wpImageMatch[1]);
            }
            
            // Generate image ID from URL if not found
            if (!imageId) {
                imageId = generateImageId(imgUrl);
            }
            
            // Track analytics event
            pinnerpressTrackEvent('image_banner_click', {
                image_url: imgUrl,
                image_id: imageId,
                attachment_id: attachmentId,
                page_url: pageUrl,
                description: description,
                title: title,
                banner_text: bannerText
            });
            
            // The actual Pinterest save will be handled by pinit.js
            // We just need to schedule the follow box to show
            setTimeout(function() {
                showFollowBoxIfEnabled();
            }, 100);
        });
        
        // Append banner to container
        $container.append($banner);
    }
    
    /**
     * Show the follow box modal if it's enabled and the cookie is not set
     */
    function showFollowBoxIfEnabled() {
        // Check if follow box is enabled in the settings
        var followBoxEnabled = false;
        var showOnPinClick = false;
        
        if (typeof pinnerpress_data !== 'undefined') {
            followBoxEnabled = pinnerpress_data.follow_box_status === 'on';
            showOnPinClick = pinnerpress_data.follow_box_display_pin_click === '1';
        }
        var cookieSet = hasFollowBoxCookie();
        
        pinnerpressDebugLog('PinnerPress: showFollowBoxIfEnabled check: Enabled=', followBoxEnabled, 'Show on pin click=', showOnPinClick, 'Cookie Set=', cookieSet);
        
        // Only show follow box if it's enabled, configured to show on pin click, and cookie is not set
        if (followBoxEnabled && showOnPinClick && !cookieSet) {
            pinnerpressDebugLog('PinnerPress: Follow box enabled and cookie not set, showing follow box modal');
            showFollowBoxModal();
        }
    }
    
    /**
     * Show the follow box modal
     */
    function showFollowBoxModal() {
        $('#pinnerpress-follow-box-modal').fadeIn(300);
    }
    
    /**
     * Check if the follow box cookie is set
     * @return {boolean} True if cookie exists, false otherwise
     */
    function hasFollowBoxCookie() {
        return getCookie('pinnerpress_followed') === 'true';
    }
    
    /**
     * Get a cookie value by name
     * @param {string} name - Name of the cookie
     * @return {string} Cookie value or empty string if not found
     */
    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return "";
    }
    
    // Helper function to convert hex color to rgb
    function hexToRgb(hex) {
        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(_, r, g, b) {
            return r + r + g + g + b + b;
        });
        
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? 
            'rgb(' + parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) + ')' :
            'rgb(0, 0, 0)';
    }
    
    // Helper function to generate consistent image ID from URL (matches PHP logic)
    function generateImageId(imageUrl) {
        // Remove query parameters and hash
        var cleanUrl = imageUrl.split('?')[0].split('#')[0];
        
        // Get filename from URL
        var filename = cleanUrl.split('/').pop();
        
        // Remove common WordPress image size suffixes (-150x150, -300x200, etc.)
        var baseFilename = filename.replace(/-\d+x\d+(\.\w+)?$/, '$1');
        
        // If no extension, use original filename
        if (!baseFilename || baseFilename === filename) {
            baseFilename = filename;
        }
        
        // Create a simple hash-like ID using the base filename
        var hash = 0;
        for (var i = 0; i < baseFilename.length; i++) {
            var char = baseFilename.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32-bit integer
        }
        
        // Convert to positive number and add prefix
        var imageId = 'w' + Math.abs(hash);
        
        return imageId;
    }
    
})(jQuery); 