'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { useT, useLocale } from '@/i18n';
import type { Locale } from '@/i18n';
import s from './Header.module.css';

export default function Header() {
  const t = useT();
  const { locale, setLocale } = useLocale();
  const pathname = usePathname();
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  const isHome = pathname === '/';

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

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

  const transparent = isHome && !scrolled && !menuOpen;

  const links = [
    { href: '/', label: t('nav_home') },
    { href: '/about', label: t('nav_about') },
    { href: '/features', label: t('nav_features') },
    { href: '/solutions', label: t('nav_solutions') },
    { href: '/developers', label: t('nav_developers') },
    { href: '/contact', label: t('nav_contact') },
  ];

  const toggleLang = () => {
    setLocale(locale === 'zh-CN' ? 'en-US' : 'zh-CN' as Locale);
  };

  const cls = [
    s.header,
    scrolled || menuOpen ? s.scrolled : '',
    transparent ? s.transparentText : '',
  ].join(' ');

  return (
    <header className={cls}>
      <div className={s.inner}>
        <Link href="/" className={s.logoArea}>
          <Image src="/logo.svg" alt="Genex" width={36} height={36} />
          <span className={s.brand}>Genex</span>
        </Link>

        <nav className={`${s.nav} ${menuOpen ? s.mobileOpen : ''}`}>
          {links.map((l) => (
            <Link
              key={l.href}
              href={l.href}
              className={`${s.navLink} ${pathname === l.href ? s.active : ''}`}
            >
              {l.label}
            </Link>
          ))}
          <div className={s.mobileActions}>
            <button className={s.langBtn} onClick={toggleLang}>
              {locale === 'zh-CN' ? 'EN' : '中文'}
            </button>
            <button className={s.ctaBtn}>{t('nav_register')}</button>
          </div>
        </nav>

        <div className={s.actions}>
          <button className={s.langBtn} onClick={toggleLang}>
            {locale === 'zh-CN' ? 'EN' : '中文'}
          </button>
          <button className={s.ctaBtn}>{t('nav_register')}</button>
        </div>

        <button
          className={s.menuToggle}
          onClick={() => setMenuOpen(!menuOpen)}
          aria-label="Menu"
        >
          <span />
          <span />
          <span />
        </button>
      </div>
    </header>
  );
}
