import { gsap, Power1 } from 'gsap'
import { getCookie } from '../../util/utils'

export default (() => {
  const decorGrid = document.querySelectorAll('.decor-filter .decor-grid [data-grid]')
  const decorContainer = document.querySelector('.decors-container')

    const timelineBt = gsap.timeline({
    })

    timelineBt.fromTo(decorContainer, {
        opacity: 0,
        y: 20,
    }, {
        opacity: 1,
        ease: Power1.easeOut,
        y: 0,
    })

    timelineBt.pause()

  if(decorContainer) {
      starterCookie()
      initializeResize()
      decorGrid.forEach(current => {
        current.addEventListener('click', () => {
          let currentCookie = getCookie('grid')
    
          if (current.dataset.grid == currentCookie) {
            current.classList.add('active')
          }
    
          const gridSize = current.dataset.grid
          current.classList.add('active')
    
          decorGrid.forEach(selector => {
            if (selector != current) {
              selector.classList.remove('active')
            }
          })
    
          resizeGrid(currentCookie, gridSize)
        })
      })
    
      function starterCookie (defaultCookie = 'grid-large') {
        let cookie = getCookie('grid')
    
        if(!cookie) {
            const defaultValue = decorContainer.dataset.default
            document.cookie = 'grid' + '=' + defaultValue + ';domain=;path=/';
        }
      }
    
      function initializeResize() {
        let cookie = getCookie('grid')
        timelineBt.play()
    
        decorGrid.forEach(current => {
          if (current.dataset.grid == cookie) {
            current.classList.add('active')
          }
        })
    
        if (starterCookie) {
          decorContainer.classList.add(cookie)
        }
      }
    
      function resizeGrid(oldCookie, newCookie) {
        if (decorContainer) {
          if (oldCookie) {
            decorContainer.classList.remove(oldCookie)
            document.cookie = 'grid' + '=; Max-Age=-99999999;';
          }
    
          if (newCookie) {
            decorContainer.classList.add(newCookie)
            document.cookie = 'grid' + '=' + newCookie + ';domain=;path=/';
          }
        }
      }
  }
})()