/**
 * Game Config Module
 * Loads engine metadata, locale, and asset roots before the UI is created.
 */
import { BaseModule } from './base-module.js';

class GameConfigModule extends BaseModule {
    constructor() {
        super('game-config', 'Game Config');
        this.dependencies = ['localization', 'persistence-manager'];
        this.config = null;

        this.bindMethods([
            'getConfig',
            'getMetadata',
            'getLocale',
            'loadConfig',
            'applyDocumentMetadata'
        ]);
    }

    async initialize() {
        try {
            this.reportProgress(20, 'Loading game configuration');
            this.config = await this.loadConfig();

            this.applyDocumentMetadata();
            document.dispatchEvent(new CustomEvent('game:config', {
                detail: this.config
            }));

            this.reportProgress(100, 'Game configuration ready');
            return true;
        } catch (error) {
            console.error('GameConfig: Failed to load game configuration:', error);
            this.config = {
                engine: 'unknown',
                locale: 'en_US',
                metadata: {
                    title: 'AI Interactive Fiction',
                    author: '',
                    subtitle: '',
                    version: '',
                    copyright: ''
                },
                assets: {
                    music: '/music/',
                    sfx: '/sounds/',
                    sounds: '/sounds/',
                    images: '/images/'
                }
            };
            this.applyDocumentMetadata();
            document.dispatchEvent(new CustomEvent('game:config', { detail: this.config }));
            this.reportProgress(100, 'Game configuration fallback ready');
            return true;
        }
    }

    async loadConfig() {
        const response = await fetch('/api/game-config', { cache: 'no-store' });
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return response.json();
    }

    applyDocumentMetadata() {
        const metadata = this.getMetadata();
        if (metadata?.title) {
            document.title = metadata.subtitle
                ? `${metadata.title} - ${metadata.subtitle}`
                : metadata.title;
        }
    }

    getConfig() {
        return this.config;
    }

    getMetadata() {
        return this.config?.metadata || {};
    }

    getLocale() {
        return this.config?.metadata?.language || this.config?.locale || 'en_US';
    }
}

const GameConfig = new GameConfigModule();

export { GameConfig };

if (window.moduleRegistry) {
    window.moduleRegistry.register(GameConfig);
}

window.GameConfig = GameConfig;
