'use client';

import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import LanguageSwitcher from '../../components/LanguageSwitcher';
import { getLocaleFromPathname } from '../../lib/i18n';

// Server-side translation function for client components
function getServerTranslations(locale: string) {
  const translations = {
    fi: { home: 'Etusivu', services: 'Palvelut', contact: 'Yhteystiedot' },
    en: { home: 'Home', services: 'Services', contact: 'Contact' },
    sv: { home: 'Hem', services: 'Tjänster', contact: 'Kontakt' }
  };

  return translations[locale as keyof typeof translations] || translations.fi;
}

export default function Header() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const pathname = usePathname();
  const locale = getLocaleFromPathname(pathname);
  const t = getServerTranslations(locale);

  const normalize = (p: string | null) => {
    if (!p) return '/';
    // Remove /sirentuomala prefix
    let normalized = p.replace(/^\/sirentuomala/, '') || '/';
    // Remove locale prefix for non-Finnish locales
    if (locale !== 'fi') {
      normalized = normalized.replace(/^\/(en|sv)/, '') || '/';
    }
    return normalized;
  };
  const current = normalize(pathname);

  // Generate locale-aware URLs
  const getLocalizedUrl = (path: string) => {
    if (locale === 'fi') {
      // Map English/Swedish paths to Finnish paths
      if (path === '/services') return '/palvelut';
      if (path === '/contact') return '/yhteystiedot';
      return path;
    }
    return `/${locale}${path}`;
  };

  const isActive = (href: string) => {
    const target = normalize(href);
    if (target === '/') return current === '/';

    // Handle Finnish paths
    if (locale === 'fi') {
      return current === target || current.startsWith(target + '/');
    }

    // Handle English/Swedish paths
    if (target === '/services') {
      return current === '/services' || current.startsWith('/services/');
    }
    if (target === '/contact') {
      return current === '/contact';
    }

    return current === target || current.startsWith(target + '/');
  };

  const linkBase =
    'text-sm sm:text-base lg:text-lg font-semibold px-5 py-3 rounded-full transition-colors duration-200';
  const linkInactive = 'text-slate-700 hover:text-slate-900 bg-slate-100 hover:bg-slate-200';
  const linkActive = 'text-white ring-1 ring-slate-500';

  return (
    <header className="backdrop-blur shadow-sm fixed top-0 left-0 right-0 z-50" style={{ backgroundColor: 'var(--header-bg)' }}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-20">
          {/* Logo */}
          <div className="flex-shrink-0">
            <Link href={getLocalizedUrl('/')} aria-label="Siren & Tuomala Oy">
              <Image
                src="/legacy/Artboard-2@2x.png"
                alt="Siren & Tuomala Oy"
                width={620}
                height={172}
                className="h-[90px] w-auto opacity-100"
                priority
              />
            </Link>
          </div>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex items-center space-x-3">
            <Link
              href={getLocalizedUrl('/')}
              className={`${linkBase} ${isActive('/') ? linkActive : linkInactive}`}
              style={isActive('/') ? { backgroundColor: '#134074' } : {}}
              aria-current={isActive('/') ? 'page' : undefined}
            >
              {t.home}
            </Link>
            <Link
              href={getLocalizedUrl('/services')}
              className={`${linkBase} ${isActive('/services') || isActive('/palvelut') ? linkActive : linkInactive}`}
              style={isActive('/services') || isActive('/palvelut') ? { backgroundColor: '#134074' } : {}}
              aria-current={isActive('/services') || isActive('/palvelut') ? 'page' : undefined}
            >
              {t.services}
            </Link>
            <Link
              href={getLocalizedUrl('/contact')}
              className={`${linkBase} ${isActive('/contact') || isActive('/yhteystiedot') ? linkActive : linkInactive}`}
              style={isActive('/contact') || isActive('/yhteystiedot') ? { backgroundColor: '#134074' } : {}}
              aria-current={isActive('/contact') || isActive('/yhteystiedot') ? 'page' : undefined}
            >
              {t.contact}
            </Link>
            <LanguageSwitcher />
          </nav>

          {/* Mobile menu button */}
          <div className="md:hidden">
            <button
              onClick={() => setIsMenuOpen(!isMenuOpen)}
              className="text-slate-600 hover:text-slate-900 p-2"
            >
              <svg className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                {isMenuOpen ? (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                ) : (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                )}
              </svg>
            </button>
          </div>
        </div>

        {/* Mobile Navigation */}
        {isMenuOpen && (
          <div className="md:hidden">
            <div className="px-2 pt-2 pb-3 space-y-2 sm:px-3 border-t border-slate-200" style={{ backgroundColor: 'var(--header-bg)' }}>
              <Link
                href={getLocalizedUrl('/')}
                className={`${linkBase} block ${isActive('/') ? linkActive : linkInactive}`}
                style={isActive('/') ? { backgroundColor: '#134074' } : {}}
                aria-current={isActive('/') ? 'page' : undefined}
                onClick={() => setIsMenuOpen(false)}
              >
                {t.home}
              </Link>
              <Link
                href={getLocalizedUrl('/services')}
                className={`${linkBase} block ${isActive('/services') || isActive('/palvelut') ? linkActive : linkInactive}`}
                style={isActive('/services') || isActive('/palvelut') ? { backgroundColor: '#134074' } : {}}
                aria-current={isActive('/services') || isActive('/palvelut') ? 'page' : undefined}
                onClick={() => setIsMenuOpen(false)}
              >
                {t.services}
              </Link>
              <Link
                href={getLocalizedUrl('/contact')}
                className={`${linkBase} block ${isActive('/contact') || isActive('/yhteystiedot') ? linkActive : linkInactive}`}
                style={isActive('/contact') || isActive('/yhteystiedot') ? { backgroundColor: '#134074' } : {}}
                aria-current={isActive('/contact') || isActive('/yhteystiedot') ? 'page' : undefined}
                onClick={() => setIsMenuOpen(false)}
              >
                {t.contact}
              </Link>

              {/* Mobile Language Switcher */}
              <div className="pt-2 border-t border-slate-300">
                <LanguageSwitcher />
              </div>
            </div>
          </div>
        )}
      </div>
    </header>
  );
}
