
document.addEventListener("DOMContentLoaded", () => {
  if (typeof Sortable === "undefined") {
    const s = document.createElement("script");
    s.src = "https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js";
    s.onload = () => {
      enableDragAndDrop();
      collapseAllCategories();
    };
    document.head.appendChild(s);
  } else {
    enableDragAndDrop();
    collapseAllCategories();
  }

  if (!document.getElementById("bottom-bar")) {
    const bar = document.createElement("div");
    bar.id = "bottom-bar";
    bar.innerHTML = `
      <button onclick="saveToServer()">💾 Ruaj Menu</button>
      <button onclick="document.getElementById('importInput').click()">📥 Importo</button>
      <button onclick="backupMenu()">📂 Backup</button>`;
    document.body.appendChild(bar);
  }
});

function enableDragAndDrop() {
  const menuEl = document.getElementById("menu-editor");
  if (!menuEl) return;

  Sortable.create(menuEl, {
    animation: 150,
    onEnd: function (evt) {
      const moved = menuData.splice(evt.oldIndex, 1)[0];
      menuData.splice(evt.newIndex, 0, moved);
    },
  });

  setTimeout(() => {
    document.querySelectorAll('.cat-content').forEach((container, catIndex) => {
      Sortable.create(container, {
        animation: 150,
        handle: '.item',
        draggable: '.item',
        onEnd: function (evt) {
          const cat = menuData[catIndex];
          const oldIndex = evt.oldIndex - 3;
          const newIndex = evt.newIndex - 3;
          if (oldIndex >= 0 && newIndex >= 0 && cat.items) {
            const moved = cat.items.splice(oldIndex, 1)[0];
            cat.items.splice(newIndex, 0, moved);
          }
        }
      });
    });
  }, 200);
}

function collapseAllCategories() {
  document.querySelectorAll(".category").forEach(cat => {
    if (!cat.classList.contains("collapsed")) {
      cat.classList.add("collapsed");
    }
  });

  // Enable click toggle
  document.querySelectorAll(".cat-header").forEach(header => {
    header.addEventListener("click", () => {
      const cat = header.closest(".category");
      cat.classList.toggle("collapsed");
    });
  });
}

// Observe mutations and re-apply collapse logic on render
const observer = new MutationObserver(() => {
  collapseAllCategories();
});
observer.observe(document.getElementById("menu-editor"), { childList: true, subtree: true });
