export function createMeasurementModal({ panel, backdrop, onDelete, onToggleVisibility, onClose }) {
  let activeMeasurementId = null;
  let currentVisible = true;

  const hide = () => {
    if (panel) {
      panel.classList.add("hidden");
      panel.style.display = "";
    }
    if (backdrop) {
      backdrop.classList.add("hidden");
      backdrop.style.display = "";
    }
    activeMeasurementId = null;
    onClose?.();
  };

  const render = () => {
    if (!panel) return;
    panel.innerHTML = "";

    const header = document.createElement("div");
    header.className = "templates-header";
    header.innerHTML = `<span class="templates-title">Размер</span>`;

    const closeBtn = document.createElement("button");
    closeBtn.className = "templates-close";
    closeBtn.textContent = "×";
    closeBtn.addEventListener("click", hide);
    header.appendChild(closeBtn);
    panel.appendChild(header);

    const list = document.createElement("div");
    list.className = "template-list";
    panel.appendChild(list);

    const deleteBtn = document.createElement("button");
    deleteBtn.className = "example-card";
    deleteBtn.textContent = "Удалить размер";
    deleteBtn.addEventListener("click", () => {
      if (!activeMeasurementId) return;
      onDelete?.(activeMeasurementId);
    });
    list.appendChild(deleteBtn);

    const toggleBtn = document.createElement("button");
    toggleBtn.className = "example-card";
    toggleBtn.textContent = currentVisible ? "Скрыть размер" : "Показать размер";
    toggleBtn.addEventListener("click", () => {
      if (!activeMeasurementId) return;
      const nextVisible = !currentVisible;
      onToggleVisibility?.(activeMeasurementId, nextVisible);
      currentVisible = nextVisible;
      toggleBtn.textContent = currentVisible ? "Скрыть размер" : "Показать размер";
    });
    list.appendChild(toggleBtn);
  };

  const show = ({ measurementId, visible = true } = {}) => {
    activeMeasurementId = measurementId || null;
    currentVisible = visible !== false;
    render();
    if (panel) {
      panel.classList.remove("hidden");
      panel.style.display = "grid";
    }
    if (backdrop) {
      backdrop.classList.remove("hidden");
      backdrop.style.display = "block";
    }
  };

  const setVisibility = (visible) => {
    currentVisible = !!visible;
    render();
    if (panel && !panel.classList.contains("hidden")) {
      panel.style.display = "grid";
    }
  };

  if (backdrop) {
    backdrop.addEventListener("click", hide);
  }

  return {
    show,
    hide,
    setVisibility,
  };
}
