'use client'
import { useHeaderTheme } from '@/providers/HeaderTheme'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import React, { useEffect, useState } from 'react'

import type { Header } from '@/payload-types'
import { Logo } from '@/components/Logo/Logo'
import { HeaderNav } from './Nav'
import { useThemeMode } from '@/hooks/useThemeMode'

function ToggleButton() {
  const { isDark, toggle } = useThemeMode()
  return (
    <button
      onClick={toggle}
      aria-label="Toggle theme"
      className="flex items-center justify-center w-8 h-8 rounded-full transition-colors text-foreground/50 hover:text-foreground/80 hover:bg-foreground/8"
    >
      <i className={isDark ? 'ti ti-sun' : 'ti ti-moon'} style={{ fontSize: 16 }} />
    </button>
  )
}

export const HeaderClient: React.FC<{ data: Header }> = ({ data }) => {
  const [theme, setTheme] = useState<string | null>(null)
  const [menuOpen, setMenuOpen] = useState(false)
  const { headerTheme, setHeaderTheme } = useHeaderTheme()
  const pathname = usePathname()

  useEffect(() => {
    setHeaderTheme(null)
    setMenuOpen(false)
  }, [pathname, setHeaderTheme])

  useEffect(() => {
    if (headerTheme && headerTheme !== theme) setTheme(headerTheme)
  }, [headerTheme, theme])

  return (
    <header className="relative z-20" {...(theme ? { 'data-theme': theme } : {})}>
      <div className="container">
        <div className="py-5 flex justify-between items-center">
          <Link href="/">
            <Logo loading="eager" priority="high" className="invert dark:invert-0" />
          </Link>

          {/* Desktop nav */}
          <div className="hidden md:flex items-center gap-3">
            <HeaderNav data={data} />
            <ToggleButton />
          </div>

          {/* Mobile right side */}
          <div className="flex md:hidden items-center gap-2">
            <ToggleButton />
            <button
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label="Toggle menu"
              className="flex items-center justify-center w-8 h-8 rounded-full text-foreground/50 hover:text-foreground/80 hover:bg-foreground/8 transition-colors"
            >
              <i className={menuOpen ? 'ti ti-x' : 'ti ti-menu-2'} style={{ fontSize: 18 }} />
            </button>
          </div>
        </div>

        {/* Mobile menu */}
        {menuOpen && (
          <div className="md:hidden pb-4 border-t border-foreground/8 pt-4 flex flex-col gap-1">
            <HeaderNav data={data} />
          </div>
        )}
      </div>
    </header>
  )
}
