(function($) {
    "use strict";

    /**
     * OKThemes Masonry & Metro Layouts
     * 
     * JavaScript handler for Masonry and Metro layouts
     * using Packery for advanced grid layouts
     * 
     * @since 1.0.0
     */
    var OKThemesMasonryMetro = function($scope, $) {
        // Find grid element
        var $grid = $scope.find('.elementor-grid');
        
        if (!$grid.length) {
            return;
        }

        var $items = $grid.find('.elementor-grid-item'),
            masonryId = $grid.data('masonry-id');
        
        if (!masonryId || !$items.length) {
            return;
        }

        var elementSettings = getElementSettings($scope);
        
        // Initialize layout based on settings
        if (elementSettings.layout === 'masonry' || elementSettings.layout === 'metro') {
            initMasonryLayout();
        }

        /**
         * Initialize Masonry Layout
         * 
         * Sets up the masonry or metro grid using Packery
         */
        function initMasonryLayout() {
            // Get column count
            var columnCount = getColumnCount(),
                columnWidth = $grid.width() / columnCount;

            // Wait for images to load
            $grid.imagesLoaded(function() {
                // Initialize Packery
                var packery = new Packery($grid[0], {
                    itemSelector: '.elementor-grid-item',
                    percentPosition: true,
                    columnWidth: '.elementor-grid-item',
                    gutter: 0
                });

                // Apply layout based on data attributes for metro
                if (elementSettings.layout === 'metro') {
                    applyMetroLayout(packery, columnWidth);
                }

                // Add resize handling
                $(window).on('resize', debounce(function() {
                    columnCount = getColumnCount();
                    columnWidth = $grid.width() / columnCount;
                    
                    if (elementSettings.layout === 'metro') {
                        applyMetroLayout(packery, columnWidth);
                    }
                    
                    packery.layout();
                }, 300));
            });
        }

        /**
         * Apply Metro Layout
         * 
         * Sets up grid items for metro layout based on settings
         * 
         * @param {Object} packery Packery instance
         * @param {number} columnWidth Width of a single column
         */
        function applyMetroLayout(packery, columnWidth) {
            // Process repeater items for Metro layout
            if (elementSettings.product_metro && elementSettings.product_metro.length) {
                $items.each(function() {
                    var $item = $(this),
                        itemId = $item.data('id');
                    
                    // Find matching metro setting
                    var metroItem = elementSettings.product_metro.find(function(item) {
                        return parseInt(item.id) === parseInt(itemId);
                    });
                    
                    if (metroItem) {
                        // Parse width and height values from settings
                        var width = parseMetroSize(metroItem.item_width),
                            height = parseMetroSize(metroItem.item_height);
                        
                        // Apply width and height
                        $item.css({
                            width: width * columnWidth + 'px',
                            height: height * columnWidth + 'px'
                        });
                    }
                });
                
                // Layout again after applying sizes
                packery.layout();
            }
        }

        /**
         * Parse Metro Size
         * 
         * Converts metro size format (e.g. "2-3") to a number
         * 
         * @param {string} size Size in format "columns-rows"
         * @returns {number} Numeric size
         */
        function parseMetroSize(size) {
            if (!size) return 1;
            
            var parts = size.split('-');
            if (parts.length === 2) {
                return parseInt(parts[0], 10);
            }
            
            return 1;
        }

        /**
         * Get Column Count
         * 
         * Determines the current column count based on responsive settings
         * 
         * @returns {number} Current column count
         */
        function getColumnCount() {
            var defaultColumns = elementSettings.columns || 3;
            
            // Check responsive settings based on window width
            if (window.innerWidth <= 767 && elementSettings.columns_mobile) {
                return elementSettings.columns_mobile;
            } else if (window.innerWidth <= 1024 && elementSettings.columns_tablet) {
                return elementSettings.columns_tablet;
            }
            
            return defaultColumns;
        }

        /**
         * Get Element Settings
         * 
         * Extract settings from the element data
         * 
         * @param {jQuery} $element The element to get settings from
         * @returns {Object} Element settings
         */
        function getElementSettings($element) {
            var elementSettings = {},
                modelCID = $element.data('model-cid');

            if (elementorFrontend.isEditMode() && modelCID) {
                var settings = elementorFrontend.config.elements.data[modelCID],
                    settingsKeys = elementorFrontend.config.elements.keys[settings.attributes.widgetType || settings.attributes.elType],
                    type = settings.attributes.widgetType || settings.attributes.elType;

                if (settings && settingsKeys) {
                    settingsKeys.forEach(function(key) {
                        elementSettings[key] = settings.getSettings(key);
                    });

                    // Process responsive settings
                    if ('widget' === type) {
                        elementSettings = processResponsiveSettings(elementSettings);
                    }
                }
            } else {
                elementSettings = $element.data('settings') || {};
            }

            return elementSettings;
        }

        /**
         * Process Responsive Settings
         * 
         * @param {Object} settings The original element settings
         * @returns {Object} Processed settings with responsive values
         */
        function processResponsiveSettings(settings) {
            var currentDeviceMode = elementorFrontend.getCurrentDeviceMode(),
                responsiveSettings = {};
                
            // Deep clone the settings object
            responsiveSettings = $.extend(true, {}, settings);
            
            // Add responsive values
            $.each(settings, function(key, value) {
                if (key.includes('_tablet')) {
                    var baseKey = key.replace('_tablet', '');
                    if (currentDeviceMode === 'tablet') {
                        responsiveSettings[baseKey] = value;
                    }
                } else if (key.includes('_mobile')) {
                    var baseKey = key.replace('_mobile', '');
                    if (currentDeviceMode === 'mobile') {
                        responsiveSettings[baseKey] = value;
                    }
                }
            });

            return responsiveSettings;
        }

        /**
         * Debounce Function
         * 
         * Limits how often a function can be called
         * 
         * @param {Function} func The function to debounce
         * @param {number} wait Wait time in milliseconds
         * @returns {Function} Debounced function
         */
        function debounce(func, wait) {
            var timeout;
            
            return function() {
                var context = this,
                    args = arguments;
                    
                clearTimeout(timeout);
                
                timeout = setTimeout(function() {
                    func.apply(context, args);
                }, wait);
            };
        }
    };

    // Initialize the widget when it's ready
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/okthemes-woo-products.default', OKThemesMasonryMetro);
    });

})(jQuery);