/**
 * Модальное окно «Проверка БД» в стиле киоска (как привязка терминала):
 * тёмная рамка, iframe с /db_check?embed=1.
 */
(function () {
  const LOG = "[WespKioskDbCheck]";
  const MENU_OVERLAY_ID = "wespKioskMenuOverlay";

  function createModal() {
    const modal = document.createElement("div");
    modal.id = "kioskDbCheckModal";
    modal.setAttribute("aria-hidden", "true");
    modal.style.cssText =
      "display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:5000;" +
      "align-items:center;justify-content:center;padding:12px;box-sizing:border-box;";
    modal.innerHTML = `
      <div class="kiosk-db-check-panel" style="
        background:#1f1f1f;
        color:#fff;
        border-radius:14px;
        border:1px solid #2f2f2f;
        box-shadow:0 0 20px rgba(0,0,0,.45);
        width:min(920px,100%);
        max-height:min(92vh,900px);
        display:flex;
        flex-direction:column;
        overflow:hidden;
      ">
        <div style="
          display:flex;
          align-items:center;
          justify-content:space-between;
          gap:12px;
          padding:14px 16px;
          border-bottom:1px solid #2f2f2f;
          flex-shrink:0;
        ">
          <h2 style="margin:0;font-size:1.125rem;font-weight:600;line-height:1.3">Проверка баз данных</h2>
          <button type="button" id="kioskDbCheckClose" style="
            padding:10px 16px;
            border-radius:8px;
            border:1px solid #7a7a7a;
            background:#3a3a3a;
            color:#fff;
            cursor:pointer;
            font-size:15px;
            flex-shrink:0;
          ">Закрыть</button>
        </div>
        <iframe
          id="kioskDbCheckFrame"
          title="Проверка баз данных"
          style="border:0;width:100%;flex:1;min-height:min(70vh,560px);background:#f9fafb;"
        ></iframe>
      </div>
    `;
    document.body.appendChild(modal);

    const iframe = modal.querySelector("#kioskDbCheckFrame");
    const closeBtn = modal.querySelector("#kioskDbCheckClose");
    const panel = modal.querySelector(".kiosk-db-check-panel");

    function closeModal() {
      modal.style.display = "none";
      modal.setAttribute("aria-hidden", "true");
      try {
        iframe.src = "about:blank";
      } catch (e) {
        console.warn(LOG, "iframe reset", e);
      }
      document.removeEventListener("keydown", onKey);
    }

    function onKey(e) {
      if (e.key === "Escape") {
        e.preventDefault();
        closeModal();
      }
    }

    function openModal() {
      const menu = document.getElementById(MENU_OVERLAY_ID);
      if (menu) menu.style.display = "none";

      iframe.src = "/db_check?embed=1";
      modal.style.display = "flex";
      modal.setAttribute("aria-hidden", "false");
      document.addEventListener("keydown", onKey);
    }

    closeBtn.addEventListener("click", closeModal);
    modal.addEventListener("click", function (e) {
      if (e.target === modal) closeModal();
    });
    if (panel) {
      panel.addEventListener("click", function (e) {
        e.stopPropagation();
      });
    }

    return { modal, openModal, closeModal };
  }

  function setup(opts) {
    const options = opts || {};
    const linkSel = options.menuLinkSelector || "#dbCheckLink";

    if (typeof window.WespKioskMenu !== "undefined" && typeof window.WespKioskMenu.ensureOverlay === "function") {
      window.WespKioskMenu.ensureOverlay();
    }

    const link = document.querySelector(linkSel);
    if (!link) {
      console.warn(LOG, "ссылка меню не найдена после ensureOverlay:", linkSel);
      return {};
    }

    let api;
    if (!window.__wespKioskDbCheckApi) {
      api = createModal();
      window.__wespKioskDbCheckApi = api;
    } else {
      api = window.__wespKioskDbCheckApi;
    }

    if (link.dataset.wespDbCheckBound === "1") {
      return { openModal: api.openModal, closeModal: api.closeModal };
    }
    link.dataset.wespDbCheckBound = "1";

    link.addEventListener(
      "click",
      function (e) {
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.button !== 0) return;
        if (window.frameElement) return;
        e.preventDefault();
        e.stopPropagation();
        api.openModal();
      },
      true
    );

    return { openModal: api.openModal, closeModal: api.closeModal };
  }

  window.WespKioskDbCheck = { setup };
})();
