/**
 * VoidPage - Main application controller
 * Coordinates configuration loading, styling, and page initialization
 */

class VoidPage {
    constructor() {
        this.config = null;
        this.configLoader = null;
        this.styleParser = null;
        this.isInitialized = false;
    }

    /**
     * Initialize the VoidPage application
     */
    async init() {
        try {
            console.log('Initializing VoidPage...');
            
            // Import required modules
            await this.loadModules();
            
            // Load configuration
            await this.loadConfiguration();
            
            // Apply styles based on configuration
            await this.applyStyles();
            
            // Initialize page content
            this.initializePageContent();
            
            // Set up event listeners
            this.setupEventListeners();
            
            this.isInitialized = true;
            console.log('VoidPage initialized successfully');
            
        } catch (error) {
            console.error('Failed to initialize VoidPage:', error);
            this.handleInitializationError(error);
        }
    }

    /**
     * Load required modules dynamically
     */
    async loadModules() {
        try {
            // Import configLoader module
            const configModule = await import('./configLoader.js');
            this.configLoader = configModule.configLoader;
            
            // Import styleParser module
            const styleModule = await import('./styleParser.js');
            this.styleParser = styleModule.styleParser;
            
            console.log('Modules loaded successfully');
        } catch (error) {
            console.error('Failed to load modules:', error);
            throw new Error('Module loading failed');
        }
    }

    /**
     * Load and parse configuration
     */
    async loadConfiguration() {
        try {
            this.config = await this.configLoader.loadConfig();
            
            // Make config globally available for other scripts
            window.VOID_CONFIG = this.config;
            
            console.log('Configuration loaded:', this.config);
        } catch (error) {
            console.error('Failed to load configuration:', error);
            throw new Error('Configuration loading failed');
        }
    }

    /**
     * Apply styles based on configuration
     */
    async applyStyles() {
        try {
            if (!this.config) {
                throw new Error('Configuration not loaded');
            }
            
            const success = this.styleParser.applyConfigStyles(this.config);
            if (!success) {
                throw new Error('Style application failed');
            }
            
            console.log('Styles applied successfully');
        } catch (error) {
            console.error('Failed to apply styles:', error);
            // Don't throw - allow page to continue with default styles
        }
    }

    /**
     * Initialize page content based on configuration
     */
    initializePageContent() {
        try {
            const settings = this.config.settings;
            const cards = this.config.cards;
            
            // Set page title
            document.title = settings.title;
            
            // Create or update page header
            this.createPageHeader(settings);
            
            // Generate cards
            this.generateCards(cards);
            
            // Set up search functionality
            this.setupSearch(settings.searchEngine);
            
            console.log('Page content initialized');
        } catch (error) {
            console.error('Failed to initialize page content:', error);
        }
    }

    /**
     * Create page header
     */
    createPageHeader(settings) {
        let header = document.querySelector('.header');
        if (!header) {
            header = document.createElement('header');
            header.className = 'header';
            document.body.insertBefore(header, document.body.firstChild);
        }
        
        header.innerHTML = `
            <h1>${settings.title}</h1>
            <div class="search-container">
                <input type="text" id="search-input" placeholder="Search ${settings.searchEngine.name}...">
                <button id="search-button">Search</button>
            </div>
        `;
    }

    /**
     * Generate cards from configuration
     */
    generateCards(cards) {
        let container = document.querySelector('.cards-container');
        if (!container) {
            container = document.createElement('div');
            container.className = 'cards-container';
            document.body.appendChild(container);
        }
        
        // Clear existing cards
        container.innerHTML = '';
        
        cards.forEach(cardData => {
            const cardElement = this.createCardElement(cardData);
            container.appendChild(cardElement);
        });
    }

    /**
     * Create individual card element
     */
    createCardElement(cardData) {
        const card = document.createElement('div');
        card.className = 'card';
        
        const openInNewTab = this.config.settings.openLinksInNewTab;
        const targetAttr = openInNewTab ? 'target="_blank" rel="noopener noreferrer"' : '';
        
        card.innerHTML = `
            <div class="card-header">
                <div class="card-icon" style="background-image: url('${cardData.iconPath}')"></div>
                <h3 class="card-title">${cardData.title}</h3>
            </div>
            <div class="card-links">
                ${cardData.links.map(link => 
                    `<a href="${link.url}" class="card-link" ${targetAttr}>${link.name}</a>`
                ).join('')}
            </div>
        `;
        
        return card;
    }

    /**
     * Set up search functionality
     */
    setupSearch(searchEngine) {
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        
        if (!searchInput || !searchButton) return;
        
        const performSearch = () => {
            const query = searchInput.value.trim();
            if (query) {
                const searchUrl = searchEngine.url + encodeURIComponent(query);
                if (this.config.settings.openLinksInNewTab) {
                    window.open(searchUrl, '_blank', 'noopener,noreferrer');
                } else {
                    window.location.href = searchUrl;
                }
            }
        };
        
        searchButton.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }

    /**
     * Set up additional event listeners
     */
    setupEventListeners() {
        // Handle configuration updates
        window.addEventListener('configUpdated', (event) => {
            this.handleConfigUpdate(event.detail);
        });
        
        // Handle window resize for responsive behavior
        window.addEventListener('resize', () => {
            this.handleResize();
        });
    }

    /**
     * Handle configuration updates
     */
    handleConfigUpdate(newConfig) {
        console.log('Configuration updated, refreshing page...');
        this.config = newConfig;
        window.VOID_CONFIG = newConfig;
        
        // Reapply styles and content
        this.applyStyles();
        this.initializePageContent();
    }

    /**
     * Handle window resize
     */
    handleResize() {
        // Add any responsive behavior here
        console.log('Window resized');
    }

    /**
     * Handle initialization errors
     */
    handleInitializationError(error) {
        console.error('VoidPage initialization failed:', error);
        
        // Create error message for user
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.innerHTML = `
            <h2>Loading Error</h2>
            <p>Failed to load the page configuration. Please check the console for details.</p>
            <button onclick="location.reload()">Retry</button>
        `;
        
        document.body.appendChild(errorDiv);
    }

    /**
     * Get current configuration
     */
    getConfig() {
        return this.config;
    }

    /**
     * Check if page is initialized
     */
    isReady() {
        return this.isInitialized;
    }
}

// Create global VoidPage instance
const voidPage = new VoidPage();

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    voidPage.init();
});

// Make VoidPage globally available
window.VoidPage = VoidPage;
window.voidPage = voidPage;

// Export for module usage
// export { VoidPage, voidPage };