/**
 * RSL Footer Runtime
 *
 * Runtime renderer for RSL footers. Converts FooterConfig JSON to semantic HTML
 * with full accessibility support.
 *
 * @fileoverview Footer rendering and behavior module
 * @version 1.0.0
 * @license MIT
 *
 * Usage:
 * RSL.FooterRuntime.render('#footer-container', config);
 *
 * // Or initialize from existing data attribute
 * <div data-rsl-footer='{"sections": [...]}'>
 * RSL.FooterRuntime.init();
 */

(function() {
    'use strict';

    window.RSL = window.RSL || {};

    // ============================================
    // FooterRuntime Module
    // ============================================

    const FooterRuntime = {

        /**
         * Initialize all footers with data-rsl-footer attribute
         */
        init: function() {
            const footers = document.querySelectorAll('[data-rsl-footer]');
            footers.forEach(container => {
                const configAttr = container.getAttribute('data-rsl-footer');
                if (configAttr) {
                    try {
                        const config = JSON.parse(configAttr);
                        this.render(container, config);
                    } catch (e) {
                        console.error('FooterRuntime: Invalid JSON in data-rsl-footer', e);
                    }
                }
            });
        },

        /**
         * Render a footer from configuration
         * @param {HTMLElement|string} container - Container element or selector
         * @param {Object} config - FooterConfig object
         * @returns {HTMLElement} - The rendered footer element
         */
        render: function(container, config) {
            const containerEl = typeof container === 'string'
                ? document.querySelector(container)
                : container;

            if (!containerEl) {
                console.error('FooterRuntime: Container not found');
                return null;
            }

            // Clear container
            containerEl.innerHTML = '';

            // Create footer element
            const footer = this._createFooterElement(config);

            // Append to container
            containerEl.appendChild(footer);

            // Initialize any interactive behaviors
            this._initBehaviors(footer, config);

            return footer;
        },

        /**
         * Generate HTML string from config (for SSR or string output)
         * @param {Object} config - FooterConfig object
         * @returns {string} - HTML string
         */
        toHTML: function(config) {
            const footer = this._createFooterElement(config);
            return footer.outerHTML;
        },

        // ============================================
        // Private Methods
        // ============================================

        /**
         * Create the main footer element
         */
        _createFooterElement: function(config) {
            const footer = document.createElement('footer');
            footer.className = 'rsl-footer';

            // Theme variant
            if (config.theme?.variant === 'light') {
                footer.classList.add('rsl-footer-light');
            } else if (config.theme?.variant === 'auto') {
                footer.classList.add('rsl-footer-auto');
            }

            // Divider above
            if (config.theme?.showDividerAbove) {
                footer.classList.add('rsl-footer-divider-above');
            }

            // Custom theme colors via CSS variables
            if (config.theme?.variant === 'custom' && config.theme?.colors) {
                const colors = config.theme.colors;
                const footerId = 'rsl-footer-' + Date.now();
                footer.id = footerId;

                // Create a scoped style element with high specificity
                const styleEl = document.createElement('style');
                styleEl.textContent = `
                    #${footerId}.rsl-footer {
                        ${colors.background ? `--rsl-footer-bg: ${colors.background}; background: ${colors.background};` : ''}
                        ${colors.text ? `--rsl-footer-text: ${colors.text}; color: ${colors.text};` : ''}
                        ${colors.textMuted ? `--rsl-footer-text-muted: ${colors.textMuted};` : ''}
                        ${colors.heading ? `--rsl-footer-heading: ${colors.heading};` : ''}
                        ${colors.link ? `--rsl-footer-link: ${colors.link};` : ''}
                        ${colors.linkHover ? `--rsl-footer-link-hover: ${colors.linkHover};` : ''}
                        ${colors.buttonBg ? `--rsl-footer-btn-bg: ${colors.buttonBg};` : ''}
                        ${colors.buttonHover ? `--rsl-footer-btn-hover: ${colors.buttonHover};` : ''}
                        ${colors.buttonText ? `--rsl-footer-btn-text: ${colors.buttonText};` : ''}
                        ${colors.border ? `--rsl-footer-border: ${colors.border};` : ''}
                    }
                    #${footerId} .rsl-footer-heading {
                        ${colors.heading ? `color: ${colors.heading} !important;` : ''}
                    }
                    #${footerId} .rsl-footer-nav-link,
                    #${footerId} .rsl-footer-social-link,
                    #${footerId} .rsl-footer-legal-link,
                    #${footerId} a {
                        ${colors.link ? `color: ${colors.link};` : ''}
                    }
                    #${footerId} .rsl-footer-nav-link:hover,
                    #${footerId} .rsl-footer-social-link:hover,
                    #${footerId} .rsl-footer-legal-link:hover,
                    #${footerId} a:hover {
                        ${colors.linkHover ? `color: ${colors.linkHover};` : ''}
                    }
                    #${footerId} p,
                    #${footerId} .rsl-footer-text {
                        ${colors.text ? `color: ${colors.text};` : ''}
                    }
                    #${footerId} .rsl-footer-legal-text,
                    #${footerId} .rsl-footer-muted {
                        ${colors.textMuted ? `color: ${colors.textMuted};` : ''}
                    }
                    #${footerId} .rsl-footer-button,
                    #${footerId} button[type="submit"] {
                        ${colors.buttonBg ? `background: ${colors.buttonBg} !important;` : ''}
                        ${colors.buttonText ? `color: ${colors.buttonText} !important;` : ''}
                    }
                    #${footerId} .rsl-footer-button:hover,
                    #${footerId} button[type="submit"]:hover {
                        ${colors.buttonHover ? `background: ${colors.buttonHover} !important;` : ''}
                    }
                    #${footerId} .rsl-footer-section {
                        ${colors.border ? `border-color: ${colors.border};` : ''}
                    }
                `;
                footer.appendChild(styleEl);
            }

            // ARIA label
            if (config.ariaLabel) {
                footer.setAttribute('aria-label', config.ariaLabel);
            }

            // Render sections
            (config.sections || []).forEach(section => {
                const sectionEl = this._createSectionElement(section);
                footer.appendChild(sectionEl);
            });

            return footer;
        },

        /**
         * Create a section element
         */
        _createSectionElement: function(section) {
            const sectionEl = document.createElement('section');
            sectionEl.className = 'rsl-footer-section';

            if (section.layout === 'inline') {
                sectionEl.classList.add('rsl-footer-section-inline');
            }

            if (section.ariaLabel) {
                sectionEl.setAttribute('aria-label', section.ariaLabel);
            }

            // Columns container
            const columnsEl = document.createElement('div');
            columnsEl.className = 'rsl-footer-columns';

            (section.columns || []).forEach(column => {
                const columnEl = this._createColumnElement(column);
                columnsEl.appendChild(columnEl);
            });

            sectionEl.appendChild(columnsEl);
            return sectionEl;
        },

        /**
         * Create a column element
         */
        _createColumnElement: function(column) {
            const columnEl = document.createElement('div');
            columnEl.className = 'rsl-footer-col';

            // Width class
            if (column.width && column.width !== 'auto') {
                const widthClass = 'rsl-footer-col-' + column.width.replace('/', '-');
                columnEl.classList.add(widthClass);
            }

            // Render blocks
            (column.blocks || []).forEach(block => {
                const blockEl = this._createBlockElement(block);
                columnEl.appendChild(blockEl);
            });

            return columnEl;
        },

        /**
         * Create a block element based on type
         */
        _createBlockElement: function(block) {
            switch (block.type) {
                case 'logo':
                    return this._createLogoBlock(block);
                case 'nav':
                    return this._createNavBlock(block);
                case 'text':
                    return this._createTextBlock(block);
                case 'social':
                    return this._createSocialBlock(block);
                case 'legal':
                    return this._createLegalBlock(block);
                case 'newsletter':
                    return this._createNewsletterBlock(block);
                case 'badgeRow':
                    return this._createBadgeRowBlock(block);
                case 'customHtml':
                    return this._createCustomHtmlBlock(block);
                default:
                    return this._createUnknownBlock(block);
            }
        },

        /**
         * Logo block
         */
        _createLogoBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-logo';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            if (block.imageSrc) {
                // Logo image
                const img = document.createElement('img');
                img.src = block.imageSrc;
                img.alt = block.imageAlt || '';

                if (block.href) {
                    const link = document.createElement('a');
                    link.href = block.href;
                    link.className = 'rsl-footer-logo-link';
                    link.appendChild(img);
                    container.appendChild(link);
                } else {
                    container.appendChild(img);
                }
            } else if (block.companyName) {
                // Text-based brand name (when no image)
                const brandName = document.createElement('span');
                brandName.className = 'rsl-footer-brand-name';
                brandName.textContent = block.companyName;

                if (block.href) {
                    const link = document.createElement('a');
                    link.href = block.href;
                    link.className = 'rsl-footer-logo-link';
                    link.appendChild(brandName);
                    container.appendChild(link);
                } else {
                    container.appendChild(brandName);
                }
            }

            // Tagline/description
            if (block.tagline) {
                const tagline = document.createElement('p');
                tagline.className = 'rsl-footer-tagline';
                tagline.textContent = block.tagline;
                container.appendChild(tagline);
            }

            return container;
        },

        /**
         * Navigation block
         */
        _createNavBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-nav';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            const list = document.createElement('ul');
            list.className = 'rsl-footer-nav-list';
            if (block.layout === 'inline') {
                list.classList.add('rsl-footer-nav-inline');
            }

            (block.links || []).forEach(link => {
                const li = document.createElement('li');
                const a = document.createElement('a');
                a.href = link.href || '#';
                a.className = 'rsl-footer-nav-link';
                a.textContent = link.label;

                if (link.meta?.target === '_blank') {
                    a.target = '_blank';
                    a.rel = 'noopener noreferrer';
                }

                li.appendChild(a);
                list.appendChild(li);
            });

            container.appendChild(list);
            return container;
        },

        /**
         * Text block
         */
        _createTextBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-text';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            if (block.html) {
                const content = document.createElement('div');
                content.innerHTML = block.html;
                container.appendChild(content);
            }

            return container;
        },

        /**
         * Social links block
         */
        _createSocialBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-social';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            const list = document.createElement('ul');
            list.className = 'rsl-footer-social-list';
            if (block.layout === 'grid') {
                list.classList.add('rsl-footer-social-grid');
            }

            (block.links || []).forEach(link => {
                const li = document.createElement('li');
                const a = document.createElement('a');
                a.href = link.href || '#';
                a.className = 'rsl-footer-social-link';
                a.target = '_blank';
                a.rel = 'noopener noreferrer';

                // Icon
                const icon = document.createElement('span');
                icon.className = link.icon || 'fas fa-link';
                icon.setAttribute('aria-hidden', 'true');
                a.appendChild(icon);

                // Screen reader text
                const srText = document.createElement('span');
                srText.className = 'sr-only';
                srText.textContent = link.label;
                a.appendChild(srText);

                li.appendChild(a);
                list.appendChild(li);
            });

            container.appendChild(list);
            return container;
        },

        /**
         * Legal block
         */
        _createLegalBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-legal';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            if (block.text) {
                const text = document.createElement('p');
                text.className = 'rsl-footer-legal-text';
                text.textContent = block.text;
                container.appendChild(text);
            }

            if (block.links && block.links.length > 0) {
                const list = document.createElement('ul');
                list.className = 'rsl-footer-legal-links';

                block.links.forEach(link => {
                    const li = document.createElement('li');
                    const a = document.createElement('a');
                    a.href = link.href || '#';
                    a.textContent = link.label;

                    if (link.meta?.target === '_blank') {
                        a.target = '_blank';
                        a.rel = 'noopener noreferrer';
                    }

                    li.appendChild(a);
                    list.appendChild(li);
                });

                container.appendChild(list);
            }

            return container;
        },

        /**
         * Newsletter block
         */
        _createNewsletterBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-newsletter';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            if (block.description) {
                const desc = document.createElement('p');
                desc.textContent = block.description;
                container.appendChild(desc);
            }

            // Form
            const form = document.createElement('form');
            form.className = 'rsl-footer-newsletter-form';
            form.action = block.formAction || '#';
            form.method = block.method || 'POST';

            // Label (visually hidden)
            const label = document.createElement('label');
            label.className = 'rsl-footer-label sr-only';
            label.setAttribute('for', 'footer-newsletter-email');
            label.textContent = 'Email address';
            form.appendChild(label);

            // Input group
            const inputGroup = document.createElement('div');
            inputGroup.className = 'rsl-footer-input-group';

            const input = document.createElement('input');
            input.type = 'email';
            input.id = 'footer-newsletter-email';
            input.name = block.emailFieldName || 'email';
            input.className = 'rsl-footer-input';
            input.placeholder = 'Enter your email';
            input.required = true;
            input.autocomplete = 'email';
            inputGroup.appendChild(input);

            const button = document.createElement('button');
            button.type = 'submit';
            button.className = 'rsl-footer-button';
            button.textContent = block.submitLabel || 'Subscribe';
            inputGroup.appendChild(button);

            form.appendChild(inputGroup);
            container.appendChild(form);

            return container;
        },

        /**
         * Badge row block
         */
        _createBadgeRowBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-badges';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            const list = document.createElement('ul');
            list.className = 'rsl-footer-badge-list';

            (block.badges || []).forEach(badge => {
                const li = document.createElement('li');

                if (badge.imgSrc) {
                    const img = document.createElement('img');
                    img.src = badge.imgSrc;
                    img.alt = badge.imgAlt || badge.label || '';

                    if (badge.href) {
                        const a = document.createElement('a');
                        a.href = badge.href;
                        a.className = 'rsl-footer-badge-link';
                        a.appendChild(img);
                        li.appendChild(a);
                    } else {
                        li.appendChild(img);
                    }
                }

                list.appendChild(li);
            });

            container.appendChild(list);
            return container;
        },

        /**
         * Custom HTML block
         */
        _createCustomHtmlBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block rsl-footer-block-custom';

            if (block.title) {
                const heading = document.createElement('h2');
                heading.className = 'rsl-footer-heading';
                heading.textContent = block.title;
                container.appendChild(heading);
            }

            if (block.html) {
                const content = document.createElement('div');
                content.innerHTML = block.html;
                container.appendChild(content);
            }

            return container;
        },

        /**
         * Unknown block type fallback
         */
        _createUnknownBlock: function(block) {
            const container = document.createElement('div');
            container.className = 'rsl-footer-block';
            container.textContent = `[Unknown block type: ${block.type}]`;
            return container;
        },

        /**
         * Initialize interactive behaviors
         */
        _initBehaviors: function(footer, config) {
            // Newsletter form submission handling (if needed)
            const newsletterForms = footer.querySelectorAll('.rsl-footer-newsletter-form');
            newsletterForms.forEach(form => {
                // Add any client-side validation or AJAX submission here
                // For now, let forms submit normally
            });

            // Mobile accordion behavior (optional)
            // Only enable if viewport is narrow and config specifies accordion
            if (this._isMobile() && config.mobileAccordion) {
                this._initMobileAccordion(footer);
            }
        },

        /**
         * Check if viewport is mobile-sized
         */
        _isMobile: function() {
            return window.innerWidth < 768;
        },

        /**
         * Initialize mobile accordion behavior
         */
        _initMobileAccordion: function(footer) {
            footer.classList.add('rsl-footer-accordion');

            const headings = footer.querySelectorAll('.rsl-footer-heading');
            headings.forEach(heading => {
                const content = heading.nextElementSibling;
                if (!content) return;

                // Make heading clickable
                heading.setAttribute('role', 'button');
                heading.setAttribute('tabindex', '0');
                heading.setAttribute('aria-expanded', 'true');

                // Wrap content for accordion
                const wrapper = document.createElement('div');
                wrapper.className = 'rsl-footer-accordion-content';
                content.parentNode.insertBefore(wrapper, content);
                wrapper.appendChild(content);

                // Click handler
                heading.addEventListener('click', () => {
                    const expanded = heading.getAttribute('aria-expanded') === 'true';
                    heading.setAttribute('aria-expanded', String(!expanded));
                });

                // Keyboard handler
                heading.addEventListener('keydown', (e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        heading.click();
                    }
                });
            });
        }
    };

    // Export to RSL namespace
    window.RSL.FooterRuntime = FooterRuntime;

    // Auto-initialize on DOMContentLoaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            FooterRuntime.init();
        });
    } else {
        FooterRuntime.init();
    }

})();
