function generateUniqueId() {
  const timestamp = new Date().getTime();
  const randomPart = Math.random().toString(36).substr(2, 9); // Gera parte aleatória de tamanho 9

  return `${timestamp}-${randomPart}`;
}

function setItemStorage(config, postID, tabID, index) {
  const indexInterger = index.replace('o2-tab-', '');
  if (!config[`tab-${postID}`]) {
    config[`tab-${postID}`] = {}; // Cria um objeto vazio se não existir
  }
  config[`tab-${postID}`][tabID] = indexInterger - 1;
  window.localStorage.setItem('o2m', JSON.stringify(config));
}

jQuery(function ($) {

  if (!window.localStorage.getItem('o2m'))
    window.localStorage.setItem('o2m', {});

  const queryString = window.location.search;
  const params = new URLSearchParams(queryString);
  const ID = params.get("post");

  let tabConfig;

  try {
    tabConfig = JSON.parse(window.localStorage.getItem('o2m'));
    let i = 0;
    const arrayTabs = $('.o2-tab');
    if (tabConfig[`tab-${ID}`]) {
      const arrayTabConfig = Object.keys(tabConfig[`tab-${ID}`]);
      if (arrayTabs) {
        while (i < arrayTabs.length && i < arrayTabConfig.length) {
          $(arrayTabs.get(i)).data('tabID', arrayTabConfig[i]);
          i++;
        }
      }
    }
  } catch (error) {
    tabConfig = {};
    tabConfig[`tab-${ID}`] = {};
  }

  $('.o2-tab').each(function () {

    let currentTabID = $(this).data('tabID');
    if (!currentTabID) {
      currentTabID = generateUniqueId();
      $(this).data('tabID', currentTabID);
    }

    $('.o2-tab-nav button', this).click((event) => {
      if ($(event.target).hasClass('active'))
        return false;

      $('.o2-tab-nav button').removeClass('active');
      $(event.target).addClass('active');

      const index = $(event.target).data('tab');

      $('.o2-tab-container', this).addClass('d-none');
      $('.o2-tab-container.' + index, this).removeClass('d-none');
      setItemStorage(tabConfig, ID, currentTabID, index);
    });

    if (tabConfig[`tab-${ID}`] && tabConfig[`tab-${ID}`][currentTabID]) {
      const currentTab = $('.o2-tab-nav', this).children().get(tabConfig[`tab-${ID}`][currentTabID]);
      if (currentTab)
        $(currentTab).trigger('click');
    }

  });

});