$(document).ready(function () {
  if (!window.location.search.includes('action=settings')) return;

  const tabMap = {
    general:        "tab2_general",
    optimization:   "tab2_optimization",
    cms_install:    "tab2_cms_install",
    email_settings: "tab2_email_settings",
    payment_settings: "tab2_payment_settings",
    ads:            "tab2_ads",
    files:          "tab2_files",
    movies:         "tab2_movies",
    news:           "tab2_news",
    products:       "tab2_products",
    events:         "tab2_events",
    lots:           "tab2_lots"
  };

  const url = new URL(window.location);
  let currentTab = url.searchParams.get('tab');

  if (!currentTab || !tabMap[currentTab]) {
    currentTab = 'general';
    url.searchParams.set('tab', currentTab);
    history.replaceState(null, '', url);
  }

  const targetTabId = tabMap[currentTab] || currentTab;
  const $link = $(`a[data-bs-toggle="tab"][href="#${targetTabId}"]`);
  if ($link.length) {
    $link.tab('show');
  }

  $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
    const fullId = $(this).attr('href').substring(1); // remove #
    const shortName = Object.keys(tabMap).find(key => tabMap[key] === fullId) || fullId;

    url.searchParams.set('tab', shortName);
    history.replaceState(null, '', url);
  });

  $(window).on('beforeunload', function () {
    if (!location.search.includes('action=settings')) {
      const cleanUrl = new URL(location);
      cleanUrl.searchParams.delete('tab');
      history.replaceState(null, '', cleanUrl);
    }
  });
});

document.addEventListener("DOMContentLoaded", function() {
  const saveButtonContainer = document.getElementById("saveSettings");
  const tabLinks = document.querySelectorAll(".settings-item .nav-link");

  function checkTabVisibility() {
    let showButton = true;

    tabLinks.forEach(link => {
      if (link.classList.contains("active") && link.getAttribute("href") === "#tab2_cms_install") {
        showButton = false;
      }
    });

    saveButtonContainer.style.display = showButton ? "block" : "none";
  }

  checkTabVisibility();

  tabLinks.forEach(link => {
    link.addEventListener("shown.bs.tab", checkTabVisibility);
  });
});