/* ============================================================
   HARAMBEE — contact form (progressive enhancement)
   Without JS the form still works: a plain POST to contact.php,
   which renders its own confirmation/error page. With JS, submission
   happens via fetch so the user never leaves the page.
   ============================================================ */
(function () {
  "use strict";

  function t(key) {
    const H = window.HARAMBEE;
    const lang = H ? H.currentLang() : (document.documentElement.lang || "ro");
    return H && H.i18n[lang] && H.i18n[lang][key] != null ? H.i18n[lang][key] : key;
  }

  function boot() {
    const form = document.getElementById("contact-form");
    if (!form) return;

    const tsField = document.getElementById("cf-ts");
    if (tsField) tsField.value = String(Date.now());

    const statusEl = document.getElementById("form-status");
    const submitBtn = form.querySelector(".form-submit");

    form.addEventListener("submit", function (e) {
      e.preventDefault();
      submitBtn.disabled = true;
      statusEl.className = "form-status";
      statusEl.textContent = t("form_sending");

      fetch(form.getAttribute("action"), {
        method: "POST",
        headers: { "Accept": "application/json" },
        body: new FormData(form)
      })
        .then(function (res) {
          return res.json().catch(function () { return { ok: false }; });
        })
        .then(function (data) {
          if (data && data.ok) {
            form.reset();
            if (tsField) tsField.value = String(Date.now());
            statusEl.textContent = t("form_success");
            statusEl.className = "form-status is-ok";
          } else if (data && data.reason === "invalid") {
            statusEl.textContent = t("form_invalid");
            statusEl.className = "form-status is-err";
          } else {
            statusEl.textContent = t("form_error");
            statusEl.className = "form-status is-err";
          }
        })
        .catch(function () {
          statusEl.textContent = t("form_error");
          statusEl.className = "form-status is-err";
        })
        .finally(function () {
          submitBtn.disabled = false;
        });
    });
  }

  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot);
  else boot();
})();
