/**
 * Pawfect Reusable Limitation System - True Shopire Style Implementation
 * Flexible system for limiting repeater controls across different sections
 */


(function($) {
    'use strict';

    var pawfect_theme_controls = $('#customize-theme-controls');


    /**
     * Reusable Limitation Class
     * Handles limitation for any repeater control with customizable settings
     */
    function PawfectLimitationSystem(config) {
        this.controlId = config.controlId;
        this.upgradeControlId = config.upgradeControlId;
        this.limit = config.limit || 2;
        this.featureName = config.featureName || 'slides';
        this.upgradeMessage = config.upgradeMessage || 'Upgrade to Pawfect Pro for unlimited ' + this.featureName + ' and premium features!';
        this.upgradeUrl = config.upgradeUrl || 'https://wpmatcha.com/wordpress-themes/pawfect/';


        this.init();
    }

    PawfectLimitationSystem.prototype = {
        /**
         * Initialize the limitation system
         */
        init: function() {
            var self = this;
            setTimeout(function() {
                self.setupLimitation();
            }, 1500);
        },

        /**
         * Setup limitation for the specific control
         */
        setupLimitation: function() {
            var self = this;
            var sliderControl = $('#customize-control-' + this.controlId);
            var upgradeControl = $('#customize-control-' + this.upgradeControlId);
            var addButton = sliderControl.find('.customizer-repeater-new-field');


            if (sliderControl.length && upgradeControl.length) {

                // Log current item count
                var currentItems = this.getCurrentItemCount();

                this.setupClickHandlers();

            } else {
                var self = this;
                setTimeout(function() {
                    self.setupLimitation();
                }, 1000);
            }
        },

        /**
         * Setup click handlers for the add button
         */
        setupClickHandlers: function() {
            var self = this;

            // Method 1: Direct event capture on the specific control
            $(document).on('click', '#customize-control-' + this.controlId + ' .customizer-repeater-new-field', function(e) {

                var totalItems = self.getCurrentItemCount();

                if (totalItems >= self.limit) {

                    // Stop all event handling immediately
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();

                    // Show upgrade notice
                    self.showUpgradeNotice();

                    return false;
                } else {
                }
            });

            // Method 2: High-priority event handler using event capture
            var controlElement = document.getElementById('customize-control-' + this.controlId);
            if (controlElement) {
                controlElement.addEventListener('click', function(e) {
                    // Check if the clicked element is the add button
                    if (e.target && (
                        e.target.classList.contains('customizer-repeater-new-field') ||
                        e.target.classList.contains('add_field') ||
                        (e.target.textContent && e.target.textContent.toLowerCase().includes('add'))
                    )) {

                        var totalItems = self.getCurrentItemCount();

                        if (totalItems >= self.limit) {

                            // Stop the event completely
                            e.preventDefault();
                            e.stopPropagation();
                            e.stopImmediatePropagation();

                            // Show upgrade notice
                            self.showUpgradeNotice();

                            return false;
                        }
                    }
                }, true); // Use capture phase (true) to run before other handlers
            }
        },

        /**
         * Get current item count for this control
         */
        getCurrentItemCount: function() {
            return $("#customize-control-" + this.controlId + " .customizer-repeater-general-control-repeater-container").length;
        },

        /**
         * Show upgrade notice with animation and detailed debugging
         * Prevents duplicates and keeps notice visible permanently
         */
        showUpgradeNotice: function() {
            var self = this;

            // First, check if upgrade notice is already visible for THIS specific section to prevent duplicates
            var upgradeControl = $("#customize-control-" + this.upgradeControlId);
            var controlElement = $("#customize-control-" + this.controlId);

            // Check for existing notices specific to this section
            var sectionSpecificDynamicClass = 'pawfect-upgrade-pro-message-dynamic-' + this.controlId.replace(/_/g, '-');
            var sectionSpecificFallbackClass = 'pawfect-upgrade-pro-message-fallback-' + this.controlId.replace(/_/g, '-');

            var existingNoticesInSection = upgradeControl.find('.pawfect-upgrade-pro-message:visible, .' + sectionSpecificDynamicClass + ':visible');
            var existingFallbackInSection = $('.' + sectionSpecificFallbackClass + ':visible');

            if (existingNoticesInSection.length > 0 || existingFallbackInSection.length > 0) {
                return;
            }

            // Try multiple selectors to find the upgrade message (already defined above)
            var upgradeMessage = upgradeControl.find('.pawfect-upgrade-pro-message');


            if (upgradeControl.length > 0) {
            }

            // Method 1: Try to find existing upgrade message
            if (upgradeMessage.length > 0) {

                // Check if it's already visible
                if (upgradeMessage.is(':visible')) {
                    return;
                }

                // Show the message permanently (no auto-hide)
                upgradeMessage.css('display', 'block').hide().fadeIn(300);

                return;
            }

            // Method 2: Try alternative selectors
            var altMessage = $('.pawfect-upgrade-pro-message');

            if (altMessage.length > 0) {
                var visibleAltMessage = altMessage.filter(':visible');
                if (visibleAltMessage.length > 0) {
                    return;
                }

                altMessage.first().css('display', 'block').hide().fadeIn(300);
                return;
            }

            // Method 3: Create upgrade notice dynamically if not found

            if (upgradeControl.length > 0) {
                // Check if dynamic notice already exists for this specific section
                var sectionSpecificClass = 'pawfect-upgrade-pro-message-dynamic-' + this.controlId.replace(/_/g, '-');
                var existingDynamic = upgradeControl.find('.' + sectionSpecificClass);
                if (existingDynamic.length > 0) {
                    if (!existingDynamic.is(':visible')) {
                        existingDynamic.fadeIn(300);
                    }
                    return;
                }

                var dynamicNotice = $('<div class="pawfect-upgrade-pro-message-dynamic ' + sectionSpecificClass + ' notice notice-info" style="display: none; margin: 12px 0; position: relative;">' +
                    '<p style="margin: 0;">' +
                    '<strong>Upgrade to <a href="' + this.upgradeUrl + '" target="_blank" rel="noopener">Pawfect Pro</a></strong> ' +
                    this.upgradeMessage +
                    '</p>' +
                    '</div>');

                // Insert the notice into the upgrade control
                upgradeControl.append(dynamicNotice);

                // Show with animation (permanent, no auto-hide)
                dynamicNotice.fadeIn(300);

            } else {
                // Method 4: Create notice directly in control as last resort
                this.createFallbackNotice();
            }
        },

        /**
         * Create fallback notice directly in the control area
         */
        createFallbackNotice: function() {
            var controlElement = $("#customize-control-" + this.controlId);

            if (controlElement.length > 0) {
                // Check if fallback notice already exists for this specific section
                var fallbackSpecificClass = 'pawfect-upgrade-pro-message-fallback-' + this.controlId.replace(/_/g, '-');
                var existingFallback = $('.' + fallbackSpecificClass);
                if (existingFallback.length > 0) {
                    if (!existingFallback.is(':visible')) {
                        existingFallback.fadeIn(300);
                    }
                    return;
                }

                var fallbackNotice = $('<div class="pawfect-upgrade-pro-message-fallback ' + fallbackSpecificClass + ' notice notice-info" style="display: none; margin: 12px 0; position: relative;">' +
                    '<p style="margin: 0;">' +
                    '<strong>Upgrade to <a href="' + this.upgradeUrl + '" target="_blank" rel="noopener">Pawfect Pro</a></strong> ' +
                    this.upgradeMessage +
                    '</p>' +
                    '</div>');

                // Insert after the control
                controlElement.after(fallbackNotice);

                // Show with animation (permanent, no auto-hide)
                fallbackNotice.fadeIn(300);

            } else {
            }
        }
    };

    // Initialize limitation systems for different sections
    var limitationSystems = [];

    /**
     * Initialize all limitation systems
     */
    function initializeLimitationSystems() {

        // Hero Slider Limitation (2 slides)
        var heroSliderLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_main_slider_content',
            upgradeControlId: 'pawfect_main_slider_content_upsale',
            limit: 2,
            featureName: 'slides',
            upgradeMessage: 'for unlimited slides and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(heroSliderLimitation);

        // Press Mentions Limitation (3 items)
        var pressMentionsLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_press_mentions_content',
            upgradeControlId: 'pawfect_press_mentions_content_upsale',
            limit: 3,
            featureName: 'press mentions',
            upgradeMessage: 'for unlimited press mentions and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(pressMentionsLimitation);

        // Feature Highlight Limitation (2 items)
        var featureHighlightLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_feature_highlight_collage',
            upgradeControlId: 'pawfect_feature_highlight_collage_upsale',
            limit: 2,
            featureName: 'feature images',
            upgradeMessage: 'for unlimited feature images and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(featureHighlightLimitation);

        // Why Choose Limitation (3 items)
        var whyChooseLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_service_content',
            upgradeControlId: 'pawfect_service_content_upsale',
            limit: 3,
            featureName: 'why choose items',
            upgradeMessage: 'for unlimited why choose items and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(whyChooseLimitation);

        // Portfolio Limitation (4 items)
        var portfolioLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_portfolio_content',
            upgradeControlId: 'pawfect_portfolio_content_upsale',
            limit: 4,
            featureName: 'portfolio items',
            upgradeMessage: 'for unlimited portfolio items and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(portfolioLimitation);

        // Testimonial Limitation (2 items)
        var testimonialLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_testimonial_content',
            upgradeControlId: 'pawfect_testimonial_content_upsale',
            limit: 2,
            featureName: 'testimonials',
            upgradeMessage: 'for unlimited testimonials and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(testimonialLimitation);

        // Pet Shop Limitation (2 items)
        var petShopLimitation = new PawfectLimitationSystem({
            controlId: 'pawfect_pet_shop_items',
            upgradeControlId: 'pawfect_pet_shop_items_upsale',
            limit: 2,
            featureName: 'pet categories',
            upgradeMessage: 'for unlimited pet categories and premium features!',
            upgradeUrl: 'https://wpmatcha.com/wordpress-themes/pawfect/'
        });

        limitationSystems.push(petShopLimitation);


        // Initialize Pro-only section prevention
        initializeProOnlyPrevention();
    }

    /**
     * Prevent Pro-only sections from opening (no visual changes)
     */
    function initializeProOnlyPrevention() {
        var proOnlySections = [
            'pawfect_instagram_gallery_section',
            'pawfect_promo_timer_section'
        ];

        proOnlySections.forEach(function(sectionId) {
            preventSectionOpening(sectionId);
        });
    }

    /**
     * Prevent a specific section from opening
     */
    function preventSectionOpening(sectionId) {
        // Multiple event handlers to ensure prevention
        $(document).on('click.proonly', '#accordion-section-' + sectionId + ' .accordion-section-title', function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            return false;
        });

        // Also prevent mousedown and keydown events
        $(document).on('mousedown.proonly keydown.proonly', '#accordion-section-' + sectionId + ' .accordion-section-title', function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            return false;
        });

        // Remove any existing click handlers that might open the section
        setTimeout(function() {
            $('#accordion-section-' + sectionId + ' .accordion-section-title').off('click.customize-section');
        }, 100);
    }

    // Initialize when document is ready
    $(document).ready(function() {
        initializeLimitationSystems();
    });

    // Also initialize on customizer ready event
    $(document).on('customize-ready', function() {
        initializeLimitationSystems();
    });


})(jQuery);
