/**
 * Configuration loader utility
 * Loads and parses the config.json file from the server
 */

class ConfigLoader {
    constructor() {
        this.config = null;
        this.configPath = '/src/config.json';
    }

    /**
     * Load configuration from the server
     * @returns {Promise<Object>} The parsed configuration object
     */
    async loadConfig() {
        try {
            const response = await fetch(this.configPath);
            
            if (!response.ok) {
                throw new Error(`Failed to load config: ${response.status} ${response.statusText}`);
            }
            
            const configText = await response.text();
            this.config = JSON.parse(configText);
            
            console.log('Configuration loaded successfully:', this.config);
            return this.config;
        } catch (error) {
            console.error('Error loading configuration:', error);
            throw error;
        }
    }

    /**
     * Get the loaded configuration
     * @returns {Object|null} The configuration object or null if not loaded
     */
    getConfig() {
        return this.config;
    }

    /**
     * Get a specific configuration value by key
     * @param {string} key - The configuration key
     * @param {*} defaultValue - Default value if key is not found
     * @returns {*} The configuration value
     */
    get(key, defaultValue = null) {
        if (!this.config) {
            console.warn('Configuration not loaded yet. Call loadConfig() first.');
            return defaultValue;
        }
        
        return this.config.hasOwnProperty(key) ? this.config[key] : defaultValue;
    }

    /**
     * Check if configuration is loaded
     * @returns {boolean} True if config is loaded
     */
    isLoaded() {
        return this.config !== null;
    }
}

// Create a global instance for easy access
const configLoader = new ConfigLoader();

// Alternative function-based approach for simpler usage
async function loadConfiguration() {
    try {
        const response = await fetch('/src/config.json');
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const config = await response.json();
        console.log('Configuration loaded:', config);
        return config;
    } catch (error) {
        console.error('Failed to load configuration:', error);
        throw error;
    }
}

// Export for module usage (if using ES6 modules)
// export { ConfigLoader, configLoader, loadConfiguration };

// For immediate use in browser without modules
window.ConfigLoader = ConfigLoader;
window.configLoader = configLoader;
window.loadConfiguration = loadConfiguration;