// Horliko podlahářství – interactivity (menu, reveal, form validation, availability)

const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));

function initYear() {
  const el = $("#year");
  if (el) el.textContent = String(new Date().getFullYear());
}

function initNav() {
  const toggle = $("#navToggle");
  const nav = $("#siteNav");
  if (!toggle || !nav) return;

  const setOpen = (open) => {
    nav.classList.toggle("is-open", open);
    toggle.setAttribute("aria-expanded", String(open));
    document.body.classList.toggle("nav-open", open);
  };

  toggle.addEventListener("click", () => {
    const isOpen = nav.classList.contains("is-open");
    setOpen(!isOpen);
  });

  // Close after clicking a link in the menu
  nav.addEventListener("click", (e) => {
    const a = e.target.closest("a");
    if (a) setOpen(false);
  });

  // Close on ESC
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") setOpen(false);
  });
}

function initReveal() {
  const els = $$(".reveal");
  if (!els.length) return;

  if (!("IntersectionObserver" in window)) {
    els.forEach((el) => el.classList.add("is-visible"));
    return;
  }

  const io = new IntersectionObserver(
    (entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-visible");
          io.unobserve(entry.target);
        }
      }
    },
    { threshold: 0.12 }
  );

  els.forEach((el) => io.observe(el));
}

function validateEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(email).trim());
}

function setFieldError(name, msg) {
  const el = document.querySelector(`.error[data-for="${name}"]`);
  if (el) el.textContent = msg || "";
}

function initSuccessModal() {
  const modal = $("#successModal");
  if (!modal) {
    // Provide no-op so initForm can call it safely even if modal is removed.
    window.openSuccessModal = () => {};
    return;
  }

  const backdrop = modal.querySelector(".modal__backdrop");
  const closeBtn = $("#modalClose");

  const open = () => {
    modal.classList.add("is-open");
    modal.setAttribute("aria-hidden", "false");
    document.body.classList.add("modal-lock");
  };

  const close = () => {
    modal.classList.remove("is-open");
    modal.setAttribute("aria-hidden", "true");
    document.body.classList.remove("modal-lock");
  };

  // Expose for initForm (keeps code simple)
  window.openSuccessModal = open;

  if (backdrop) backdrop.addEventListener("click", close);
  if (closeBtn) closeBtn.addEventListener("click", close);

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && modal.classList.contains("is-open")) close();
  });
}

function initForm() {
  const form = $("#contactForm");
  if (!form) return;

  const status = $("#formStatus");
  const setStatus = (msg) => {
    if (status) status.textContent = msg || "";
  };

  const getValue = (id) => (document.getElementById(id)?.value ?? "").trim();

  const validate = () => {
    let ok = true;
    ["name", "email", "service", "message", "gdpr"].forEach((k) => setFieldError(k, ""));

    const name = getValue("name");
    const email = getValue("email");
    const service = getValue("service");
    const message = getValue("message");
    const gdpr = document.getElementById("gdpr")?.checked;

    if (name.length < 2) {
      setFieldError("name", "Zadejte prosím jméno.");
      ok = false;
    }
    if (!validateEmail(email)) {
      setFieldError("email", "Zadejte prosím platný e-mail.");
      ok = false;
    }
    if (!service) {
      setFieldError("service", "Vyberte prosím službu.");
      ok = false;
    }
    if (message.length < 10) {
      setFieldError("message", "Popište prosím zakázku (alespoň 10 znaků).");
      ok = false;
    }
    if (!gdpr) {
      setFieldError("gdpr", "Souhlas je povinný.");
      ok = false;
    }

    return ok;
  };

  // Po návratu z odeslání zobraz potvrzení (FormSubmit přesměruje na _next)
  const params = new URLSearchParams(window.location.search);
  if (params.get("sent") === "1") {
    setStatus("");
    try {
      if (typeof window.openSuccessModal === "function") window.openSuccessModal();
    } catch (_) {
      // ignore
    }

    // Uklid URL (ať se modal neotvírá po refreshi)
    params.delete("sent");
    const clean = window.location.pathname + (params.toString() ? "?" + params.toString() : "") + "#kontakt";
    window.history.replaceState({}, "", clean);
  }

  form.addEventListener("submit", (e) => {
    if (!validate()) {
      e.preventDefault();
      setStatus("Zkontrolujte prosím vyplnění polí.");
      return;
    }

    // Nastav _next na aktuální stránku + ?sent=1#kontakt
    const next = form.querySelector('input[name="_next"]');
    if (next) {
      const url = new URL(window.location.href);
      url.searchParams.set("sent", "1");
      url.hash = "kontakt";
      next.value = url.toString();
    }

    setStatus("Odesílám…");
  });
}

async function applyAvailability() {
  const el = document.getElementById("availability");
  const textEl = document.getElementById("availabilityText");
  if (!el) return;

  // 1) Prefer server-side status (global for all visitors)
  try {
    const res = await fetch("api/get.php?t=" + Date.now(), { cache: "no-store" });
    if (res.ok) {
      const data = await res.json();
      if (data && data.status) {
        el.classList.remove("available", "limited", "unavailable");
        el.classList.add(data.status);
        if (textEl && data.text) textEl.textContent = data.text;
        return;
      }
    }
  } catch (_) {
    // ignore
  }

  // 2) Fallback: localStorage (only for this device)
  const key = "horliko_availability";
  let stored = null;
  try {
    stored = JSON.parse(localStorage.getItem(key) || "null");
  } catch (_) {
    stored = null;
  }

  if (stored && stored.status) {
    el.classList.remove("available", "limited", "unavailable");
    el.classList.add(stored.status);
    if (textEl && stored.text) textEl.textContent = stored.text;
  }
}

// Enable CSS that depends on JS (animations, reveal)
document.documentElement.classList.add("js");

// Boot
initYear();
initNav();
initReveal();
initSuccessModal();
initForm();
applyAvailability();

// === Kontakt: odeslání formuláře + success modal ===
(function () {
  const form = document.getElementById("contactForm");
  const modal = document.getElementById("successModal");
  const closeBtn = document.getElementById("closeModal");
  if (!form || !modal || !closeBtn) return;

  // Pokud už je navěšený handler, nepřidávej znovu
  if (form.dataset.modalBound === "1") return;
  form.dataset.modalBound = "1";

  form.addEventListener("submit", async (e) => {
    e.preventDefault();

    try {
      const res = await fetch(form.action, {
        method: "POST",
        body: new FormData(form),
        headers: { "Accept": "application/json" }
      });

      if (!res.ok) throw new Error("Odeslání selhalo");

      form.reset();
      modal.style.display = "flex";
      modal.setAttribute("aria-hidden", "false");
    } catch (err) {
      alert("Zprávu se nepodařilo odeslat. Zkuste to prosím znovu.");
    }
  });

  closeBtn.addEventListener("click", () => {
    modal.style.display = "none";
    modal.setAttribute("aria-hidden", "true");
  });

  modal.addEventListener("click", (e) => {
    if (e.target === modal) {
      modal.style.display = "none";
      modal.setAttribute("aria-hidden", "true");
    }
  });
})();
