'use client';

import { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { LanguageSelector } from '../ui/LanguageSelector';

const NAV_LINKS = [
  { href: '/actu', label: 'Actu' },
  { href: '/', label: 'Présentation' },

  { href: '/documentation', label: 'Documentation' },
  { href: '/app', label: 'App' },
  { href: '/marketplace', label: 'MarketPlace' },
  { href: '/forum', label: 'Forum' },
  { href: '/shop', label: 'Boutique' },
  { href: '/association', label: "L'Asso" },
];

/** Map pathname → page-specific logo filename */
function getPageLogo(pathname: string): string {
  const map: Record<string, string> = {
    '/': '/images/logo-presentation.png',
    '/actu': '/images/logo-actu.png',
    '/documentation': '/images/logo-documentation.png',
    '/app': '/images/logo-app.png',
    '/marketplace': '/images/logo-marketplace.png',
    '/forum': '/images/logo-forum.png',
    '/shop': '/images/logo-shop.png',
    '/association': '/images/logo-association.png',
    '/account': '/images/logo-account.png',
    '/play': '/images/logo-play.png',
  };
  return map[pathname] || '/images/logo.png';
}

export function NavBar() {
  const pathname = usePathname();
  const [scrollProgress, setScrollProgress] = useState(0);
  const [menuOpen, setMenuOpen] = useState(false);
  const [viewportHeight, setViewportHeight] = useState(600);
  const navRef = useRef<HTMLElement>(null);

  const isHome = pathname === '/';
  const pageLogo = getPageLogo(pathname);

  useEffect(() => {
    if (!isHome) {
      setScrollProgress(0);
      return () => {};
    }
    setViewportHeight(window.innerHeight);
    const SCROLL_THRESHOLD = window.innerHeight * 0.8;
    const onScroll = () => {
      const progress = Math.min(window.scrollY / SCROLL_THRESHOLD, 1);
      setScrollProgress(progress);
    };
    const onResize = () => {
      setViewportHeight(window.innerHeight);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);
    onScroll();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
    };
  }, [isHome]);

  const maxLogoSize = Math.min(600, viewportHeight * 0.8);
  const logoSize = isHome ? Math.round(maxLogoSize * (1 - scrollProgress)) : 0;
  const bannerHeight = isHome ? Math.round(viewportHeight * (1 - scrollProgress)) : 0;
  const bannerOpacity = isHome ? Math.max(1 - scrollProgress * 1.2, 0) : 0;

  const scrollToNav = () => {
    if (navRef.current) {
      navRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    <>
      {/* Logo banner — only on home page */}
      {isHome && (
        <div
          className="w-full flex flex-col justify-center items-center relative"
          style={{
            background: 'rgba(10,10,10,0.98)',
            height: bannerHeight,
            overflow: 'hidden',
            opacity: bannerOpacity,
            transition: 'none',
          }}
        >
          <Link href="/" className="flex items-center">
            <Image
              src={pageLogo}
              alt="Ombres & Lumières — Mafiaz.World"
              width={600}
              height={600}
              priority
              style={{
                width: logoSize,
                height: 'auto',
                transition: 'none',
              }}
            />
            <h1 className="sr-only">Ombres &amp; Lumières — Mafiaz.World</h1>
          </Link>

          {/* "Ici" scroll indicator */}
          {scrollProgress < 0.3 && (
            <button
              onClick={scrollToNav}
              className="absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-1 transition-opacity animate-bounce z-10"
              style={{
                opacity: Math.max(1 - scrollProgress * 4, 0),
                color: 'var(--color-gold)',
              }}
            >
              <span className="text-sm font-bold tracking-widest uppercase">Ici</span>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 5v14" /><path d="m19 12-7 7-7-7" />
              </svg>
            </button>
          )}
        </div>
      )}

      {/* Sticky nav bar */}
      <nav
        ref={navRef}
        className="w-full shrink-0 sticky top-0 z-50 px-4 lg:px-6 py-2"
        style={{
          background: 'rgba(10,10,10,0.95)',
          borderBottom: '1px solid var(--border-dark)',
          backdropFilter: 'blur(12px)',
        }}
      >
        {/* ═══ DESKTOP (lg+) ═══ */}
        <div className="hidden lg:flex items-center justify-between">
          <Link href="/" className="flex-shrink-0">
            <Image src={pageLogo} alt="Ombres & Lumières" width={38} height={38} priority style={{ width: 38, height: 38 }} />
          </Link>

          <div className="flex items-center gap-3 flex-1 justify-center">
            {NAV_LINKS.map((link) => {
              const isActive = pathname === link.href;
              return (
                <Link
                  key={link.href}
                  href={link.href}
                  className="text-sm font-medium transition-colors hover:opacity-80 px-2"
                  style={{ color: isActive ? 'var(--color-gold)' : 'var(--text-secondary)' }}
                >
                  {link.label}
                </Link>
              );
            })}
          </div>

          <div className="flex items-center gap-2.5">
            <Link
              href="/play"
              className="px-4 py-1.5 rounded text-sm font-bold transition-all hover:scale-105"
              style={{
                background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
                color: 'white',
                boxShadow: '0 0 20px rgba(196,30,30,0.3)',
              }}
            >
              Jouer
            </Link>
            <Link
              href="/account"
              className="p-1.5 rounded-lg transition-all hover:bg-white/5 flex items-center"
              style={{ color: 'var(--color-gold)' }}
              title="Mon Compte"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
              </svg>
            </Link>
            <LanguageSelector />
          </div>
        </div>

        {/* ═══ TABLET (md to lg) ═══ */}
        <div className="hidden md:flex lg:hidden items-center justify-between">
          <Link href="/" className="flex-shrink-0">
            <Image src={pageLogo} alt="Ombres & Lumières" width={38} height={38} priority style={{ width: 38, height: 38 }} />
          </Link>

          {/* Menu + Jouer centered */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => setMenuOpen(!menuOpen)}
              className="flex items-center gap-2 px-4 py-1.5 transition-all hover:bg-white/5"
              style={{ color: 'var(--text-secondary)', border: '1px solid var(--border-dark)', borderRadius: 5 }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                {menuOpen ? <><path d="M18 6 6 18"/><path d="M6 6l12 12"/></> : <><path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h16"/></>}
              </svg>
              <span className="text-sm font-medium">Menu</span>
            </button>
            <Link
              href="/play"
              className="px-4 py-1.5 rounded text-sm font-bold transition-all hover:scale-105"
              style={{
                background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
                color: 'white',
                boxShadow: '0 0 15px rgba(196,30,30,0.3)',
              }}
            >
              Jouer
            </Link>
          </div>

          {/* Language far right */}
          <div className="flex items-center gap-2.5">
            <Link
              href="/account"
              className="p-1.5 rounded-lg transition-all hover:bg-white/5 flex items-center"
              style={{ color: 'var(--color-gold)' }}
              title="Mon Compte"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
              </svg>
            </Link>
            <LanguageSelector />
          </div>
        </div>

        {/* ═══ MOBILE (<md) ═══ */}
        <div className="flex md:hidden items-center justify-between">
          {/* Left: Logo + Menu SVG */}
          <div className="flex items-center gap-2">
            <Link href="/" className="flex-shrink-0">
              <Image src={pageLogo} alt="Ombres & Lumières" width={32} height={32} priority style={{ width: 32, height: 32 }} />
            </Link>
            <button
              onClick={() => setMenuOpen(!menuOpen)}
              className="p-1.5 rounded-lg transition-all hover:bg-white/5"
              style={{ color: 'var(--text-secondary)' }}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                {menuOpen ? <><path d="M18 6 6 18"/><path d="M6 6l12 12"/></> : <><path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h16"/></>}
              </svg>
            </button>
          </div>

          {/* Center: Jouer */}
          <Link
            href="/play"
            className="px-4 py-1.5 rounded text-sm font-bold transition-all hover:scale-105"
            style={{
              background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
              color: 'white',
              boxShadow: '0 0 15px rgba(196,30,30,0.3)',
            }}
          >
            Jouer
          </Link>

          {/* Right: Account + Language */}
          <div className="flex items-center gap-1.5">
            <Link
              href="/account"
              className="p-1.5 rounded-lg transition-all hover:bg-white/5 flex items-center"
              style={{ color: 'var(--color-gold)' }}
              title="Mon Compte"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
              </svg>
            </Link>
            <LanguageSelector />
          </div>
        </div>
      </nav>

      {/* Dropdown menu (tablet + mobile) */}
      {menuOpen && (
        <div
          className="lg:hidden fixed inset-x-0 top-[52px] z-40 p-4 space-y-2"
          style={{
            background: 'rgba(10,10,10,0.98)',
            borderBottom: '1px solid var(--border-dark)',
          }}
        >
          {NAV_LINKS.map((link) => {
            const isActive = pathname === link.href;
            return (
              <Link
                key={link.href}
                href={link.href}
                onClick={() => setMenuOpen(false)}
                className="block py-2 px-3 rounded text-sm font-medium"
                style={{
                  color: isActive ? 'var(--color-gold)' : 'var(--text-secondary)',
                  background: isActive ? 'rgba(196,30,30,0.1)' : 'transparent',
                }}
              >
                {link.label}
              </Link>
            );
          })}
          <Link
            href="/account"
            onClick={() => setMenuOpen(false)}
            className="block py-2 px-3 rounded text-sm font-medium"
            style={{
              color: pathname === '/account' ? 'var(--color-gold)' : 'var(--text-secondary)',
              background: pathname === '/account' ? 'rgba(196,30,30,0.1)' : 'transparent',
            }}
          >
            Mon Compte
          </Link>
          <Link
            href="/play"
            onClick={() => setMenuOpen(false)}
            className="block py-2 px-3 rounded text-sm font-bold text-center mt-3"
            style={{
              background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
              color: 'white',
            }}
          >
            Jouer
          </Link>
        </div>
      )}
    </>
  );
}
