/**
 * RSL Layout System - Auto-Calculation Enhancement
 *
 * Progressive enhancement layer that provides automatic column calculation
 * for layouts without explicit data-cols-* attributes.
 *
 * ARCHITECTURE:
 * - grid.css handles ALL layouts with data-cols-* attributes (CSS-only)
 * - This file provides auto-calculation for layouts WITHOUT attributes
 * - If this file fails to load, CSS-defined layouts still work perfectly
 *
 * @fileoverview Auto-calculation enhancement for RSL grid system
 * @version 3.1.0 - Progressive Enhancement
 * @license MIT
 */

(function() {
    'use strict';

    /**
     * Initialize layout system on DOM ready
     */
    document.addEventListener('DOMContentLoaded', initializeLayouts);

    /**
     * Main initialization function
     * Sets up auto-calculation and responsive behavior
     */
    function initializeLayouts() {
        const layouts = document.querySelectorAll('.slot-layout, .nested-slot-layout');

        // Calculate columns for all layouts
        layouts.forEach(layout => {
            calculateColumns(layout);
            applyAdvancedSlotPositioning(layout);
        });

        // Recalculate on window resize
        window.addEventListener('resize', () => {
            layouts.forEach(layout => {
                calculateColumns(layout);
                applyAdvancedSlotPositioning(layout);
            });
        });
    }

    /**
     * Calculate and apply column count based on container width
     *
     * Sets --dynamic-cols CSS variable which is used as fallback when
     * no data-cols-* attributes are present.
     *
     * @param {HTMLElement} layout - The slot-layout container
     */
    function calculateColumns(layout) {
        // Performance optimization: skip if layout has explicit columns
        // CSS will handle it via --cols variable (takes priority in fallback chain)
        if (layout.hasAttribute('data-cols-xs') || layout.hasAttribute('data-cols-sm') ||
            layout.hasAttribute('data-cols-md') || layout.hasAttribute('data-cols-lg') ||
            layout.hasAttribute('data-cols-xl') || layout.hasAttribute('data-cols-xxl')) {
            return;
        }

        const layoutWidth = layout.offsetWidth;
        const slotItemsCount = layout.children.length;

        let columns = 1;

        // Auto-calculation based on container width
        if (layoutWidth > 1600) {
            // XXL: 1601px+ (large desktop) - up to 12 columns
            columns = Math.min(12, slotItemsCount);
        } else if (layoutWidth > 1200) {
            // XL: 1201-1600px (desktop) - up to 6 columns
            columns = Math.min(6, slotItemsCount);
        } else if (layoutWidth > 992) {
            // LG: 993-1200px (small desktop) - up to 4 columns
            columns = Math.min(4, slotItemsCount);
        } else if (layoutWidth > 768) {
            // MD: 769-992px (tablet) - up to 3 columns
            columns = Math.min(3, slotItemsCount);
        } else if (layoutWidth > 576) {
            // SM: 577-768px (large mobile/small tablet) - up to 2 columns
            columns = Math.min(2, slotItemsCount);
        } else {
            // XS: 0-576px (mobile) - 1 column
            columns = 1;
        }

        // Set --dynamic-cols CSS variable
        // This will be used only if no data-cols-* attributes are present
        layout.style.setProperty('--dynamic-cols', columns);
    }

    /**
     * Apply advanced grid placement from data attributes
     *
     * Reads data-col-start, data-col-end, data-row-start, data-row-end attributes
     * from .slot-item and .nested-slot-item elements and applies them as CSS variables
     * for explicit grid positioning control.
     *
     * This is an escape hatch for developers who need precise control over
     * grid-row and grid-column placement beyond RSL's automatic layout.
     *
     * @param {HTMLElement} container - The slot-layout or nested-slot-layout container
     *
     * @example
     * <div class="slot-layout" data-cols-md="3">
     *   <div class="slot-item" data-col-start="1" data-col-end="3">Spans 2 columns</div>
     *   <div class="slot-item" data-row-start="1" data-row-end="3">Spans 2 rows</div>
     * </div>
     */
    function applyAdvancedSlotPositioning(container) {
        // Get all slot items (both regular and nested)
        const items = container.querySelectorAll('.slot-item, .nested-slot-item');

        items.forEach(item => {
            // Read placement data attributes
            const colStart = item.getAttribute('data-col-start');
            const colEnd = item.getAttribute('data-col-end');
            const rowStart = item.getAttribute('data-row-start');
            const rowEnd = item.getAttribute('data-row-end');

            // Apply CSS variables if attributes are present
            if (colStart) {
                item.style.setProperty('--column-start', colStart);
            }
            if (colEnd) {
                item.style.setProperty('--column-end', colEnd);
            }
            if (rowStart) {
                item.style.setProperty('--row-start', rowStart);
            }
            if (rowEnd) {
                item.style.setProperty('--row-end', rowEnd);
            }
        });
    }

    /**
     * Expose public API for programmatic column adjustment
     */
    window.RSL = window.RSL || {};
    window.RSL.Layout = {
        /**
         * Recalculate columns for a specific layout
         * @param {HTMLElement|string} layout - Layout element or selector
         */
        recalculate: function(layout) {
            const el = typeof layout === 'string' ? document.querySelector(layout) : layout;
            if (el) {
                calculateColumns(el);
                applyAdvancedSlotPositioning(el);
            }
        },

        /**
         * Recalculate all layouts
         */
        recalculateAll: function() {
            document.querySelectorAll('.slot-layout, .nested-slot-layout').forEach(layout => {
                calculateColumns(layout);
                applyAdvancedSlotPositioning(layout);
            });
        },

        /**
         * Apply advanced grid positioning to a specific layout
         * @param {HTMLElement|string} layout - Layout element or selector
         */
        applyAdvancedPositioning: function(layout) {
            const el = typeof layout === 'string' ? document.querySelector(layout) : layout;
            if (el) {
                applyAdvancedSlotPositioning(el);
            }
        }
    };

})();
