/**
 * Style Parser and Applicator
 * Builds and applies CSS stylesheets based on configuration values
 */

class StyleParser {
    constructor() {
        this.dynamicStyleElement = null;
        this.cssVariablesApplied = false;
    }

    /**
     * Build CSS stylesheet text from configuration
     * @param {Object} config - The parsed configuration object
     * @returns {string} Complete CSS stylesheet text
     */
    buildStylesheet(config) {
        const { settings, cards } = config;
        
        let css = `
/* Dynamic stylesheet generated from config.json */

/* Root CSS Variables */
:root {
    --bg-image: url('${settings.backgroundImgPath}');
    --header-bg-color: ${settings.headerBgColor};
    --header-outline-color: ${settings.headerOutlineColor};
    --header-outline-thickness: ${settings.headerOutlineThickness}px;
    --card-bg-color: ${settings.cardBgColor};
    --corner-radius: ${settings.cornerRadius}px;
}

/* Body and Background */
body {
    background-image: var(--bg-image);
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
}

/* Header Styles */
.header,
header {
    background-color: var(--header-bg-color);
    border: var(--header-outline-thickness) solid var(--header-outline-color);
    border-radius: var(--corner-radius);
}

/* Card Styles */
.card {
    background-color: var(--card-bg-color);
    border-radius: var(--corner-radius);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
}

/* Card Container */
.cards-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    padding: 20px;
}

/* Link Target Behavior */
`;

        // Add link target behavior based on config
        if (settings.openLinksInNewTab) {
            css += `
.card a {
    target: _blank;
}
`;
        }

        // Add card-specific styles if needed
        cards.forEach((card, index) => {
            if (card.iconPath) {
                css += `
.card:nth-child(${index + 1}) .card-icon {
    background-image: url('${card.iconPath}');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}
`;
            }
        });

        css += `
/* Card Icons */
.card-icon {
    width: 32px;
    height: 32px;
    display: inline-block;
    margin-right: 10px;
}

/* Responsive Design */
@media (max-width: 768px) {
    .cards-container {
        grid-template-columns: 1fr;
        padding: 10px;
    }
    
    .card {
        margin-bottom: 15px;
    }
}
`;

        return css;
    }

    /**
     * Apply CSS variables to document root
     * @param {Object} settings - Configuration settings object
     */
    applyCSSVariables(settings) {
        const root = document.documentElement;
        
        root.style.setProperty('--bg-image', `url('${settings.backgroundImgPath}')`);
        root.style.setProperty('--header-bg-color', settings.headerBgColor);
        root.style.setProperty('--header-outline-color', settings.headerOutlineColor);
        root.style.setProperty('--header-outline-thickness', `${settings.headerOutlineThickness}px`);
        root.style.setProperty('--card-bg-color', settings.cardBgColor);
        root.style.setProperty('--corner-radius', `${settings.cornerRadius}px`);
        
        this.cssVariablesApplied = true;
        console.log('CSS variables applied to document root');
    }

    /**
     * Create and inject dynamic stylesheet into document head
     * @param {string} cssText - CSS stylesheet text
     * @returns {HTMLStyleElement} The created style element
     */
    injectStylesheet(cssText) {
        // Remove existing dynamic stylesheet if present
        this.removeDynamicStylesheet();
        
        // Create new style element
        this.dynamicStyleElement = document.createElement('style');
        this.dynamicStyleElement.type = 'text/css';
        this.dynamicStyleElement.id = 'dynamic-config-styles';
        this.dynamicStyleElement.textContent = cssText;
        
        // Inject into document head
        document.head.appendChild(this.dynamicStyleElement);
        
        console.log('Dynamic stylesheet injected');
        return this.dynamicStyleElement;
    }

    /**
     * Remove the dynamic stylesheet from document
     */
    removeDynamicStylesheet() {
        if (this.dynamicStyleElement) {
            this.dynamicStyleElement.remove();
            this.dynamicStyleElement = null;
            console.log('Dynamic stylesheet removed');
        }
    }

    /**
     * Apply link target behavior to existing links
     * @param {boolean} openInNewTab - Whether to open links in new tab
     */
    applyLinkTargetBehavior(openInNewTab) {
        const links = document.querySelectorAll('.card a, .card-link');
        
        links.forEach(link => {
            if (openInNewTab) {
                link.setAttribute('target', '_blank');
                link.setAttribute('rel', 'noopener noreferrer');
            } else {
                link.removeAttribute('target');
                link.removeAttribute('rel');
            }
        });
        
        console.log(`Link target behavior applied: ${openInNewTab ? 'new tab' : 'same tab'}`);
    }

    /**
     * Complete style application from configuration
     * @param {Object} config - The complete configuration object
     */
    applyConfigStyles(config) {
        try {
            // Build and inject stylesheet
            const cssText = this.buildStylesheet(config);
            this.injectStylesheet(cssText);
            
            // Apply CSS variables
            this.applyCSSVariables(config.settings);
            
            // Apply link behavior
            this.applyLinkTargetBehavior(config.settings.openLinksInNewTab);
            
            console.log('All configuration styles applied successfully');
            return true;
        } catch (error) {
            console.error('Error applying configuration styles:', error);
            return false;
        }
    }

    /**
     * Update specific style property
     * @param {string} property - CSS property name
     * @param {string} value - CSS property value
     */
    updateStyleProperty(property, value) {
        const root = document.documentElement;
        const cssVarName = `--${property.replace(/([A-Z])/g, '-$1').toLowerCase()}`;
        root.style.setProperty(cssVarName, value);
        console.log(`Updated ${cssVarName}: ${value}`);
    }

    /**
     * Get current dynamic stylesheet text
     * @returns {string|null} Current stylesheet text or null if not applied
     */
    getCurrentStylesheet() {
        return this.dynamicStyleElement ? this.dynamicStyleElement.textContent : null;
    }

    /**
     * Check if styles are currently applied
     * @returns {boolean} True if dynamic styles are active
     */
    isStylesApplied() {
        return this.dynamicStyleElement !== null && this.cssVariablesApplied;
    }
}

// Create global instance
const styleParser = new StyleParser();

// Utility functions for external access
function applyConfigurationStyles(config) {
    return styleParser.applyConfigStyles(config);
}

function buildStylesheetFromConfig(config) {
    return styleParser.buildStylesheet(config);
}

function updateStyleProperty(property, value) {
    return styleParser.updateStyleProperty(property, value);
}

function removeConfigurationStyles() {
    return styleParser.removeDynamicStylesheet();
}

// Export for module usage
// export { StyleParser, styleParser, applyConfigurationStyles, buildStylesheetFromConfig };

// Global access
window.StyleParser = StyleParser;
window.styleParser = styleParser;
window.applyConfigurationStyles = applyConfigurationStyles;
window.buildStylesheetFromConfig = buildStylesheetFromConfig;
window.updateStyleProperty = updateStyleProperty;
window.removeConfigurationStyles = removeConfigurationStyles;