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

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

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

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);
  });

  nav.addEventListener("click", (e) => {
    const a = e.target.closest("a");
    if (!a) return;
    setOpen(false);
  });

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

function initReveal() {
  const els = $$(".reveal");
  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 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í
  const params = new URLSearchParams(window.location.search);
  if (params.get("sent") === "1") {
    setStatus(""); openSuccessModal();
    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…");
  });
}

initYear();

initNav();
initNav();
initReveal();
initForm();




  if (stored && stored.status){
    el.classList.remove("available","limited","unavailable");
    el.classList.add(stored.status);

    if (textEl && stored.text){
      textEl.textContent = stored.text;
    }
  }
}


applyAvailability();



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(_) {}

  // 2) Fallback: localStorage (only for this device) if server not available
  const key = "horliko_availability";
  let stored = null;
  try { stored = JSON.parse(localStorage.getItem(key) || "null"); } catch(_) {}
  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();
initForm();
applyAvailability();






async function initGallery(){
  const gallery = document.getElementById("gallery");
  if (!gallery) return;

  try{
    const res = await fetch("api/gallery.php", { cache: "no-store" });
    if(!res.ok) throw new Error("gallery http " + res.status);
    const data = await res.json();

    const items = Array.isArray(data?.items) ? data.items : [];
    gallery.innerHTML = items.map(it => {
      const src = String(it.src || "");
      const caption = String(it.caption || "");
      const cat = String(it.cat || "dlazba");
      const safeCaption = caption.replace(/</g,"&lt;").replace(/>/g,"&gt;");
      return `
        <figure class="shot reveal is-visible" data-cat="${cat}">
          <img class="shot__img" src="${src}" alt="${safeCaption}" loading="lazy" />
          <figcaption>${safeCaption}</figcaption>
        </figure>
      `;
    }).join("\n");
  } catch(e){
    console.warn("Galerie se nepodařilo načíst:", e);
    // fallback – nech prázdné (stránka ale zůstane funkční)
  }

  initGalleryFilter();
}

function initGalleryFilter(){
  const wrap = document.querySelector(".filters");
  const gallery = document.getElementById("gallery");
  if (!wrap || !gallery) return;

  const shots = () => Array.from(gallery.querySelectorAll(".shot"));
  const buttons = Array.from(wrap.querySelectorAll(".filter"));

  const setActive = (btn) => {
    buttons.forEach(b => {
      const active = b === btn;
      b.classList.toggle("is-active", active);
      b.setAttribute("aria-selected", active ? "true" : "false");
    });
  };

  const apply = (filter) => {
    shots().forEach(s => {
      const cat = s.getAttribute("data-cat") || "";
      const show = (filter === "all") || (cat === filter);
      s.classList.toggle("is-hidden", !show);
    });
  };

  wrap.addEventListener("click", (e) => {
    const btn = e.target.closest(".filter");
    if (!btn) return;
    const filter = btn.getAttribute("data-filter") || "all";
    setActive(btn);
    apply(filter);
  });

  apply("all");
}

// start
initGallery();

