// ###################################
// ### UTILITIES
// ###################################

function getActivePublicationType() {
  return document
    .querySelector('.filters-toolbar--archive-publications')
    .getAttribute('active-publication-type');
}
function getActiveThematiquesFiltersIds() {
  const checkedFilters = document.querySelectorAll(
    '.filters-toolbar__action-thematiques-filter:checked'
  );
  return Array.from(checkedFilters).map((filter) => filter.getAttribute('value'));
}
function isThematiqueFilterActive() {
  const toolBar = document.querySelector('.filters-toolbar--archive-publications');
  return toolBar.hasAttribute('thematique-filter-active');
}

// ###################################
// ### UPDATE INDICATORS AND DISPLAY
// ###################################

function updatePublicationsCountResults() {
  const webinairePostsCount =
    parseInt(
      document
        .querySelector('.videos-webinaires-archives #webinaires-rows')
        .getAttribute('current-post-count'),
      10
    ) || 0;
  const ficheInfoPostsCount =
    parseInt(
      document
        .querySelector('.fiches-infos-archives #fiche-infos-rows')
        .getAttribute('current-post-count'),
      10
    ) || 0;
  const brochurePostsCount =
    parseInt(
      document
        .querySelector('.brochures-archives #brochures-rows')
        .getAttribute('current-post-count'),
      10
    ) || 0;

  const currentPublicationType = getActivePublicationType();

  let postcount;
  switch (currentPublicationType) {
    case 'brochures':
      postcount = brochurePostsCount;
      break;
    case 'fiches-infos':
      postcount = ficheInfoPostsCount;
      break;
    case 'webinaires':
      postcount = webinairePostsCount;
      break;
    case 'all':
      postcount = brochurePostsCount + ficheInfoPostsCount + webinairePostsCount;
      break;
  }

  const searchResultsComponent = document.querySelector('.filters-toolbar__posts-results-amount');
  const postAmountSpan = searchResultsComponent.querySelector('.results-amount');
  postAmountSpan.innerHTML = postcount;
}
function toggleActivePublicationTypeFilterButton() {
  const filterButtons = document.querySelectorAll('.filters-toolbar__action-button');
  const activePublicationType = getActivePublicationType();

  filterButtons.forEach((button) => {
    button.classList.remove('filters-toolbar__action-button--active');
    button.setAttribute('aria-pressed', 'false');
  });

  const correspondingActiveThematiqueButton = document.querySelector(
    `.filters-toolbar__action-button[data-publication-type=${activePublicationType}]`
  );

  if (!correspondingActiveThematiqueButton) return;
  correspondingActiveThematiqueButton.classList.add('filters-toolbar__action-button--active');
  correspondingActiveThematiqueButton.setAttribute('aria-pressed', 'true');
}
function updateActiveThematiquesFiltersViewer() {
  const activeFilters = document.querySelectorAll(
    '.filters-toolbar__action-thematiques-filter:checked'
  );
  const resetFiltersButton = document.querySelector(
    '.filters-toolbar__action-button--reset-filter'
  );
  const activeFiltersContainer = document.querySelector(
    '.filters-toolbar__active-filters-viewer .active-filters-button-container'
  );
  activeFiltersContainer.innerHTML = '';
  if (activeFilters.length === 0) {
    resetFiltersButton.setAttribute('hidden', '');
    checkShowAllCheckboxFilter();
    setToolbarThematiqueFilterInactive();
  }

  if (activeFilters.length > 0) {
    resetFiltersButton.removeAttribute('hidden');
  }

  activeFilters.forEach((activeFilterCheckbox) => {
    const button = document.createElement('button');
    button.classList.add('filters-toolbar__action-button--active-filter-remover');

    const span = document.createElement('span');
    span.classList.add('sr-only');
    span.innerText = mainAppJsDynamicDatas.deleteFilter + ' :';
    button.appendChild(span);

    const buttonText = document.createTextNode(activeFilterCheckbox.getAttribute('data-title'));
    button.appendChild(buttonText);

    button.setAttribute('value', activeFilterCheckbox.getAttribute('value'));

    activeFiltersContainer.appendChild(button);

    button.addEventListener('click', () => {
      activeFilterCheckbox.checked = false;
      filterPublications();
    });
  });
}

