// #########################
// ### FILTER POSTS
// #########################
async function filterPosts(e) {
  const filterID =
    e.target.getAttribute('data-term-id') ??
    e.target.parentElement.getAttribute('data-term-id') ??
    null;
  const termName =
    e.target.getAttribute('data-term-name') ??
    e.target.parentElement.getAttribute('data-term-name') ??
    null;

  const filterButtons = document.querySelectorAll('.filters-toolbar__action-button');

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

  const newsContainer = document.querySelector('.news-container .card-grid-container');
  newsContainer.setAttribute('isLoading', true);
  await hydrateNewsFeedByTypeId(filterID, termName);
  newsContainer.removeAttribute('isLoading');

  e.target.classList.add('filters-toolbar__action-button--active');
  e.target.setAttribute('aria-pressed', 'true');

  updateActivePageNumber(1);
}

async function loadMorePosts(e) {
  const newsContainer = document.querySelector('.news-container .card-grid-container');
  newsContainer.setAttribute('isLoading', true);
  await hydrateNewsFeedWithNextPosts();
  newsContainer.removeAttribute('isLoading');
}

// ###################################
// ### UPDATE INDICATORS AND DISPLAY
// ###################################
function updateActivePageNumber(activePage) {
  const filtersToolbar = document.querySelector('.filters-toolbar--archive-news');
  filtersToolbar.setAttribute('data-active-page', activePage);
}

function updateHasMorePosts(activePage, maxNumPages) {
  const filtersToolbar = document.querySelector('.filters-toolbar--archive-news');

  filtersToolbar.setAttribute('data-has-more-posts', activePage < maxNumPages);
}

function checkLoadMoreButtonsVisibility() {
  const loadMoreButton = document.querySelector('#load-more-news');
  const loadAllButton = document.querySelector('#load-all-news');
  const filtersToolbar = document.querySelector('.filters-toolbar--archive-news');
  const hasMorePosts = filtersToolbar.getAttribute('data-has-more-posts') === 'true';

  if (hasMorePosts) {
    loadMoreButton.removeAttribute('hidden');
    loadAllButton.removeAttribute('hidden');
    return;
  }

  loadAllButton.setAttribute('hidden', 'true');
  loadMoreButton.setAttribute('hidden', 'true');
}

function updateSearchResultsAmount(totalPostsFound, termName) {
  const searchResultsComponent = document.querySelector('.filters-toolbar__posts-results-amount');

  if (termName !== 'all') {
    searchResultsComponent.querySelector('.results-amount').innerHTML = totalPostsFound;
    searchResultsComponent.querySelector('.results-filter-name').innerHTML = '"' + termName + '"';
    searchResultsComponent.classList.add('filter-active');
    searchResultsComponent.classList.remove('filter-disable');
    return;
  }
  if (termName === 'all') {
    searchResultsComponent.classList.remove('filter-active');
    searchResultsComponent.classList.add('filter-disable');
    searchResultsComponent.querySelector('.results-amount').innerHTML = totalPostsFound;
    searchResultsComponent.querySelector('.results-filter-name').innerHTML = termName;
    return;
  }
}

function updateToolbarActiveFilter(termId) {
  const filterToolbar = document.querySelector('.filters-toolbar--archive-news');
  if (!filterToolbar) return;

  filterToolbar.setAttribute('data-active-news-term', termId);
}

// #########################
// ### HYDRATATION
// #########################
async function hydrateNewsFeedByTypeId(filterID, termName) {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const filtersToolbar = document.querySelector('.filters-toolbar--archive-news');

  const postsPerPage = filtersToolbar.getAttribute('data-posts-per-page') ?? 12;
  const activePage = filtersToolbar.getAttribute('data-active-page');

  let newCardsDatas;
  if (filterID === 'all') {
    const response = await fetch(
      `/wp-json/homegrade-datas/v1/build/news?current-page-language=${currentLanguage}&active-page=${0}&posts-per-page=${postsPerPage}`
    );
    newCardsDatas = await response.json();
  } else {
    const response = await fetch(
      `/wp-json/homegrade-datas/v1/build/news?current-page-language=${currentLanguage}&active-page=${0}&active-term-id=${filterID}&posts-per-page=${postsPerPage}`
    );
    newCardsDatas = await response.json();
  }

  let container = document.querySelector('.card-grid-container');
  container.innerHTML = newCardsDatas.html_template;

  updateToolbarActiveFilter(filterID);
  updateSearchResultsAmount(newCardsDatas.total_posts_found, termName);
  updateHasMorePosts(newCardsDatas.active_page, newCardsDatas.max_num_pages);
  checkLoadMoreButtonsVisibility();
}

async function hydrateNewsFeedWithAllPosts() {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const filtersToolbar = document.querySelector('.filters-toolbar--archive-news');

  const postsPerPage = -1;
  const activeNewsTermId = filtersToolbar.getAttribute('data-active-news-term') ?? 'all';

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/news?current-page-language=${currentLanguage}&active-page=${0}&active-term-id=${activeNewsTermId}&posts-per-page=${postsPerPage}`
  );
  newsDatas = await response.json();

  const newsGrid = document.querySelector('.news-container .card-grid-container');
  newsGrid.innerHTML = newsDatas.html_template;

  updateHasMorePosts(newsDatas.active_page, newsDatas.max_num_pages);
  checkLoadMoreButtonsVisibility();
}

async function hydrateNewsFeedWithNextPosts() {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const filtersToolbar = document.querySelector('.filters-toolbar--archive-news');

  const activePage = filtersToolbar.getAttribute('data-active-page') ?? 1;
  const postsPerPage = filtersToolbar.getAttribute('data-posts-per-page') ?? 12;
  const activeNewsTermId = filtersToolbar.getAttribute('data-active-news-term') ?? 'all';

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/news?current-page-language=${currentLanguage}&active-page=${activePage}&active-term-id=${activeNewsTermId}&posts-per-page=${postsPerPage}`
  );
  newsDatas = await response.json();

  const newsGrid = document.querySelector('.news-container .card-grid-container');
  newsGrid.innerHTML += newsDatas.html_template;

  updateActivePageNumber(newsDatas.active_page);
  updateHasMorePosts(newsDatas.active_page, newsDatas.max_num_pages);
  checkLoadMoreButtonsVisibility();
}

// #########################
// ### INIT
// #########################
function filterNewsInit() {
  const filterNewsToolbar = document.querySelector('.filters-toolbar--archive-news');
  if (!filterNewsToolbar) return;

  const filterButtons = filterNewsToolbar.querySelectorAll('.filters-toolbar__action-button');
  if (!filterButtons) return;

  filterButtons.forEach((button) => {
    const termId = button.getAttribute('data-term-id');
    button.addEventListener('click', (e) => filterPosts(e));
  });
}

function loadMoreNewsInit() {
  const loadAllButton = document.querySelector('#load-all-news');
  const loadMoreButton = document.querySelector('#load-more-news');

  // if (!loadAllButton) return;
  loadAllButton.addEventListener('click', hydrateNewsFeedWithAllPosts);

  // if (!loadMoreButton) return;
  loadMoreButton.addEventListener('click', loadMorePosts);
}

export default function archiveNewsInit() {
  const filterNewsToolbar = document.querySelector('.filters-toolbar--archive-news');
  if (!filterNewsToolbar) return;

  filterNewsInit();
  loadMoreNewsInit();
}
