/**
 * RSL Layout System - Core Grid Engine
 *
 * Dynamically calculates and applies column counts to slot-layout containers
 * based on viewport width and data attributes. Supports responsive breakpoints
 * with cascading inheritance from smaller to larger breakpoints.
 *
 * @fileoverview Core grid calculation engine for RSL's slot-based layout system
 * @version 2.0.0
 * @license MIT
 *
 * Breakpoints:
 * - XS: 0-576px (mobile)
 * - SM: 577-768px (large mobile/small tablet)
 * - MD: 769-992px (tablet)
 * - LG: 993-1200px (small desktop)
 * - XL: 1201-1600px (desktop)
 * - XXL: 1601px+ (large desktop)
 *
 * Usage:
 * <div class="slot-layout" data-cols-xs="1" data-cols-md="2" data-cols-lg="3">
 *   <div class="slot-item">...</div>
 * </div>
 */

(function() {
    'use strict';

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

    /**
     * Main initialization function
     * Finds all slot layouts and sets up responsive column calculation
     */
    function initializeLayouts() {
        const slotLayouts = document.querySelectorAll('.slot-layout, .nested-slot-layout');

        // Calculate columns for all layouts on page load
        slotLayouts.forEach(layout => calculateColumns(layout));

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

    /**
     * Safely read an integer from a data attribute
     *
     * @param {HTMLElement} layout - The layout element
     * @param {string} attrName - The data attribute name (e.g., 'data-cols-md')
     * @returns {number|null} Parsed integer or null if not present/invalid
     */
    function getColsAttr(layout, attrName) {
        const val = layout.getAttribute(attrName);
        if (val === null || val === '') return null;
        const parsed = parseInt(val, 10);
        return Number.isNaN(parsed) ? null : parsed;
    }

    /**
     * Returns the first non-null/non-undefined value from arguments
     * Used for cascading breakpoint inheritance
     *
     * @param {...*} values - Values to check
     * @returns {*} First defined value or null
     *
     * @example
     * firstDefined(null, undefined, 3, 4) // returns 3
     */
    function firstDefined(...values) {
        for (const v of values) {
            if (v !== null && v !== undefined) {
                return v;
            }
        }
        return null;
    }

    /**
     * Calculate and apply column count based on viewport width
     *
     * Implements cascading breakpoint inheritance: larger breakpoints
     * automatically inherit from smaller ones if not explicitly set.
     * Falls back to auto-calculation based on item count if no
     * breakpoints are defined.
     *
     * @param {HTMLElement} layout - The slot-layout container
     *
     * @example
     * // Layout with only data-cols-md="2" will use:
     * // - 1 column on XS and SM (inherited from default)
     * // - 2 columns on MD, LG, XL, XXL (inherited from MD)
     */
    function calculateColumns(layout) {
        const layoutWidth = layout.offsetWidth;
        const slotItemsCount = layout.children.length;

        // Read all breakpoint attributes once
        const colsXs  = getColsAttr(layout, 'data-cols-xs');
        const colsSm  = getColsAttr(layout, 'data-cols-sm');
        const colsMd  = getColsAttr(layout, 'data-cols-md');
        const colsLg  = getColsAttr(layout, 'data-cols-lg');
        const colsXl  = getColsAttr(layout, 'data-cols-xl');
        const colsXxl = getColsAttr(layout, 'data-cols-xxl');

        let columns = 1;

        // Determine column count based on viewport width
        // Each breakpoint cascades down through smaller breakpoints
        if (layoutWidth > 1600) {
            // XXL: 1601px+ (large desktop)
            columns = firstDefined(
                colsXxl,
                colsXl,
                colsLg,
                colsMd,
                colsSm,
                colsXs,
                Math.min(12, slotItemsCount) // Auto: up to 12 columns
            );
        } else if (layoutWidth > 1200) {
            // XL: 1201-1600px (desktop)
            columns = firstDefined(
                colsXl,
                colsLg,
                colsMd,
                colsSm,
                colsXs,
                Math.min(6, slotItemsCount) // Auto: up to 6 columns
            );
        } else if (layoutWidth > 992) {
            // LG: 993-1200px (small desktop)
            columns = firstDefined(
                colsLg,
                colsMd,
                colsSm,
                colsXs,
                Math.min(4, slotItemsCount) // Auto: up to 4 columns
            );
        } else if (layoutWidth > 768) {
            // MD: 769-992px (tablet)
            columns = firstDefined(
                colsMd,
                colsSm,
                colsXs,
                Math.min(3, slotItemsCount) // Auto: up to 3 columns
            );
        } else if (layoutWidth > 576) {
            // SM: 577-768px (large mobile/small tablet)
            columns = firstDefined(
                colsSm,
                colsXs,
                Math.min(2, slotItemsCount) // Auto: up to 2 columns
            );
        } else {
            // XS: 0-576px (mobile-first default)
            columns = colsXs !== null ? colsXs : 1;
        }

        // Apply column count to CSS custom property
        // grid.css uses: grid-template-columns: repeat(var(--dynamic-cols), 1fr)
        layout.style.setProperty('--dynamic-cols', columns);
    }

})();
