(async function initMenuAdmin() {
  if (!document.body.classList.contains("menu-admin-page")) {
    return;
  }

  if (!window.MenuStore) {
    return;
  }

  const categoryListNode = document.querySelector("[data-admin-category-list]");
  const editorNode = document.querySelector("[data-admin-editor]");
  const saveButton = document.querySelector("[data-admin-save]");
  const exportButton = document.querySelector("[data-admin-export]");
  const importInput = document.querySelector("[data-admin-import-file]");
  const resetButton = document.querySelector("[data-admin-reset]");
  const addItemButton = document.querySelector("[data-admin-add-item]");
  const statusNode = document.querySelector("[data-admin-status]");

  if (
    !categoryListNode ||
    !editorNode ||
    !saveButton ||
    !exportButton ||
    !importInput ||
    !resetButton ||
    !addItemButton ||
    !statusNode
  ) {
    return;
  }

  let menuData = null;
  let activeCategoryId = null;
  let isDirty = false;

  const setStatus = (message, mode = "info") => {
    statusNode.textContent = message;
    statusNode.dataset.mode = mode;
  };

  const markDirty = () => {
    isDirty = true;
    setStatus("Cambios sin guardar.", "warn");
  };

  const getActiveCategory = () =>
    menuData.categories.find((category) => category.id === activeCategoryId) || menuData.categories[0];

  const createEmptyItem = (category) => {
    const timestamp = Date.now();
    return {
      id: `${category.id}-${timestamp}`,
      tag: "Nuevo",
      name: "Nuevo producto",
      description: "Describe aquí este producto.",
      price: "0,00 €",
      badge: "Editar badge",
      image: "./assets/milkshake.webp",
      alt: "Producto de carta",
      featured: false
    };
  };

  const renderCategoryList = () => {
    categoryListNode.innerHTML = menuData.categories
      .map((category) => {
        const isActive = category.id === activeCategoryId;
        return `
          <button
            type="button"
            class="menu-admin-category-btn${isActive ? " is-active" : ""}"
            data-admin-category="${category.id}"
          >${category.label}</button>
        `;
      })
      .join("");
  };

  const renderEditor = () => {
    const category = getActiveCategory();
    if (!category) {
      editorNode.innerHTML = "";
      return;
    }

    editorNode.innerHTML = `
      <article class="menu-v2-panel menu-admin-panel">
        <header class="menu-v2-panel-head menu-admin-panel-head">
          <label>
            Nombre del grupo
            <input type="text" value="${category.label}" data-admin-category-field="label">
          </label>
          <label>
            Descripcion del grupo
            <textarea rows="2" data-admin-category-field="description">${category.description}</textarea>
          </label>
        </header>

        <div class="menu-v2-grid menu-admin-grid">
          ${category.items
            .map(
              (item, index) => `
            <article class="menu-v2-product${item.featured ? " menu-v2-product-featured" : ""}" data-admin-item-index="${index}">
              <figure class="menu-v2-product-media media-shell" data-fallback="${item.name}">
                <img src="${item.image}" alt="${item.alt}">
              </figure>
              <div class="menu-v2-product-copy">
                <p class="menu-v2-kicker" contenteditable="plaintext-only" data-admin-field="tag" data-admin-item-index="${index}">${item.tag}</p>
                <h3 contenteditable="plaintext-only" data-admin-field="name" data-admin-item-index="${index}">${item.name}</h3>
                <p contenteditable="plaintext-only" data-admin-field="description" data-admin-item-index="${index}">${item.description}</p>
                <div class="menu-v2-meta">
                  <strong contenteditable="plaintext-only" data-admin-field="price" data-admin-item-index="${index}">${item.price}</strong>
                  <span contenteditable="plaintext-only" data-admin-field="badge" data-admin-item-index="${index}">${item.badge}</span>
                </div>

                <div class="menu-admin-item-tools">
                  <label>
                    Imagen actual
                    <input type="text" value="${item.image}" data-admin-input-field="image" data-admin-item-index="${index}" readonly>
                  </label>
                  <label class="menu-admin-upload">
                    Subir nueva imagen
                    <input type="file" accept="image/*" data-admin-upload-image data-admin-item-index="${index}">
                  </label>
                  <label>
                    Alt imagen
                    <input type="text" value="${item.alt}" data-admin-input-field="alt" data-admin-item-index="${index}">
                  </label>
                  <label class="menu-admin-toggle">
                    <input type="checkbox" ${item.featured ? "checked" : ""} data-admin-input-field="featured" data-admin-item-index="${index}">
                    Destacado
                  </label>
                  <button type="button" class="menu-admin-remove-item" data-admin-remove-item="${index}">Eliminar producto</button>
                </div>
              </div>
            </article>
          `
            )
            .join("")}
        </div>
      </article>
    `;
  };

  const updateImagePreview = (itemIndex, imagePath, altText) => {
    const imageNode = editorNode.querySelector(
      `[data-admin-item-index="${itemIndex}"] .menu-v2-product-media img`
    );
    const figureNode = editorNode.querySelector(`[data-admin-item-index="${itemIndex}"] .menu-v2-product-media`);
    if (!imageNode || !figureNode) {
      return;
    }
    figureNode.classList.remove("is-missing");
    imageNode.src = imagePath;
    imageNode.alt = altText || imageNode.alt;
  };

  const persistData = async () => {
    try {
      menuData = await window.MenuStore.saveData(menuData);
      isDirty = false;
      setStatus("Carta guardada en archivo (menu-data.json).", "ok");
    } catch (error) {
      setStatus("No pude guardar en archivo. Asegúrate de usar dev_server.py.", "error");
    }
  };

  categoryListNode.addEventListener("click", (event) => {
    const target = event.target.closest("[data-admin-category]");
    if (!target) {
      return;
    }
    const categoryId = target.getAttribute("data-admin-category");
    if (!categoryId) {
      return;
    }
    activeCategoryId = categoryId;
    renderCategoryList();
    renderEditor();
    initMediaFallback(editorNode);
  });

  addItemButton.addEventListener("click", () => {
    const category = getActiveCategory();
    if (!category) {
      return;
    }
    category.items.push(createEmptyItem(category));
    renderEditor();
    initMediaFallback(editorNode);
    markDirty();
  });

  editorNode.addEventListener("keydown", (event) => {
    const editable = event.target.closest("[contenteditable]");
    if (!editable) {
      return;
    }
    if (event.key === "Enter") {
      event.preventDefault();
      editable.blur();
    }
  });

  editorNode.addEventListener("input", (event) => {
    const category = getActiveCategory();
    if (!category) {
      return;
    }

    const categoryFieldNode = event.target.closest("[data-admin-category-field]");
    if (categoryFieldNode) {
      const field = categoryFieldNode.getAttribute("data-admin-category-field");
      if (field === "label" || field === "description") {
        category[field] = categoryFieldNode.value.trim() || category[field];
        if (field === "label") {
          renderCategoryList();
        }
        markDirty();
      }
      return;
    }

    const contentNode = event.target.closest("[data-admin-field]");
    if (contentNode) {
      const field = contentNode.getAttribute("data-admin-field");
      const index = Number(contentNode.getAttribute("data-admin-item-index"));
      if (!Number.isInteger(index) || !category.items[index]) {
        return;
      }
      const nextValue = contentNode.textContent.trim();
      category.items[index][field] = nextValue || category.items[index][field];
      markDirty();
      return;
    }

    const inputFieldNode = event.target.closest("[data-admin-input-field]");
    if (inputFieldNode) {
      const field = inputFieldNode.getAttribute("data-admin-input-field");
      const index = Number(inputFieldNode.getAttribute("data-admin-item-index"));
      if (!Number.isInteger(index) || !category.items[index]) {
        return;
      }

      if (field === "featured") {
        category.items[index].featured = Boolean(inputFieldNode.checked);
        renderEditor();
        initMediaFallback(editorNode);
      } else {
        const nextValue = inputFieldNode.value.trim();
        category.items[index][field] = nextValue || category.items[index][field];
        if (field === "alt" || field === "image") {
          updateImagePreview(index, category.items[index].image, category.items[index].alt);
        }
      }
      markDirty();
    }
  });

  editorNode.addEventListener("change", async (event) => {
    const uploadNode = event.target.closest("[data-admin-upload-image]");
    if (!uploadNode) {
      return;
    }

    const category = getActiveCategory();
    if (!category) {
      return;
    }

    const index = Number(uploadNode.getAttribute("data-admin-item-index"));
    if (!Number.isInteger(index) || !category.items[index]) {
      return;
    }

    const file = uploadNode.files?.[0];
    if (!file) {
      return;
    }

    try {
      setStatus("Subiendo imagen...", "info");
      const json = await window.MenuStore.uploadImage(
        file,
        category.items[index].id || `${category.id}-${index + 1}`
      );
      if (!json.path) {
        throw new Error("Respuesta de subida inválida");
      }

      category.items[index].image = json.path;
      if (!category.items[index].alt || category.items[index].alt === "Producto de carta") {
        category.items[index].alt = category.items[index].name;
      }

      const imagePathInput = editorNode.querySelector(
        `[data-admin-input-field="image"][data-admin-item-index="${index}"]`
      );
      if (imagePathInput) {
        imagePathInput.value = category.items[index].image;
      }

      const altInput = editorNode.querySelector(
        `[data-admin-input-field="alt"][data-admin-item-index="${index}"]`
      );
      if (altInput) {
        altInput.value = category.items[index].alt;
      }

      updateImagePreview(index, category.items[index].image, category.items[index].alt);
      markDirty();
      setStatus("Imagen subida. Pulsa guardar para persistir cambios en archivo.", "warn");
    } catch (error) {
      setStatus("No pude subir imagen. Verifica dev_server.py y el tamaño del archivo.", "error");
    } finally {
      uploadNode.value = "";
    }
  });

  editorNode.addEventListener("click", (event) => {
    const removeNode = event.target.closest("[data-admin-remove-item]");
    if (!removeNode) {
      return;
    }

    const index = Number(removeNode.getAttribute("data-admin-remove-item"));
    const category = getActiveCategory();
    if (!Number.isInteger(index) || !category?.items[index]) {
      return;
    }

    category.items.splice(index, 1);
    if (!category.items.length) {
      category.items.push(createEmptyItem(category));
    }

    renderEditor();
    initMediaFallback(editorNode);
    markDirty();
  });

  saveButton.addEventListener("click", async () => {
    await persistData();
  });

  exportButton.addEventListener("click", () => {
    const fileContent = JSON.stringify(menuData, null, 2);
    const blob = new Blob([fileContent], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `titas-carta-${new Date().toISOString().slice(0, 10)}.json`;
    link.click();
    URL.revokeObjectURL(url);
    setStatus("JSON exportado.", "ok");
  });

  importInput.addEventListener("change", async (event) => {
    const file = event.target.files?.[0];
    if (!file) {
      return;
    }

    try {
      const text = await file.text();
      const parsed = JSON.parse(text);
      menuData = window.MenuStore.normalizeData(parsed);
      activeCategoryId = menuData.defaultCategoryId || menuData.categories[0].id;
      renderCategoryList();
      renderEditor();
      initMediaFallback(editorNode);
      markDirty();
      setStatus("JSON importado. Recuerda guardar cambios.", "warn");
    } catch (error) {
      setStatus("No pude importar ese archivo JSON.", "error");
    } finally {
      importInput.value = "";
    }
  });

  resetButton.addEventListener("click", async () => {
    const confirmed = window.confirm(
      "Esto restaurará la carta base y sobrescribirá tu versión guardada en archivo. ¿Quieres continuar?"
    );
    if (!confirmed) {
      return;
    }
    try {
      menuData = await window.MenuStore.resetData();
      activeCategoryId = menuData.defaultCategoryId || menuData.categories[0].id;
      renderCategoryList();
      renderEditor();
      initMediaFallback(editorNode);
      isDirty = false;
      setStatus("Carta restaurada a la versión base.", "ok");
    } catch (error) {
      setStatus("No pude restaurar en archivo. Verifica dev_server.py.", "error");
    }
  });

  window.addEventListener("beforeunload", (event) => {
    if (!isDirty) {
      return;
    }
    event.preventDefault();
    event.returnValue = "";
  });

  try {
    menuData = await window.MenuStore.loadData();
    activeCategoryId = menuData.defaultCategoryId || menuData.categories[0]?.id;
  } catch (error) {
    menuData = window.MenuStore.getDefaultData();
    activeCategoryId = menuData.defaultCategoryId || menuData.categories[0]?.id;
    setStatus("No pude leer archivo, cargué valores base.", "warn");
  }

  renderCategoryList();
  renderEditor();
  initMediaFallback(editorNode);
})();
