/* ============================================================
   form.js — заявка → lead_id → CRM (Task 4 §1.4)
   form_submit з lead_id у dataLayer; loading → success/error.
   ============================================================ */
(function () {
  "use strict";
  var KZ = window.KZ || {};
  var cfg = KZ.config || {};
  var copy = (KZ.form) || {};
  var form = document.getElementById("leadForm");
  if (!form) return;

  var btn = form.querySelector('button[type="submit"]');
  var result = document.getElementById("leadResult");
  var nameEl = document.getElementById("lf-name");
  var contactEl = document.getElementById("lf-contact");

  function uuid() {
    if (window.crypto && crypto.randomUUID) return crypto.randomUUID();
    return "lead-" + Date.now() + "-" + Math.floor(Math.random() * 1e9);
  }

  function setError(input, on) {
    var field = input.closest(".field");
    var err = field && field.querySelector(".field__error");
    if (field) field.classList.toggle("field--error", !!on);
    if (err) err.hidden = !on;
    input.setAttribute("aria-invalid", on ? "true" : "false");
  }

  function validContact(v) {
    if (!v) return false;
    var digits = (v.match(/\d/g) || []).length;
    return digits >= 7 || /@[\w.]{3,}/.test(v); // телефон АБО @username
  }

  function showResult(ok) {
    if (!result) return;
    result.hidden = false;
    result.textContent = ok ? (copy.success || "Дякуємо! Заявку прийнято.")
                            : (copy.error || "Щось пішло не так. Спробуй ще раз.");
    result.classList.toggle("is-error", !ok);
    result.classList.toggle("is-success", ok);
  }

  function send(payload) {
    if (!cfg.crmEndpoint) {
      // Заглушка: CRM-ендпоінт ще не наданий — симулюємо успіх (Task 4 §0)
      return new Promise(function (res) { setTimeout(res, 600); });
    }
    return fetch(cfg.crmEndpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    }).then(function (r) { if (!r.ok) throw new Error("CRM " + r.status); });
  }

  form.addEventListener("submit", function (e) {
    e.preventDefault();
    var nameVal = (nameEl.value || "").trim();
    var contactVal = (contactEl.value || "").trim();

    var okName = nameVal.length >= 2;
    var okContact = validContact(contactVal);
    setError(nameEl, !okName);
    setError(contactEl, !okContact);
    if (!okName) { nameEl.focus(); return; }
    if (!okContact) { contactEl.focus(); return; }

    btn.classList.add("is-loading");
    btn.disabled = true;
    if (result) result.hidden = true;

    var lead_id = uuid();
    var payload = {
      lead_id: lead_id,
      name: nameVal,
      contact: contactVal,
      variant_id: cfg.variantId,
      audience_segment: cfg.audienceSegment
    };

    if (window.KZTrack) window.KZTrack.push("form_submit", { lead_id: lead_id });

    send(payload).then(function () {
      btn.classList.remove("is-loading");
      form.reset();
      showResult(true);
      btn.disabled = false;
    }).catch(function () {
      btn.classList.remove("is-loading");
      btn.disabled = false;
      showResult(false);
    });
  });

  /* прибрати помилку при введенні */
  [nameEl, contactEl].forEach(function (el) {
    el.addEventListener("input", function () { setError(el, false); });
  });
})();
