// Admin (Namecheap shared hosting): saves availability to server via PHP (api/set.php)
(function(){
  const API_SET = "../api/set.php";
  const API_GET = "../api/get.php";
  const API_UPLOAD = "../api/upload.php";
  const API_GALLERY = "../api/gallery.php";
  const API_GALLERY_SET = "../api/gallery_set.php";
  const API_GALLERY_DELETE = "../api/gallery_delete.php";
  const TOKEN = "BMXpCxm5N9viSEuJRcrkSLDVzr4GFQIG"; // token je i v api/config.php

  const $ = (s) => document.querySelector(s);
  const $$ = (s) => Array.from(document.querySelectorAll(s));

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

  const msg = $("#msg");
  const currentTag = $("#currentTag");
  const currentLabel = $("#currentLabel");

  let selected = "available";

  const palette = {
    available: { dot: "#2ecc71", label: "Přijímáme zakázky" },
    limited: { dot: "#f1c40f", label: "Omezená kapacita" },
    unavailable: { dot: "#e74c3c", label: "Nepřijímáme" },
  };

  function paintTag(st){
    if (!currentTag) return;
    const dot = currentTag.querySelector(".dot");
    if (dot) dot.style.background = palette[st].dot;
    if (currentLabel) currentLabel.textContent = palette[st].label;
  }

  function highlight(st){
    $$(".seg button").forEach(b => {
      const is = b.dataset.status === st;
      b.classList.toggle("btn--ghost", !is);
    });
  }

  async function load(){
    try {
      const res = await fetch(API_GET + "?t=" + Date.now(), { cache: "no-store" });
      if (res.ok) {
        const data = await res.json();
        if (data?.status) selected = data.status;
        if (msg) msg.value = data?.text || "Aktuálně přijímáme nové zakázky";
      }
    } catch(_){
      if (msg) msg.value = "Aktuálně přijímáme nové zakázky";
    }
    paintTag(selected);
    highlight(selected);
  }

  $$(".seg button").forEach(b => {
    b.addEventListener("click", () => {
      selected = b.dataset.status;
      paintTag(selected);
      highlight(selected);
      setStatus("");
    });
  });

  $("#save")?.addEventListener("click", async () => {
    const text = (msg?.value || "").trim() || "Aktuálně přijímáme nové zakázky";
    const body = new URLSearchParams();
    body.set("token", TOKEN);
    body.set("status", selected);
    body.set("text", text);

    setStatus("Ukládám…");

    try {
      const res = await fetch(API_SET, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) {
        throw new Error(data?.error || `Chyba (HTTP ${res.status})`);
      }
      setStatus("Uloženo. Změna je viditelná pro všechny návštěvníky.");
    } catch (e) {
      console.error(e);
      setStatus("Nepodařilo se uložit. Zkontrolujte, že server podporuje PHP a že je možné zapisovat do api/status.json.");
    }
  });

  $("#reset")?.addEventListener("click", async () => {
    selected = "available";
    if (msg) msg.value = "Aktuálně přijímáme nové zakázky";
    paintTag(selected);
    highlight(selected);

    const body = new URLSearchParams();
    body.set("token", TOKEN);
    body.set("status", selected);
    body.set("text", msg.value);

    setStatus("Obnovuji…");
    try {
      const res = await fetch(API_SET, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error(data?.error || `Chyba (HTTP ${res.status})`);
      setStatus("Výchozí stav uložen.");
    } catch (e) {
      console.error(e);
      setStatus("Nepodařilo se uložit výchozí stav.");
    }
  });


  // Galerie upload
  const gStatus = $("#galleryStatus");
  const setGStatus = (t) => { if (gStatus) gStatus.textContent = t || ""; };

  $("#upload")?.addEventListener("click", async () => {
    const file = $("#photo")?.files?.[0];
    const catSel = $("#cat")?.value || "dlazba";
    const cap = ($("#caption")?.value || "").trim();

    if (!file){
      setGStatus("Vyberte prosím soubor.");
      return;
    }

    const fd = new FormData();
    fd.append("token", TOKEN);
    fd.append("cat", catSel);
    fd.append("caption", cap);
    fd.append("photo", file);

    setGStatus("Nahrávám…");

    try{
      const res = await fetch(API_UPLOAD, { method: "POST", body: fd });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error(data?.error || `Chyba (HTTP ${res.status})`);
      setGStatus("Nahráno. Fotka je v galerii.");
      await loadGallery();
      // reset inputs
      const p=$("#photo"); if (p) p.value="";
      const c=$("#caption"); if (c) c.value="";
    } catch(e){
      console.error(e);
      setGStatus("Nepodařilo se nahrát. Zkontrolujte PHP a práva zápisu do /assets/uploads a /api/gallery.json.");
    }
  });



  // === Galerie: list + reorder + delete ===
  const listEl = $("#galleryList");
  const orderStatus = $("#orderStatus");
  const setOrderStatus = (t) => { if (orderStatus) orderStatus.textContent = t || ""; };

  let galleryItems = [];

  function esc(s){
    return String(s||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
  }

  function renderGalleryList(){
    if (!listEl) return;
    listEl.innerHTML = galleryItems.map((it, idx) => {
      const cap = esc(it.caption);
      const cat = esc(it.cat);
      const src = esc(it.src);
      return `
        <div class="gitem" draggable="true" data-idx="${idx}">
          <img class="gthumb" src="../${it.src}" alt="${cap}">
          <div class="gmeta">
            <div class="cap">${src}</div>

            <label>Popisek</label>
            <input type="text" value="${cap}" data-edit="caption" data-idx="${idx}" />

            <label>Kategorie</label>
            <select data-edit="cat" data-idx="${idx}">
              <option value="dlazba" ${cat==="dlazba" ? "selected" : ""}>Dlažba</option>
              <option value="pvc" ${cat==="pvc" ? "selected" : ""}>PVC</option>
              <option value="koberec" ${cat==="koberec" ? "selected" : ""}>Koberec</option>
            </select>

            <div class="gactions">
              <button class="btn btn--small btn--ghost" data-action="del" data-src="${src}">Smazat</button>
            </div>
          </div>
        </div>
      `;
    }).join("");
  }

  // Inline edit (caption/category)
  listEl?.addEventListener("input", (e) => {
    const el = e.target;
    const idx = Number(el?.dataset?.idx);
    const key = el?.dataset?.edit;
    if (!Number.isFinite(idx) || !key) return;
    if (!galleryItems[idx]) return;

    if (key === "caption"){
      galleryItems[idx].caption = el.value;
      setOrderStatus("Upraveno (nezapomeň uložit pořadí).");
    }
  });

  listEl?.addEventListener("change", (e) => {
    const el = e.target;
    const idx = Number(el?.dataset?.idx);
    const key = el?.dataset?.edit;
    if (!Number.isFinite(idx) || !key) return;
    if (!galleryItems[idx]) return;

    if (key === "cat"){
      galleryItems[idx].cat = el.value;
      setOrderStatus("Upraveno (nezapomeň uložit pořadí).");
    }
  });

  async function loadGallery(){
    try{
      const res = await fetch(API_GALLERY, { cache: "no-store" });
      if(!res.ok) throw new Error("HTTP " + res.status);
      const data = await res.json();
      galleryItems = Array.isArray(data?.items) ? data.items : [];
      renderGalleryList();
      setOrderStatus("");
    } catch(e){
      console.error(e);
      setOrderStatus("Nepodařilo se načíst galerii.");
    }
  }

  // Drag & drop reorder
  let dragFrom = null;

  listEl?.addEventListener("dragstart", (e) => {
    const item = e.target.closest(".gitem");
    if (!item) return;
    dragFrom = Number(item.dataset.idx);
    item.classList.add("is-dragging");
    e.dataTransfer.effectAllowed = "move";
  });

  listEl?.addEventListener("dragend", (e) => {
    const item = e.target.closest(".gitem");
    if (item) item.classList.remove("is-dragging");
  });

  listEl?.addEventListener("dragover", (e) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
  });

  listEl?.addEventListener("drop", (e) => {
    e.preventDefault();
    const item = e.target.closest(".gitem");
    if (!item) return;
    const to = Number(item.dataset.idx);
    if (Number.isNaN(dragFrom) || Number.isNaN(to) || dragFrom === to) return;

    const moved = galleryItems.splice(dragFrom, 1)[0];
    galleryItems.splice(to, 0, moved);
    dragFrom = null;
    renderGalleryList();
    setOrderStatus("Pořadí změněno (nezapomeň uložit).");
  });

  // Delete
  listEl?.addEventListener("click", async (e) => {
    const btn = e.target.closest("button[data-action='del']");
    if (!btn) return;

    const src = btn.getAttribute("data-src");
    if (!src) return;

    if (!confirm("Opravdu smazat fotku z galerie?")) return;

    const body = new URLSearchParams();
    body.set("token", TOKEN);
    body.set("src", src);

    setOrderStatus("Mažu…");
    try{
      const res = await fetch(API_GALLERY_DELETE, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body
      });
      const data = await res.json().catch(()=>null);
      if (!res.ok) throw new Error(data?.error || ("HTTP " + res.status));
      setOrderStatus("Smazáno.");
      await loadGallery();
    } catch(err){
      console.error(err);
      setOrderStatus("Nepodařilo se smazat.");
    }
  });

  // Save order
  $("#saveOrder")?.addEventListener("click", async () => {
    setOrderStatus("Ukládám…");
    const body = new URLSearchParams();
    body.set("token", TOKEN);
    body.set("items", JSON.stringify(galleryItems));

    try{
      const res = await fetch(API_GALLERY_SET, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body
      });
      const data = await res.json().catch(()=>null);
      if (!res.ok) throw new Error(data?.error || ("HTTP " + res.status));
      setOrderStatus("Pořadí uloženo.");
    } catch(e){
      console.error(e);
      setOrderStatus("Nepodařilo se uložit pořadí.");
    }
  });

  $("#reloadGallery")?.addEventListener("click", () => loadGallery());


  loadGallery();
  load();
})();


async function loadGalleryCategories() {
  const sel = document.getElementById("galleryCategory");
  if (!sel) return;

  try {
    const res = await fetch("../api/config_get.php?ts=" + Date.now(), { cache: "no-store" });
    if (!res.ok) return;
    const cfg = await res.json();
    const cats = Array.isArray(cfg.categories) ? cfg.categories : ["Vše"];
    sel.innerHTML = "";
    cats.filter(c => c && c !== "Vše").forEach(c => {
      const opt = document.createElement("option");
      opt.value = c;
      opt.textContent = c;
      sel.appendChild(opt);
    });
    if (cfg.defaultCategory) sel.value = cfg.defaultCategory;
  } catch(e) {}
}
document.addEventListener("DOMContentLoaded", loadGalleryCategories);

// Ensure category saved even if gallery item was built elsewhere
function attachCategory(item){
  if (!item || typeof item !== "object") return item;
  if (!("category" in item)) item.category = (document.getElementById("galleryCategory")?.value || "");
  return item;
}