// ############################################
// ### HANDLE THEMATIQUE FILTER SUBMENU TOGGLE
// ############################################
function handleSubmenuToggle() {
  const submenuToggle = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .filter-by-thematiques-submenu-toggle'
  );
  const submenuFilters = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .action-thematiques-filters-list'
  );

  if (!submenuToggle) return;

  submenuToggle.addEventListener('click', () => {
    const isSubmenuOpen = submenuToggle.getAttribute('aria-expanded');

    if (isSubmenuOpen === 'true') {
      return closeSubMenuFilters();
    } else {
      return openSubMenuFilters();
    }
  });

  // CLOSE SUBMENU IF CLICK OUTSIDE
  document.addEventListener('click', (e) => {
    const submenuGroup = document.querySelector('.filters-toolbar__action-thematiques-filters');

    const isClickInside = submenuGroup.contains(e.target);
    if (!isClickInside) {
      closeSubMenuFilters();
    }
  });

  // CLOSE SUBMENU IF ESCAPE KEY
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      closeSubMenuFilters();
    }
  });
}
function openSubMenuFilters() {
  const submenuToggle = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .filter-by-thematiques-submenu-toggle'
  );
  const submenuFilters = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .action-thematiques-filters-list'
  );
  submenuFilters.removeAttribute('hidden');
  submenuFilters.removeAttribute('aria-hidden');

  submenuToggle.setAttribute('active', '');
  submenuToggle.setAttribute('aria-expanded', 'true');
}
function closeSubMenuFilters() {
  const submenuToggle = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .filter-by-thematiques-submenu-toggle'
  );
  const submenuFilters = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .action-thematiques-filters-list'
  );
  submenuFilters.setAttribute('hidden', '');
  submenuFilters.setAttribute('aria-hidden', '');

  submenuToggle.removeAttribute('active');
  submenuToggle.setAttribute('aria-expanded', 'false');
  // submenuToggle.removeAttribute('aria-expanded');
}

// #################################################
// ### HANDLE THEMATIQUE FILTER CHECKING/UNCHECKING
// #################################################

function handleThematiqueCheckFilters() {
  const filters = document.querySelectorAll('.filters-toolbar__action-thematiques-filter');

  if (!filters) return;

  // HANDLE FILTERS
  filters.forEach((filter) =>
    filter.addEventListener('click', () => {
      uncheckShowAllFilter();
      filterPublications();
      setToolbarThematiqueFilterActive();
      const activeFilters = document.querySelectorAll(
        '.filters-toolbar__action-thematiques-filter:checked'
      );
      if (activeFilters.length === 0) {
        checkShowAllCheckboxFilter();
        filterPublications();
        setToolbarThematiqueFilterInactive();
      }
    })
  );

  // HANDLE SHOW ALL FILTER
  const showAllPostsCheckbox = document.querySelector(
    '.filters-toolbar__action-thematiques-filter--show-all'
  );
  showAllPostsCheckbox.addEventListener('click', () => {
    uncheckAllFilters();
    filterPublications();
    setToolbarThematiqueFilterInactive();
  });
}
function uncheckAllFilters() {
  const activeFilters = document.querySelectorAll(
    '.filters-toolbar__action-thematiques-filter:checked'
  );
  activeFilters.forEach((filter) => (filter.checked = false));
}
function uncheckShowAllFilter() {
  const showAllFilter = document.querySelector(
    '.filters-toolbar__action-thematiques-filter--show-all'
  );
  showAllFilter.checked = false;
}
function checkShowAllCheckboxFilter() {
  const showAllFilter = document.querySelector(
    '.filters-toolbar__action-thematiques-filter--show-all'
  );
  showAllFilter.checked = true;
}
function handleThematiqueFiltersReset() {
  const resetThematiquesFilterButton = document.querySelector(
    '.filters-toolbar__action-button--reset-filter'
  );
  resetThematiquesFilterButton.addEventListener('click', () => {
    uncheckAllFilters();
    checkShowAllCheckboxFilter();
    updateActiveThematiquesFiltersViewer();
    setToolbarThematiqueFilterInactive();
    filterPublications();
  });
}

// ####################################
// ### HANDLE PUBLICATION TYPE FILTER
// ####################################

function handlePublicationTypeFilters() {
  const publicationTypeFilterButtons = document.querySelectorAll(
    '.publication-type-filters-wrapper .filters-toolbar__action-button'
  );
  publicationTypeFilterButtons.forEach((button) => {
    const buttonPublicationType = button.getAttribute('data-publication-type');
    const toolBar = document.querySelector('.filters-toolbar--archive-publications');
    button.addEventListener('click', (e) => {
      toolBar.setAttribute('active-publication-type', buttonPublicationType);
      // filterPublications(publicationType, e);
      filterPublications();
    });
  });
}

