/**
 * RSL Sidebar Layout System
 *
 * Automatically configures sidebar layouts by applying appropriate CSS classes
 * based on data attributes. Supports left, right, and dual sidebar configurations
 * with optional full-width content sections below sidebars.
 *
 * @fileoverview Automatic sidebar layout configuration system
 * @version 1.0.1
 * @license MIT
 *
 * Key Features:
 * - Automatic class application based on data attributes
 * - Three layout modes: left, right, both
 * - Optional below-sidebar full-width section
 * - Flexible slot-based architecture
 * - JSON Layout API compatible
 * - Semantic slot naming for clarity
 *
 * Usage:
 * // Left sidebar layout:
 * <div class="rsl-sidebar-auto" data-sidebar="left">
 *   <aside data-sidebar-slot="sidebar">Left sidebar content</aside>
 *   <main data-sidebar-slot="main">Main content</main>
 * </div>
 *
 * // Right sidebar layout:
 * <div class="rsl-sidebar-auto" data-sidebar="right">
 *   <main data-sidebar-slot="main">Main content</main>
 *   <aside data-sidebar-slot="sidebar">Right sidebar content</aside>
 * </div>
 *
 * // Dual sidebar layout:
 * <div class="rsl-sidebar-auto" data-sidebar="both">
 *   <aside data-sidebar-slot="left">Left sidebar</aside>
 *   <main data-sidebar-slot="main">Main content</main>
 *   <aside data-sidebar-slot="right">Right sidebar</aside>
 * </div>
 *
 * // With full-width section below:
 * <div class="rsl-sidebar-auto" data-sidebar="left">
 *   <aside data-sidebar-slot="sidebar">Sidebar</aside>
 *   <main data-sidebar-slot="main">Main</main>
 *   <section data-sidebar-slot="below">Full-width footer</section>
 * </div>
 *
 * Public API:
 * - RSL.Sidebar.init() - Initialize all sidebar layouts (JSON API compatible)
 * - RSL.Sidebar.create(container) - Create sidebar layout for specific container
 * - RSL.Sidebar.instances - Map of initialized sidebar instances
 * - Container class: .rsl-sidebar-auto
 * - Mode attribute: data-sidebar="left|right|both"
 * - Slot attributes: data-sidebar-slot="sidebar|left|right|main|below"
 * - Applied classes: .rsl-sidebar, .rsl-sidebar-left, .rsl-sidebar-right,
 *   .rsl-main-with-sidebar, .rsl-main-with-both, .rsl-below-sidebar
 *
 * JSON Layout API:
 * This component is fully compatible with the RSL JSON Layout API.
 * Sidebars rendered via JSON will automatically initialize when
 * RSL.Sidebar.init() is called (automatic in JSON rendering).
 */

