/**
 * AniWorld - Index Page Application Initializer
 *
 * Main entry point for the index page. Initializes all modules.
 *
 * Dependencies: All shared and index modules
 */

var AniWorld = window.AniWorld || {};

AniWorld.IndexApp = (function() {
    'use strict';

    let localization = null;

    /**
     * Initialize the index page application
     */
    async function init() {
        console.log('AniWorld Index App initializing...');

        // Initialize localization if available
        if (typeof Localization !== 'undefined') {
            localization = new Localization();
        }

        // Check authentication first
        const isAuthenticated = await AniWorld.Auth.checkAuth();
        if (!isAuthenticated) {
            return; // Auth module handles redirect
        }

        // Initialize theme
        AniWorld.Theme.init();

        // Initialize WebSocket connection
        AniWorld.WebSocketClient.init();

        // Initialize socket event handlers for this page
        AniWorld.IndexSocketHandler.init(localization);

        // Initialize page modules
        AniWorld.SeriesManager.init();
        AniWorld.SelectionManager.init();
        AniWorld.Search.init();
        AniWorld.ScanManager.init();
        AniWorld.ConfigManager.init();
        AniWorld.ContextMenu.init();

        // Bind global events
        bindGlobalEvents();

        // Load initial data
        await AniWorld.SeriesManager.loadSeries();

        console.log('AniWorld Index App initialized successfully');
    }

    /**
     * Bind global event handlers
     */
    function bindGlobalEvents() {
        // Theme toggle
        const themeToggle = document.getElementById('theme-toggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', function() {
                AniWorld.Theme.toggle();
            });
        }

        // Logout button
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', function() {
                AniWorld.Auth.logout(AniWorld.UI.showToast);
            });
        }
    }

    /**
     * Get localization instance
     */
    function getLocalization() {
        return localization;
    }

    // Public API
    return {
        init: init,
        getLocalization: getLocalization
    };
})();

// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    AniWorld.IndexApp.init();
});

// Expose app globally for inline event handlers (backwards compatibility)
window.app = {
    addSeries: function(link, name) {
        return AniWorld.Search.addSeries(link, name);
    }
};
