import { createComponent } from "@wp/js/component-factory";

/**
 * TODO: layout switch button.
 * @param {HTMLElement} element
 * @param {string} layout
 */
export function CardList(element = null, layout = "feature") {
  const cardList = element ? initFromElement(element) : initFromScratch();
  let currentLayout = layout;


  let thumbSizeSetting = undefined;
  try {
    let cookies = getCookies();
    thumbSizeSetting = parseInt(cookies?.thumbSize);
    thumbSizeSetting = isNaN(thumbSizeSetting) ? undefined : thumbSizeSetting;
  } catch (e) {
    return cardList;
  }
  if (!thumbSizeSetting){
    addCookie("thumbSize","180", 399)
  }

  let defaultThumbSize = 180;
  let thumbSize = parseInt(thumbSizeSetting) === parseInt(defaultThumbSize) ? undefined: thumbSizeSetting;

  let cardListEl = document.querySelector('.card-list__items');

  if (cardListEl.parentNode.classList.contains("card-list--phone")){
      return cardList;
  }

  window.addEventListener('resize', () => updateThumbsizes(cardListEl, defaultThumbSize, thumbSize));
  updateThumbsizes(cardListEl, defaultThumbSize, thumbSize)

  return cardList;
}

/**
 * @param {HTMLElement} element
 */
function initFromElement(element) {
  /**
   * @type {HTMLDivElement}
   */
  const cardContainer = element.querySelector(".card-list__items");
  /**
   * @type {NodeListOf<HTMLElement>}
   */
  const itemListElements = element.querySelectorAll(".card-list__items > *");

  return {
    cardList: element,
    cardContainer,
    cardItems: Array.from(itemListElements),
  };
}

function initFromScratch() {
  /**
   * @type {HTMLElement}
   */
  const cardList = createComponent("card-list");
  /**
   * @type {HTMLDivElement}
   */
  const cardContainer = cardList?.querySelector(".card-list__items");
  /**
   * @type {HTMLElement[]}
   */
  const cardItems = [];

  return {
    cardList,
    cardContainer,
    cardItems,
  };
}


function getCookies(){
  return document.cookie.split(';').reduce((cookies, cookie) => (cookies[cookie.split('=')[0].trim()] = decodeURIComponent(cookie.split('=')[1]), cookies), {});
}

function setCookie(name, value, daysToExpire) {
  const date = new Date();
  date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
  const expires = "expires=" + date.toUTCString();
  document.cookie = name + "=" + value + "; " + expires + ";path=/";
}
function addCookie(name, newValue, daysToExpire) {
  const existingCookie = document.cookie
    .split(';')
    .find(cookie => cookie.trim().startsWith(name + '='));

  if (!existingCookie) {
    setCookie(name, newValue, daysToExpire);
  }
}
function updateThumbsizes(element, defaultSize, thumbSizeSetting){
  let thumbSize = thumbSizeSetting? thumbSizeSetting : defaultSize;
  if (!thumbSizeSetting){
    let viewportWidth = window.innerWidth;
    let offset = 24;
    let viewportWidthExcludingMargin = viewportWidth - offset;
    let howManyFit = viewportWidthExcludingMargin/thumbSize;

    if ( howManyFit < 2.0 && 1.5 < howManyFit) {
      thumbSize = viewportWidthExcludingMargin / 2;
    } else if( howManyFit > 12 ){
      thumbSize = defaultSize*1.5;
    }
  }
  element.style.setProperty('--card-size', `${thumbSize}px`);
}