// 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() {
  // NOTE:
  // script.js is loaded BEFORE the modal HTML is placed in index.html.
  // So we must wire this lazily – i.e., find (or create) the modal at the moment we open it.

  const ensureModal = () => {
    let modal = $("#successModal");
    if (modal) return modal;

    // If the modal isn't in DOM (e.g. older versions), create a compatible one.
    modal = document.createElement("div");
    modal.className = "modal";
    modal.id = "successModal";
    modal.setAttribute("aria-hidden", "true");
    modal.innerHTML = `
      <div class="modal__backdrop"></div>
      <div class="modal__dialog" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
        <h3 id="modalTitle">Formulář byl úspěšně odeslán</h3>
        <p id="modalBody">E-mail byl úspěšně odeslán. Budeme se mu co nejdříve věnovat a brzy vás kontaktujeme.</p>
        <button class="btn btn--small" id="modalClose" type="button">Zavřít</button>
      </div>
    `;
    document.body.appendChild(modal);
    return modal;
  };

  const wireCloseOnce = () => {
    const modal = ensureModal();
    if (modal.dataset.wired === "1") return;
    modal.dataset.wired = "1";

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

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

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

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

  // Expose for initForm + universal popup
  window.openSuccessModal = open;

  // If the modal exists later (because it's placed after script.js), wire close once DOM is ready.
  document.addEventListener("DOMContentLoaded", () => {
    try { wireCloseOnce(); } catch (_) {}
  });
}

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

  const submitBtn = form.querySelector('button[type="submit"], input[type="submit"]');

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

  // Kontrola příloh: jen JPG/PNG/PDF, celkem max 5 MB
  function validateAttachments() {
    const input = document.getElementById("attachments");
    if (!input || !input.files) return true;

    const allowed = new Set(["image/jpeg", "image/png", "application/pdf"]);
    let total = 0;
    for (const f of Array.from(input.files)) {
      total += f.size || 0;
      if (f.type && !allowed.has(f.type)) {
        setStatus("Povolené jsou pouze soubory JPG, PNG nebo PDF.");
        return false;
      }
    }
    if (total > 5 * 1024 * 1024) {
      setStatus("Celková velikost příloh je max 5 MB.");
      return false;
    }
    return true;
  }

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

    if (!validate()) {
      setStatus("Zkontrolujte prosím vyplnění polí.");
      return;
    }
    if (!validateAttachments()) return;

    setStatus("Odesílám…");
    if (submitBtn) submitBtn.disabled = true;

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

      let data = null;
      try {
        data = await res.json();
      } catch (_) {
        data = null;
      }

      if (res.ok && data && data.ok) {
        setStatus("");
        try {
          if (typeof window.openSuccessModal === "function") window.openSuccessModal();
        } catch (_) {}
        form.reset();
      } else {
        const msg = (data && data.error) ? data.error : "Odeslání se nepodařilo. Zkuste to prosím znovu.";
        setStatus(msg);
      }
    } catch (err) {
      setStatus("Odeslání se nepodařilo. Zkontrolujte připojení a zkuste to znovu.");
    } finally {
      if (submitBtn) submitBtn.disabled = false;
    }
  });
}

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

// --- Univerzální vyskakovací okno po kliknutí na Odeslat ---
// Funguje napříč verzemi (FormSubmit / PHP / jiný backend). Popup se zobrazí ihned po kliknutí.
(function universalSubmitPopup(){
  const MSG_TITLE = "E-mail byl úspěšně odeslán";
  const MSG_BODY = "E-mail byl úspěšně odeslán. Budeme se mu co nejdříve věnovat a brzy vás kontaktujeme.";

  // Ensure we have a modal in DOM; if not, create one that uses existing .modal CSS.
  function ensureModal(){
    let modal = document.getElementById("successModal");
    if (modal) return modal;

    modal = document.createElement("div");
    modal.className = "modal";
    modal.id = "successModal";
    modal.setAttribute("aria-hidden", "true");
    modal.innerHTML = `
      <div class="modal__backdrop"></div>
      <div class="modal__dialog" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
        <h3 id="modalTitle"></h3>
        <p id="modalBody"></p>
        <button class="btn btn--small" id="modalClose">Zavřít</button>
      </div>
    `;
    document.body.appendChild(modal);
    return modal;
  }

  function openNow(){
    // Prefer existing modal handler if present.
    try {
      if (typeof window.openSuccessModal === "function") {
        // Update text (if elements exist)
        const t = document.getElementById("modalTitle");
        const b = document.getElementById("modalBody");
        if (t) t.textContent = MSG_TITLE;
        if (b) b.textContent = MSG_BODY;
        window.openSuccessModal();
        return;
      }
    } catch (_) {}

    // Fallback: create modal and open it.
    const modal = ensureModal();
    const t = modal.querySelector("#modalTitle");
    const b = modal.querySelector("#modalBody");
    if (t) t.textContent = MSG_TITLE;
    if (b) b.textContent = MSG_BODY;
    modal.classList.add("is-open");
    modal.setAttribute("aria-hidden", "false");
    document.body.classList.add("modal-lock");
  }

  // One-time close wiring (works for both existing and injected modal)
  function wireCloseOnce(){
    const modal = ensureModal();
    if (modal.dataset.wired === "1") return;
    modal.dataset.wired = "1";

    const backdrop = modal.querySelector(".modal__backdrop");
    const closeBtn = modal.querySelector("#modalClose");
    const close = () => {
      modal.classList.remove("is-open");
      modal.setAttribute("aria-hidden", "true");
      document.body.classList.remove("modal-lock");
    };
    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();
    });
  }

  wireCloseOnce();
})();
