'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Menu, X } from 'lucide-react';
import { logout } from '@/app/actions/auth';
import { Logo } from '@/components/ui/Logo';
import { Button } from '@/components/ui/Button';
import { Container } from '@/components/ui/Container';
import { isAdmin } from '@/lib/auth/roles';
import { cn } from '@/lib/cn';
import { useMessages } from '@/i18n/client';
import { LanguageSwitcher } from './LanguageSwitcher';
import { UserMenu, type SessionUser } from './UserMenu';

interface NavbarProps {
  user: SessionUser | null;
  onGetStarted: () => void;
  /** Omitted during the free trial, which hides the pricing link. */
  onPricing?: () => void;
}

const mobileLink = 'border-b border-white/[0.06] py-4 text-[17px] font-medium text-white/90';

const LINKS = [
  { key: 'home', href: '#home' },
  { key: 'features', href: '#features' },
  { key: 'howItWorks', href: '#how-it-works' },
  { key: 'pricing', href: '#pricing' },
  { key: 'about', href: '#about' },
] as const;


export function Navbar({ user, onGetStarted, onPricing }: NavbarProps) {
  const t = useMessages().layout.nav;
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

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

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => {
      document.body.style.overflow = '';
    };
  }, [open]);

  const handleLink = (href: string) => (e: React.MouseEvent) => {
    setOpen(false);
    // Pricing has no section of its own — it opens the plan sheet.
    if (href === '#pricing') {
      e.preventDefault();
      onPricing?.();
    }
  };

  return (
    <header
      className={cn(
        'fixed inset-x-0 top-0 z-40 transition-[background-color,border-color,backdrop-filter] duration-300',
        scrolled || open
          ? 'border-b border-white/[0.06] bg-night-900/80 backdrop-blur-xl backdrop-saturate-150'
          : 'border-b border-transparent',
      )}
    >
      <Container className="flex h-16 items-center justify-between sm:h-[76px]">
        <Logo />

        <nav aria-label={t.main} className="hidden items-center gap-9 md:flex">
          {LINKS.filter((l) => l.key !== 'pricing' || onPricing).map((l) => (
            <a
              key={l.href}
              href={l.href}
              onClick={handleLink(l.href)}
              className="text-[13px] font-medium text-white/75 transition-colors hover:text-white"
            >
              {t[l.key]}
            </a>
          ))}
        </nav>

        <div className="hidden items-center gap-5 md:flex">
          <LanguageSwitcher />
          {user ? (
            <UserMenu user={user} />
          ) : (
            <Link
              href="/masuk"
              className="text-[13px] font-medium text-white/75 transition-colors hover:text-white"
            >
              {t.signIn}
            </Link>
          )}
          <Button variant="light" size="sm" onClick={onGetStarted}>
            {user ? t.auraPhoto : t.getStarted}
          </Button>
        </div>

        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          aria-expanded={open}
          aria-label={open ? t.closeMenu : t.openMenu}
          className="-mr-2 inline-flex size-10 items-center justify-center rounded-full text-white md:hidden"
        >
          {open ? <X className="size-5" /> : <Menu className="size-5" />}
        </button>
      </Container>

      {open && (
        <div className="h-[calc(100dvh-64px)] overflow-y-auto bg-night-900 md:hidden">
          <Container className="flex flex-col py-6">
            {LINKS.filter((l) => l.key !== 'pricing' || onPricing).map((l) => (
              <a
                key={l.href}
                href={l.href}
                onClick={handleLink(l.href)}
                className={mobileLink}
              >
                {t[l.key]}
              </a>
            ))}
            {user ? (
              <>
                <Link href="/akun" onClick={() => setOpen(false)} className={mobileLink}>
                  {t.myReports}
                </Link>
                {isAdmin(user.role) && (
                  <Link href="/admin" onClick={() => setOpen(false)} className={mobileLink}>
                    {t.adminPanel}
                  </Link>
                )}
              </>
            ) : (
              <Link href="/masuk" onClick={() => setOpen(false)} className={mobileLink}>
                {t.signIn}
              </Link>
            )}
            <LanguageSwitcher className="mt-6 self-start" />
            <Button
              variant="light"
              className="mt-8 w-full"
              withArrow
              onClick={() => {
                setOpen(false);
                onGetStarted();
              }}
            >
              {user ? t.auraPhoto : t.getStarted}
            </Button>
            {user && (
              <form action={logout} className="mt-3">
                <button type="submit" className="w-full py-3 text-sm font-medium text-white/60">
                  {t.signOut}
                </button>
              </form>
            )}
          </Container>
        </div>
      )}
    </header>
  );
}