// ###############################################
// ### HANDLE TOOLBAR ACTIVE FILTERS CLASS STATUS
// ###############################################

function setToolbarThematiqueFilterActive() {
  const toolBar = document.querySelector('.filters-toolbar--archive-publications');
  toolBar.setAttribute('thematique-filter-active', '');
}
function setToolbarThematiqueFilterInactive() {
  const toolBar = document.querySelector('.filters-toolbar--archive-publications');
  toolBar.removeAttribute('thematique-filter-active');
}

// #########################
// ### HYDRATATION
// #########################

async function hydrateBrochureArchiveGrid() {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const activeFiltersIds = getActiveThematiquesFiltersIds();

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/brochures-archive-rows?current-page-language=${currentLanguage}&thematiques-ids=${activeFiltersIds}`
  );
  brochuresDatas = await response.json();

  const brochureRows = document.querySelector('.brochures-archives #brochures-rows');
  brochureRows.innerHTML = brochuresDatas.html_template;
  brochureRows.setAttribute('current-post-count', brochuresDatas.total_posts_found);
}
async function hydrateFicheInfoArchiveGrid() {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const activeFiltersIds = getActiveThematiquesFiltersIds();

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/fiche-info-archive-rows?current-page-language=${currentLanguage}&thematiques-ids=${activeFiltersIds}`
  );
  ficheInfosDatas = await response.json();

  const ficheInfoRows = document.querySelector('.fiches-infos-archives #fiche-infos-rows');

  ficheInfoRows.innerHTML = ficheInfosDatas.html_template;
  ficheInfoRows.setAttribute('current-post-count', ficheInfosDatas.total_posts_found);
}
async function hydrateWebinaireArchiveGrid() {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const activeFiltersIds = getActiveThematiquesFiltersIds();

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/webinaire-archive-rows?current-page-language=${currentLanguage}&thematiques-ids=${activeFiltersIds}`
  );
  webinairesDatas = await response.json();

  const webinaireRows = document.querySelector('.videos-webinaires-archives #webinaires-rows');
  webinaireRows.innerHTML = webinairesDatas.html_template;
  webinaireRows.setAttribute('current-post-count', webinairesDatas.total_posts_found);
}
async function hydrateAll() {
  await hydrateBrochureArchiveGrid();
  await hydrateFicheInfoArchiveGrid();
  await hydrateWebinaireArchiveGrid();
}

// #########################
// ### SECTION VISIBILITIES
// #########################

function hideSectionPrintedBrochure() {
  const sectionPrintedBrochure = document.querySelector('#highlighted-share-publication') ?? null;
  if (!sectionPrintedBrochure) return;
  sectionPrintedBrochure.setAttribute('hidden', true);
}
function showSectionPrintedBrochure() {
  const sectionPrintedBrochure = document.querySelector('#highlighted-share-publication');
  if (!sectionPrintedBrochure) return;
  sectionPrintedBrochure.removeAttribute('hidden');
}
function hideSectionFichesInfos() {
  const sectionFichesInfos = document.querySelector('.fiches-infos-archives');
  if (!sectionFichesInfos) return;
  sectionFichesInfos.setAttribute('hidden', true);
}
function showSectionFichesInfos() {
  const sectionFichesInfos = document.querySelector('.fiches-infos-archives');
  if (!sectionFichesInfos) return;
  sectionFichesInfos.removeAttribute('hidden');
}
function handleSectionVisibility() {
  const sectionBrochures = document.querySelector('.brochures-archives');
  const sectionWebinaires = document.querySelector('.videos-webinaires-archives');
  const sectionHighlight = document.querySelector('#highlighted-document');
  const sectionFichesInfos = document.querySelector('.fiches-infos-archives');

  showSectionPrintedBrochure();
  showSectionFichesInfos();
  sectionWebinaires.removeAttribute('hidden');
  sectionBrochures.removeAttribute('hidden');
  sectionHighlight.removeAttribute('hidden');

  let loadMoreBrochuresButton = sectionBrochures.querySelector('.cta--load-more');
  let loadMoreFichesInfosButton = sectionFichesInfos.querySelector('.cta--load-more');

  const publicationType = getActivePublicationType();

  switch (publicationType) {
    case 'brochures':
      hideSectionFichesInfos();
      hideSectionPrintedBrochure();
      sectionWebinaires.setAttribute('hidden', true);
      sectionHighlight.setAttribute('hidden', true);
      loadMoreBrochuresButton.setAttribute('hidden', true);
      break;

    case 'fiches-infos':
      hideSectionPrintedBrochure();
      sectionBrochures.setAttribute('hidden', true);
      sectionWebinaires.setAttribute('hidden', true);
      sectionHighlight.setAttribute('hidden', true);

      loadMoreFichesInfosButton.setAttribute('hidden', true);

      break;

    case 'webinaires':
      sectionFichesInfos.setAttribute('hidden', true);
      sectionBrochures.setAttribute('hidden', true);
      sectionHighlight.setAttribute('hidden', true);
      hideSectionFichesInfos();
      hideSectionPrintedBrochure();
      break;

    case 'all':
      loadMoreBrochuresButton.setAttribute('hidden', true);
      loadMoreFichesInfosButton.setAttribute('hidden', true);
      break;
  }
}

// #########################
// ### FILTER
// #########################
async function filterPublications() {
  updateActiveThematiquesFiltersViewer();
  const activePublicationType = getActivePublicationType();

  const sectionFichesInfos = document.querySelector('.fiches-infos-archives');
  const sectionBrochures = document.querySelector('.brochures-archives');
  const sectionWebinaires = document.querySelector('.videos-webinaires-archives');

  handleSectionVisibility();
  switch (activePublicationType) {
    case 'all':
      sectionBrochures.setAttribute('isLoading', true);
      sectionFichesInfos.setAttribute('isLoading', true);
      await hydrateAll();
      sectionBrochures.removeAttribute('isLoading');
      sectionFichesInfos.removeAttribute('isLoading');
      break;

    case 'brochures':
      sectionBrochures.setAttribute('isLoading', true);
      await hydrateBrochureArchiveGrid();
      sectionBrochures.removeAttribute('isLoading');
      break;

    case 'fiches-infos':
      sectionFichesInfos.setAttribute('isLoading', true);
      await hydrateFicheInfoArchiveGrid();
      sectionFichesInfos.removeAttribute('isLoading');
      break;

    case 'webinaires':
      sectionWebinaires.setAttribute('isLoading', true);
      await hydrateWebinaireArchiveGrid();
      sectionWebinaires.removeAttribute('isLoading');

      // setTimeout(() => {}, 300);
      break;
  }
  handleScrollerFilterVisibility();

  updatePublicationsCountResults();
  toggleActivePublicationTypeFilterButton();
}
// ###########################
// ### LOAD MORE PUBLICATIONS
// ###########################

async function loadMorePublications(publicationType, button) {
  button.setAttribute('hidden', true);
  const sectionFichesInfos = document.querySelector('.fiches-infos-archives');
  const sectionBrochures = document.querySelector('.brochures-archives');

  switch (publicationType) {
    case 'brochures':
      sectionBrochures.setAttribute('isLoading', true);
      await hydrateBrochureArchiveGrid();
      sectionBrochures.removeAttribute('isLoading');
      break;

    case 'fiches-infos':
      sectionFichesInfos.setAttribute('isLoading', true);
      await hydrateFicheInfoArchiveGrid();
      sectionFichesInfos.removeAttribute('isLoading');
      break;
  }
}
function handleLoadMore() {
  const loadMoreButtons = document.querySelectorAll('.cta--load-more');
  if (!loadMoreButtons) return;
  loadMoreButtons.forEach((button) => {
    const publicationType = button.getAttribute('data-publication-type');
    button.addEventListener('click', (e) => {
      loadMorePublications(publicationType, button, e);
    });
  });
}
function handleLoadAll() {
  const loadAllbutton = document.querySelector('.filters-toolbar__action-button--load-all');
  if (!loadAllbutton) return;

  loadAllbutton.addEventListener('click', (e) => {
    const publicationType = loadAllbutton.getAttribute('data-publication-type');
    filterPublications();
  });
}
function handleScrollerFilterVisibility() {
  const scrollerFilter = document.querySelector('#scroller-filter');
  if (!scrollerFilter) return;

  const publicationType = getActivePublicationType();

  if (publicationType === 'all' && !isThematiqueFilterActive()) {
    scrollerFilter.setAttribute('hidden', true);
  } else {
    scrollerFilter.removeAttribute('hidden');
  }
}

// #########################
// ### INSTANCIATE
// #########################
export default function filterPublicationsInit() {
  const publicationsFiltersToolbar = document.querySelector(
    '.filters-toolbar--archive-publications'
  );
  if (!publicationsFiltersToolbar) return;

  handleSubmenuToggle();
  handleThematiqueCheckFilters();
  handleThematiqueFiltersReset();
  handlePublicationTypeFilters();
  handleLoadMore();
  handleLoadAll();
  handleScrollerFilterVisibility();
}
