import { css, cx } from '@styled-system/css'
import { token } from '@styled-system/tokens'
import { type FC, useCallback, useEffect, useState } from 'react'
import SrJuggernautLogo from '@/components/assets/SrJuggernautLogo'
import MainMenu from '@/components/layout/fragments/MainMenu'
import srOnlyClass from '@/styles/srOnly'

const headerClass = css({
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',
  position: 'sticky',
  top: 0,
  transition: `background-color ${token('durations.slow')} ${token('easings.easeOutQuint')}`,
  zIndex: 1,
  flexShrink: 0
})

const headerUnscrolledClass = css({
  backgroundColor: 'transparent'
})

const headerScrolledClass = css({
  backgroundColor: 'neutral.2'
})

const headerContainerClass = css({
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  width: '100%',
  padding: 'md',
  maxWidth: {
    sm: 'breakpoint-sm',
    md: 'breakpoint-md',
    lg: 'breakpoint-lg',
    xl: 'breakpoint-xl',
    '2xl': 'breakpoint-2xl'
  }
})

const headerLogoLinkClass = css({
  color: 'neutral.12',
  cursor: 'pointer'
})

const headerLogoClass = css({
  fill: 'neutral.12',
  height: '30px',
  width: 'auto'
})

const Header: FC = () => {
  const [scrolled, setScrolled] = useState(false)

  const handleScroll = useCallback(() => {
    if (window.scrollY > 0) {
      setScrolled(true)
    } else {
      setScrolled(false)
    }
  }, [])

  useEffect(() => {
    if (typeof window === 'undefined') {
      return
    }
    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [handleScroll])

  return (
    <header
      className={cx(
        headerClass,
        scrolled ? headerScrolledClass : headerUnscrolledClass
      )}
    >
      <div className={headerContainerClass}>
        <a
          className={headerLogoLinkClass}
          href="/"
        >
          <SrJuggernautLogo className={headerLogoClass} />
          <span className={srOnlyClass}>Ir a la página principal</span>
        </a>
        <MainMenu />
      </div>
    </header>
  )
}

export default Header
