export function createObjectModal({ panel, backdrop, onDelete, onClose }) {
  let activeTarget = null;

  const hide = () => {
    if (panel) {
      panel.classList.add("hidden");
      panel.style.display = "";
    }
    if (backdrop) {
      backdrop.classList.add("hidden");
      backdrop.style.display = "";
    }
    activeTarget = 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);

    if (activeTarget?.label) {
      const label = document.createElement("div");
      label.className = "muted";
      label.style.margin = "0 0 8px";
      label.textContent = activeTarget.label;
      list.appendChild(label);
    }

    const deleteBtn = document.createElement("button");
    deleteBtn.className = "example-card danger-btn";
    deleteBtn.textContent = "Удалить объект";
    deleteBtn.addEventListener("click", () => {
      if (!activeTarget?.modelId) return;
      onDelete?.(activeTarget);
    });
    list.appendChild(deleteBtn);
  };

  const show = ({ modelId, label } = {}) => {
    activeTarget = { modelId, label };
    render();
    if (panel) {
      panel.classList.remove("hidden");
      panel.style.display = "grid";
    }
    if (backdrop) {
      backdrop.classList.remove("hidden");
      backdrop.style.display = "block";
    }
  };

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

  return {
    show,
    hide,
  };
}
