/**
 * Mengisi textContent elemen berdasarkan key lokal dari i18next.
 *
 * @param {Object} elementMap - Map dari nilai atribut ke key i18n. Contoh: { h_dashboard: "h_dashboard" }
 * @param {string} attrKey - Nama atribut yang digunakan, misalnya "data-header-element" atau "data-dashboard-element"
 * @param {string} namespace - Namespace i18next yang aktif, misalnya "header" atau "dashboard"
 */

export function initDynamicLanguageHandler(namespaces) {
  if (!Array.isArray(namespaces)) return;

  // Pemetaan fungsi per namespace
  const namespaceHandlers = {
    header: () => typeof updateHeader === "function" && updateHeader(),
    dashboard: () => translatePage("dashboard"),
    dropzone: () => translatePage("dropzone"),
    supplier: () => translatePage("supplier"),
    // tambahkan lainnya jika perlu
  };

  // Fungsi gabungan untuk update
  const langUpdateCallback = () => {
    namespaces.forEach((ns) => {
      if (namespaceHandlers[ns]) {
        try {
          namespaceHandlers[ns]();
        } catch (e) {
          console.error(`❌ Error updating namespace '${ns}':`, e);
        }
      }
    });
  };

  // Panggil langsung saat halaman ready
  langUpdateCallback();

  // Daftarkan supaya dipanggil ulang saat language berubah
  addLangCallback(langUpdateCallback);
}

export function addLangCallback(fn) {
  window.onLanguageChangeCallbacks = window.onLanguageChangeCallbacks || [];
  if (
    typeof fn === "function" &&
    !window.onLanguageChangeCallbacks.includes(fn)
  ) {
    window.onLanguageChangeCallbacks.push(fn);
  }
}

/**
 * Menerjemahkan elemen-elemen untuk halaman tertentu
 * berdasarkan peta atribut dan namespace yang relevan.
 *
 * @param {string} page - Nama halaman, seperti "dashboard", "profile"
 */
export function translatePage(page) {
  const pageMap = {
    dashboard: {
      map: {
        h_dashboard: "h_dashboard",
        user_no_link: "user_no_link",
        user_belum_anggota: "user_belum_anggota",
        welcome_msg: "welcome_msg",
        anggota_terhubung: "anggota_terhubung",
        absensi_masuk_hari_ini: "absensi_masuk_hari_ini",
        absensi_pulang_hari_ini: "absensi_pulang_hari_ini",
        total_uploaded: "total_uploaded",
        total_waiting: "total_waiting",
        total_approved: "total_approved",
        total_rejected: "total_rejected",
      },
      attr: "data-dashboard-element",
      namespace: "dashboard",
    },

    dropzone: {
      map: {
        upload_drop_here: "upload_drop_here",
        upload_limit_files: "upload_limit_files",
        upload_allowed_ext: "upload_allowed_ext",
      },
      attr: "data-dropzone-element",
      namespace: "dropzone",
    },

    supplier: {
      map: {
        search_input: { key: "search_placeholder", attr: "placeholder" },
        filter_status: {
          key: "filter_status",
          type: "select_options",
          options: [
            { value: " ", labelKey: "all" },
            { value: "1", labelKey: "approved" },
            { value: "2", labelKey: "rejected" },
            { value: "0", labelKey: "waiting" },
          ],
        },
        btn_register_supplier: "btn_register_supplier",
      },
      attr: "data-supplier-element",
      namespace: "supplier",
    },

    // Tambahkan page lain di sini
  };

  const config = pageMap[page.toLowerCase()];
  if (!config) {
    console.warn(`translatePage: page '${page}' tidak dikenali`);
    return;
  }

  //setLocales_textContent(config.map, config.attr, config.namespace);
  setLocales_extended(config.map, config.attr, config.namespace);
}

export function setLocales_textContent(elementMap, attrKey, namespace) {
  Object.entries(elementMap).forEach(([attrValue, i18nKey]) => {
    const selector = `[${attrKey}="${attrValue}"]`;
    const elements = document.querySelectorAll(selector);

    if (elements.length > 0) {
      const translated = i18next.t(`${namespace}:${i18nKey}`);
      elements.forEach((el) => {
        el.textContent = translated;
      });
    } else {
      console.warn(
        `[Locales] Tidak ditemukan elemen dengan ${attrKey}="${attrValue}" di DOM`
      );
    }
  });
}

export function setLocales_extended(elementMap, attrKey, namespace) {
  Object.entries(elementMap).forEach(([attrValue, config]) => {
    const selector = `[${attrKey}="${attrValue}"]`;
    const elements = document.querySelectorAll(selector);

    if (!elements.length) {
      console.warn(
        `[Locales] Tidak ditemukan elemen dengan ${attrKey}="${attrValue}" di DOM`
      );
      return;
    }

    const i18nKey = typeof config === "string" ? config : config.key;
    const translated = i18next.t(`${namespace}:${i18nKey}`);

    elements.forEach((el) => {
      if (typeof config === "string" || config.type === "text") {
        el.textContent = translated;
      } else if (config.attr === "placeholder") {
        el.setAttribute("placeholder", translated);
      } else if (config.attr === "data-placeholder") {
        el.setAttribute("data-placeholder", translated);
        if ($(el).hasClass("select2-hidden-accessible")) {
          $(el).select2(); // Reinit jika perlu
        }
      } else if (
        config.type === "select_options" &&
        Array.isArray(config.options)
      ) {
        el.innerHTML = ""; // Clear existing options
        config.options.forEach(({ value, labelKey }) => {
          const opt = document.createElement("option");
          opt.value = value;
          opt.textContent = i18next.t(`${namespace}:${labelKey}`);
          el.appendChild(opt);
        });
      }
    });
  });
}
