'use client';

import { useEffect, useRef, useState } from 'react';

import { motion } from 'framer-motion';
import { FiRefreshCw } from 'react-icons/fi';

import MenuBar from '@/components/header/MenuBar';

import { useAuth } from '@/contexts/AuthContext';

import MobileMenu from './MobileMenu';

export default function Header() {
  const [isMenuOpen, setIsMenuOpen] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isHeaderVisible, setIsHeaderVisible] = useState<boolean>(true);
  const [lastScroll, setLastScroll] = useState<number>(0);
  const headerRef = useRef<HTMLDivElement | null>(null);
  const { isSuperAdmin } = useAuth();

  const handleRevalidate = async () => {
    setIsLoading(true);

    try {
      const res = await fetch('/api/revalidate-path', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pathname: window.location.pathname }),
      });
      const data = await res.json();
      if (data.revalidated) {
        // Hard refresh
        window.location.reload();
      }
    } catch (err) {
      console.error('Revalidation error:', err);
    }

    setIsLoading(false);
  };

  const toggleMobileMenu = () => {
    setIsMenuOpen((prevState) => !prevState);
  };

  useEffect(() => {
    const handleScroll = () => {
      const currentScroll = window.scrollY;

      if (currentScroll > lastScroll && currentScroll > 80) {
        // when scrolling down && not on top
        setIsHeaderVisible(false);
      } else {
        // when scrolling up
        setIsHeaderVisible(true);
      }

      setLastScroll(currentScroll);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [lastScroll]);

  // Bináris: ha látszik → header teljes magassága, ha nem → 0
  useEffect(() => {
    const el = headerRef.current;
    if (!el) return;

    const setVar = () => {
      const full = el.offsetHeight; // 56 / 80 / 100 a breakpointhoz igazodva
      const value = isHeaderVisible ? full : 0;
      document.documentElement.style.setProperty('--header-h', `${value}px`);
    };

    setVar();
    window.addEventListener('resize', setVar);
    return () => window.removeEventListener('resize', setVar);
  }, [isHeaderVisible]);

  return (
    <>
      <motion.header
        id="site-header"
        ref={headerRef}
        className="fixed top-0 left-0 right-0 z-50 h-[60px] md:h-[68px] lg:h-[76px] border-b border-black/10 bg-white/95 backdrop-blur"
        initial={{ y: 0 }}
        animate={{ y: isHeaderVisible ? 0 : -100 }}
        transition={{ duration: 0.25 }}
        onUpdate={(latest) => {
          const el = headerRef.current;
          if (!el) return;
          const h = el.offsetHeight;
          const y = typeof latest.y === 'number' ? latest.y : 0; // 0...-100
          const visible = Math.max(0, Math.min(h, h + y)); // h + (-abs) => clamp
          document.documentElement.style.setProperty('--header-h', `${visible}px`);
        }}
      >
        <div className="w-full h-full items-center">
          {isSuperAdmin && (
            <button
              onClick={handleRevalidate}
              className="fixed top-[10px] left-[10px] z-[9999] px-3 py-3 rounded bg-red-100 text-red-700 font-bold shadow-lg flex items-center gap-2 hover:bg-red-200 transition group"
              disabled={isLoading}
            >
              <motion.span
                whileHover={{ rotate: 360 }}
                transition={{ duration: 0.6, ease: 'easeInOut' }}
                className="flex"
              >
                <FiRefreshCw className="text-red-500 text-lg" />
              </motion.span>
            </button>
          )}

          <MenuBar isMenuOpen={isMenuOpen} toggleMobileMenu={toggleMobileMenu} />
        </div>
      </motion.header>

      <MobileMenu isOpen={isMenuOpen} closeMenu={() => setIsMenuOpen(false)} />
    </>
  );
}
