(function (global) {
  const app = (global.EpicrisisApp = global.EpicrisisApp || {});
  const DEFAULT_SUBVIEW = "auditoria";
  const TOP_HASH = "epicrisis_top";

  let tabs = [];
  let panels = [];
  let activeSubview = DEFAULT_SUBVIEW;
  let headerObserver = null;

  function subviewFromHash(hash = global.location.hash) {
    const candidate = String(hash || "").replace(/^#/, "");
    if (candidate === TOP_HASH) return activeSubview;
    return tabs.some((tab) => tab.dataset.subview === candidate) ? candidate : DEFAULT_SUBVIEW;
  }

  function updateHeaderOffset() {
    const header = document.querySelector(".ui-header");
    const height = header ? header.getBoundingClientRect().height : 0;
    document.documentElement.style.setProperty("--epicrisis-header-height", `${Math.ceil(height)}px`);
  }

  function activate(subview, { focusTab = false } = {}) {
    const target = tabs.some((tab) => tab.dataset.subview === subview) ? subview : DEFAULT_SUBVIEW;
    activeSubview = target;

    tabs.forEach((tab) => {
      const selected = tab.dataset.subview === target;
      tab.setAttribute("aria-selected", String(selected));
      tab.tabIndex = selected ? 0 : -1;
      if (selected && focusTab) tab.focus({ preventScroll: true });
    });

    panels.forEach((panel) => {
      panel.hidden = panel.dataset.subviewPanel !== target;
    });
  }

  function selectFromUserAction(subview, focusTab = false) {
    activate(subview, { focusTab });
    const nextHash = `#${subview}`;
    if (global.location.hash !== nextHash) {
      global.history.pushState(null, "", nextHash);
    }
  }

  function handleHistoryNavigation() {
    if (global.location.hash === `#${TOP_HASH}`) return;
    activate(subviewFromHash());
  }

  function handleKeydown(event) {
    const currentIndex = tabs.indexOf(event.currentTarget);
    if (currentIndex < 0) return;

    let nextIndex = null;
    if (event.key === "ArrowRight" || event.key === "ArrowDown") nextIndex = (currentIndex + 1) % tabs.length;
    if (event.key === "ArrowLeft" || event.key === "ArrowUp") nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;
    if (event.key === "Home") nextIndex = 0;
    if (event.key === "End") nextIndex = tabs.length - 1;
    if (nextIndex === null) return;

    event.preventDefault();
    selectFromUserAction(tabs[nextIndex].dataset.subview, true);
  }

  function observeHeader() {
    updateHeaderOffset();
    const header = document.querySelector(".ui-header");
    if (header && "ResizeObserver" in global) {
      headerObserver?.disconnect();
      headerObserver = new ResizeObserver(updateHeaderOffset);
      headerObserver.observe(header);
    } else {
      global.addEventListener("resize", updateHeaderOffset);
    }
  }

  function init() {
    const tablist = document.querySelector("[data-epicrisis-subview-nav] [role='tablist']");
    if (!tablist) return;

    tabs = Array.from(tablist.querySelectorAll("[role='tab'][data-subview]"));
    panels = Array.from(document.querySelectorAll("[role='tabpanel'][data-subview-panel]"));
    if (!tabs.length || !panels.length) return;

    tabs.forEach((tab) => {
      tab.addEventListener("click", (event) => {
        event.preventDefault();
        selectFromUserAction(tab.dataset.subview);
      });
      tab.addEventListener("keydown", handleKeydown);
    });
    global.addEventListener("popstate", handleHistoryNavigation);
    global.addEventListener("hashchange", handleHistoryNavigation);

    activate(subviewFromHash());
    document.body.classList.add("epicrisis-subviews-ready");
    observeHeader();
  }

  app.subviews = {
    activate,
    init,
    subviewFromHash,
  };
})(globalThis);
