/**
 * I18N Manager - Unified Translation Management
 *
 * Single point of truth for all translations.
 * Fetches from server endpoint /eskaera/i18n once and caches.
 *
 * Usage:
 *   i18nManager.init().then(function() {
 *       var translated = i18nManager.get('product');  // Returns translated string
 *       var allLabels = i18nManager.getAll();         // Returns all labels
 *   });
 *
 * Copyright 2025 Criptomart
 * License AGPL-3.0 or later
 */

(function () {
    "use strict";

    window.i18nManager = {
        labels: null,
        initialized: false,
        initPromise: null,

        /**
         * Initialize by fetching translations from server
         * Returns a Promise that resolves when translations are loaded
         */
        init: function () {
            if (this.initialized) {
                return Promise.resolve();
            }

            if (this.initPromise) {
                return this.initPromise;
            }

            var self = this;

            // Detect user's language from document or fallback to en_US
            var detectedLang = document.documentElement.lang || "es_ES";
            console.log("[i18nManager] Detected language:", detectedLang);

            // Fetch translations from server
            this.initPromise = fetch("/eskaera/i18n", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ lang: detectedLang }),
            })
                .then(function (response) {
                    if (!response.ok) {
                        throw new Error("HTTP error, status = " + response.status);
                    }
                    return response.json();
                })
                .then(function (data) {
                    // Handle JSON-RPC response format
                    // Server returns: { "jsonrpc": "2.0", "id": null, "result": { labels } }
                    // Extract the actual labels from the result property
                    var labels = data.result || data;

                    console.log(
                        "[i18nManager] ✓ Loaded",
                        Object.keys(labels).length,
                        "translation labels"
                    );
                    self.labels = labels;
                    self.initialized = true;
                    return labels;
                })
                .catch(function (error) {
                    console.error("[i18nManager] Error loading translations:", error);
                    // Fallback to empty object so app doesn't crash
                    self.labels = {};
                    self.initialized = true;
                    return {};
                });

            return this.initPromise;
        },

        /**
         * Get a specific translation label
         * Returns the translated string or the key if not found
         */
        get: function (key) {
            if (!this.initialized) {
                console.warn("[i18nManager] Not yet initialized. Call init() first.");
                return key;
            }
            return this.labels[key] || key;
        },

        /**
         * Get all translation labels as object
         */
        getAll: function () {
            if (!this.initialized) {
                console.warn("[i18nManager] Not yet initialized. Call init() first.");
                return {};
            }
            return this.labels;
        },

        /**
         * Check if a specific label exists
         */
        has: function (key) {
            if (!this.initialized) return false;
            return key in this.labels;
        },

        /**
         * Format currency to Euro format
         */
        formatCurrency: function (amount) {
            try {
                return new Intl.NumberFormat(document.documentElement.lang || "es_ES", {
                    style: "currency",
                    currency: "EUR",
                }).format(amount);
            } catch (e) {
                // Fallback to simple Euro format
                return "€" + parseFloat(amount).toFixed(2);
            }
        },

        /**
         * Escape HTML to prevent XSS
         */
        escapeHtml: function (text) {
            if (!text) return "";
            var div = document.createElement("div");
            div.textContent = text;
            return div.innerHTML;
        },
    };

    // Auto-initialize on DOM ready
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", function () {
            i18nManager.init().catch(function (err) {
                console.error("[i18nManager] Auto-init failed:", err);
            });
        });
    } else {
        // DOM already loaded
        setTimeout(function () {
            i18nManager.init().catch(function (err) {
                console.error("[i18nManager] Auto-init failed:", err);
            });
        }, 100);
    }
})();