(function() {
    'use strict';

    // Initialize RSL namespace
    window.RSL = window.RSL || {};

    /**
     * Sidebar layout modes
     * @const
     * @type {Object<string, string>}
     */
    const SIDEBAR_MODES = {
        LEFT: 'left',
        RIGHT: 'right',
        BOTH: 'both'
    };

    /**
     * Track initialized sidebar instances to prevent double-initialization
     * @type {Map<HTMLElement, Object>}
     */
    const instances = new Map();

    /**
     * Get sidebar mode from data attribute
     *
     * Retrieves and normalizes the data-sidebar attribute value.
     * Defaults to 'left' if not specified or invalid.
     *
     * @param {HTMLElement} container - Sidebar layout container
     * @returns {string} Sidebar mode: 'left', 'right', or 'both'
     *
     * @example
     * <div data-sidebar="right">
     * getSidebarMode(element); // returns 'right'
     */
    function getSidebarMode(container) {
        const mode = (container.getAttribute('data-sidebar') || 'left').toLowerCase();
        return Object.values(SIDEBAR_MODES).includes(mode) ? mode : SIDEBAR_MODES.LEFT;
    }

    /**
     * Configure left sidebar layout
     *
     * Applies classes for a left sidebar configuration where the sidebar
     * appears on the left side with main content on the right.
     *
     * @param {Object} slots - Object containing slot elements
     * @param {HTMLElement} slots.sidebarGeneric - Generic sidebar slot
     * @param {HTMLElement} slots.main - Main content slot
     * @returns {void}
     *
     * @example
     * // Transforms:
     * // <aside data-sidebar-slot="sidebar"> -> class="rsl-sidebar"
     * // <main data-sidebar-slot="main"> -> class="rsl-main-with-sidebar"
     */
    function configureLeftSidebar(slots) {
        if (slots.sidebarGeneric) {
            slots.sidebarGeneric.classList.add('rsl-sidebar');
        }
        if (slots.main) {
            slots.main.classList.add('rsl-main-with-sidebar');
        }
    }

    /**
     * Configure right sidebar layout
     *
     * Applies classes for a right sidebar configuration where the sidebar
     * appears on the right side with main content on the left.
     *
     * @param {Object} slots - Object containing slot elements
     * @param {HTMLElement} slots.sidebarGeneric - Generic sidebar slot
     * @param {HTMLElement} slots.main - Main content slot
     * @returns {void}
     *
     * @example
     * // Transforms:
     * // <aside data-sidebar-slot="sidebar"> -> class="rsl-sidebar-right"
     * // <main data-sidebar-slot="main"> -> class="rsl-main-with-sidebar"
     */
    function configureRightSidebar(slots) {
        if (slots.sidebarGeneric) {
            slots.sidebarGeneric.classList.add('rsl-sidebar-right');
        }
        if (slots.main) {
            slots.main.classList.add('rsl-main-with-sidebar');
        }
    }

    /**
     * Configure dual sidebar layout
     *
     * Applies classes for a layout with both left and right sidebars,
     * with main content in the center.
     *
     * @param {Object} slots - Object containing slot elements
     * @param {HTMLElement} slots.sidebarLeft - Left sidebar slot
     * @param {HTMLElement} slots.sidebarRight - Right sidebar slot
     * @param {HTMLElement} slots.main - Main content slot
     * @returns {void}
     *
     * @example
     * // Transforms:
     * // <aside data-sidebar-slot="left"> -> class="rsl-sidebar-left"
     * // <aside data-sidebar-slot="right"> -> class="rsl-sidebar-right"
     * // <main data-sidebar-slot="main"> -> class="rsl-main-with-both"
     */
    function configureBothSidebars(slots) {
        if (slots.sidebarLeft) {
            slots.sidebarLeft.classList.add('rsl-sidebar-left');
        }
        if (slots.sidebarRight) {
            slots.sidebarRight.classList.add('rsl-sidebar-right');
        }
        if (slots.main) {
            slots.main.classList.add('rsl-main-with-both');
        }
    }

    /**
     * Configure below-sidebar section
     *
     * Applies class to content that should appear below the sidebar/main
     * layout in a full-width section. Useful for footers or related content.
     *
     * @param {HTMLElement} belowSlot - Below slot element
     * @returns {void}
     *
     * @example
     * // Transforms:
     * // <section data-sidebar-slot="below"> -> class="rsl-below-sidebar"
     */
    function configureBelowSection(belowSlot) {
        if (belowSlot) {
            belowSlot.classList.add('rsl-below-sidebar');
        }
    }

    /**
     * Get all sidebar slot elements from container
     *
     * Queries container for all slot elements using data-sidebar-slot attributes.
     * Returns an object with named references to each slot for easy access.
     *
     * @param {HTMLElement} container - Sidebar layout container
     * @returns {Object} Object containing slot element references
     * @returns {HTMLElement|null} return.sidebarGeneric - Generic sidebar slot
     * @returns {HTMLElement|null} return.sidebarLeft - Left sidebar slot
     * @returns {HTMLElement|null} return.sidebarRight - Right sidebar slot
     * @returns {HTMLElement|null} return.main - Main content slot
     * @returns {HTMLElement|null} return.below - Below-sidebar slot
     *
     * @example
     * const slots = getSidebarSlots(container);
     * if (slots.sidebarGeneric) { ... }
     */
    function getSidebarSlots(container) {
        return {
            sidebarGeneric: container.querySelector('[data-sidebar-slot="sidebar"]'),
            sidebarLeft: container.querySelector('[data-sidebar-slot="left"]'),
            sidebarRight: container.querySelector('[data-sidebar-slot="right"]'),
            main: container.querySelector('[data-sidebar-slot="main"]'),
            below: container.querySelector('[data-sidebar-slot="below"]')
        };
    }

    /**
     * Create sidebar layout for a specific container
     *
     * Converts an auto-sidebar container into a proper sidebar layout by:
     * 1. Checking for existing initialization (prevents double-init)
     * 2. Adding base layout class
     * 3. Determining layout mode from data attribute
     * 4. Querying for slot elements
     * 5. Applying appropriate classes based on mode
     * 6. Storing instance for tracking
     *
     * @param {HTMLElement} container - Sidebar container with class .rsl-sidebar-auto
     * @returns {Object} Instance object containing container, mode, and slots
     *
     * @example
     * const container = document.querySelector('.rsl-sidebar-auto');
     * RSL.Sidebar.create(container);
     */
    function createSidebarLayout(container) {
        // Prevent double-initialization
        if (instances.has(container)) {
            return instances.get(container);
        }

        // Transform into proper sidebar layout
        container.classList.add('rsl-sidebar-layout');

        const mode = getSidebarMode(container);
        const slots = getSidebarSlots(container);

        // Apply classes based on sidebar mode
        switch (mode) {
            case SIDEBAR_MODES.LEFT:
                configureLeftSidebar(slots);
                break;
            case SIDEBAR_MODES.RIGHT:
                configureRightSidebar(slots);
                break;
            case SIDEBAR_MODES.BOTH:
                configureBothSidebars(slots);
                break;
        }

        // Configure full-width section below sidebars (if present)
        configureBelowSection(slots.below);

        // Store instance
        const instance = {
            container: container,
            mode: mode,
            slots: slots
        };
        instances.set(container, instance);

        return instance;
    }

    /**
     * Auto-initialize all sidebar layouts on the page
     *
     * Finds all .rsl-sidebar-auto containers and processes each one to apply
     * appropriate sidebar layout classes. Called automatically on DOM ready
     * and by the JSON Layout API after rendering.
     *
     * @returns {void}
     *
     * @example
     * // Called automatically, or manually for dynamic content:
     * autoInit();
     */
    function autoInit() {
        const sidebarContainers = document.querySelectorAll('.rsl-sidebar-auto');

        sidebarContainers.forEach(function(container) {
            createSidebarLayout(container);
        });
    }

    /**
     * Public API
     *
     * @namespace RSL.Sidebar
     * @property {Function} init - Initialize all sidebar layouts on the page
     * @property {Function} create - Create sidebar layout for specific container
     * @property {Map} instances - Map of initialized sidebar instances
     */
    window.RSL.Sidebar = {
        /**
         * Track initialized instances
         */
        instances: instances,

        /**
         * Initialize all sidebar layouts on the page
         *
         * Scans for all .rsl-sidebar-auto elements and initializes sidebar layouts.
         * This method is automatically called by the JSON Layout API after rendering.
         *
         * @returns {void}
         *
         * @example
         * // JSON API compatible - Initialize all instances:
         * RSL.Sidebar.init();
         */
        init: function() {
            autoInit();
        },

        /**
         * Create sidebar layout for a specific container
         *
         * @param {HTMLElement} container - The sidebar container element
         * @returns {Object} Instance object
         *
         * @example
         * const container = document.querySelector('.rsl-sidebar-auto');
         * RSL.Sidebar.create(container);
         */
        create: createSidebarLayout
    };

    /**
     * Auto-initialize on DOM ready or immediately if already loaded
     */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', autoInit);
    } else {
        autoInit();
    }

})();
