/**
 * Firebase Configuration
 * Fetches configuration dynamically from the database and initializes Firebase
 */

(function() {
    'use strict';

    // Wait for DOM to be ready before starting
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initFirebase);
    } else {
        initFirebase();
    }

    function initFirebase() {
    // Determine the correct API path based on script location
    let apiPath = '../api/get_firebase_config.php';
    if (document.currentScript && document.currentScript.src) {
        const scriptSrc = document.currentScript.src;
        if (scriptSrc.includes('admin/includes/')) {
            apiPath = scriptSrc.substring(0, scriptSrc.indexOf('admin/includes/')) + 'api/get_firebase_config.php';
        }
    }

    console.log("[Firebase] Fetching config from:", apiPath);

    // Global timeout for config fetch
    const CONFIG_TIMEOUT = 10000; // 10 seconds

    function dispatchFirebaseReady(detail) {
        // Small delay to ensure listener is attached
        setTimeout(() => {
            document.dispatchEvent(new CustomEvent('firebase-ready', {
                detail: detail
            }));
        }, 100);
    }

    function validateConfig(config) {
        const errors = [];
        const warnings = [];

        // Required fields
        if (!config.apiKey || config.apiKey.includes('YOUR_') || config.apiKey.length < 20) {
            errors.push('apiKey is missing or appears to be a placeholder');
        }

        if (!config.projectId || config.projectId.includes('YOUR_') || config.projectId.includes('example')) {
            errors.push('projectId is missing or appears to be a placeholder');
        }

        if (!config.databaseURL || config.databaseURL.includes('YOUR_') || config.databaseURL.includes('example.com')) {
            errors.push('databaseURL is missing or appears to be a placeholder');
        }

        // Warnings for optional but recommended fields
        if (!config.authDomain) warnings.push('authDomain is not set');
        if (!config.storageBucket) warnings.push('storageBucket is not set');
        if (!config.messagingSenderId) warnings.push('messagingSenderId is not set');
        if (!config.appId) warnings.push('appId is not set');

        return { errors, warnings, isValid: errors.length === 0 };
    }

    function initializeFirebase(config) {
        if (typeof firebase === 'undefined') {
            console.error("[Firebase] SDK not loaded. Please ensure firebase-app-compat.js is included before this script.");
            dispatchFirebaseReady({
                success: false,
                error: 'Firebase SDK not loaded',
                code: 'SDK_MISSING'
            });
            return;
        }

        // Check if already initialized
        if (firebase.apps.length > 0) {
            console.log("[Firebase] Already initialized (Apps count: " + firebase.apps.length + ")");
            dispatchFirebaseReady({
                config: config,
                isValid: true,
                alreadyInitialized: true
            });
            return;
        }

        try {
            firebase.initializeApp(config);
            console.log("[Firebase] Initialized successfully with Project ID:", config.projectId);
            console.log("[Firebase] Database URL:", config.databaseURL);

            // Test database connection
            const database = firebase.database();
            const connectedRef = database.ref('.info/connected');

            connectedRef.once('value').then((snap) => {
                if (snap.val() === true) {
                    console.log("[Firebase] Successfully connected to Realtime Database");
                } else {
                    console.warn("[Firebase] Connected to Firebase but Realtime Database may be unavailable");
                }
            }).catch((err) => {
                console.warn("[Firebase] Could not verify database connection:", err.message);
            });

            dispatchFirebaseReady({
                config: config,
                isValid: true
            });

        } catch (e) {
            console.error("[Firebase] Initialization error:", e);
            dispatchFirebaseReady({
                success: false,
                error: e.message,
                code: 'INIT_ERROR'
            });
        }
    }

    // Fetch with timeout
    const fetchController = new AbortController();
    const timeoutId = setTimeout(() => {
        fetchController.abort();
    }, CONFIG_TIMEOUT);

    fetch(apiPath, { signal: fetchController.signal })
        .then(res => {
            clearTimeout(timeoutId);
            if (!res.ok) {
                throw new Error("HTTP error " + res.status + " - " + res.statusText);
            }
            return res.json();
        })
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'API returned unsuccessful response');
            }

            const config = data.config;
            console.log("[Firebase] Config received:", {
                projectId: config.projectId,
                authDomain: config.authDomain,
                databaseURL: config.databaseURL ? '***' : 'missing',
                hasApiKey: !!config.apiKey,
                hasAppId: !!config.appId
            });

            // Validate configuration
            const validation = validateConfig(config);

            if (validation.errors.length > 0) {
                console.error("[Firebase] Configuration errors:", validation.errors);
                dispatchFirebaseReady({
                    config: config,
                    isValid: false,
                    errors: validation.errors,
                    warnings: validation.warnings,
                    code: 'CONFIG_INVALID'
                });
                return;
            }

            if (validation.warnings.length > 0) {
                console.warn("[Firebase] Configuration warnings:", validation.warnings);
            }

            // Initialize Firebase
            initializeFirebase(config);
        })
        .catch(err => {
            clearTimeout(timeoutId);

            if (err.name === 'AbortError') {
                console.error("[Firebase] Config fetch timed out after " + (CONFIG_TIMEOUT/1000) + "s");
                dispatchFirebaseReady({
                    success: false,
                    error: 'Configuration fetch timed out. Check your network connection.',
                    code: 'TIMEOUT'
                });
            } else {
                console.error("[Firebase] Error fetching config:", err);
                dispatchFirebaseReady({
                    success: false,
                    error: err.message,
                    code: 'FETCH_ERROR'
                });
            }
        });
    }
})();
