"use client";

import { NavLink } from './NavLink';
import Link from 'next/link';
import { ThemeToggleButton } from '@/components/common/ThemeToggleButton';
import UserDropdown from '@/components/header/UserDropdown';
import { useOrganization } from '@/context/OrganizationContext';
import { BrandingLogo } from '@/components/common/BrandingLogo';
import { useEffect, useState } from 'react';
import { desktopNavigationItems } from '@/lib/appNavigation';

const navItems = desktopNavigationItems;

function OrganizationAwareLogo() {
  const { organization } = useOrganization();
  const [logo, setLogo] = useState<string | null>(null);
  useEffect(() => {
    const frame = requestAnimationFrame(() => {
      const element = document.getElementById('dynamic-branding-logo');
      setLogo(element?.getAttribute('data-logo') || null);
    });
    return () => cancelAnimationFrame(frame);
  }, []);
  if (logo) {
    return <BrandingLogo src={logo} alt={`${organization?.name || 'Tiar'} Logo`} width={160} height={48} className="h-12 w-auto object-contain" />;
  }

  return (
    <h1 className="text-2xl font-bold text-brand-600">
      {organization?.name || 'Tiar'}
    </h1>
  );
}

export function DesktopNavBar({ bannerVisible }: { readonly bannerVisible: boolean }) {

  return (
    <nav
      className={`fixed hidden md:flex bg-white border-gray-200 shadow-sm dark:border-gray-800 dark:bg-gray-900 left-0 right-0 z-40 ${
        // If banner is visible, position navbar 48px from the top.
        // If not, position it at the very top.
        bannerVisible ? 'top-[48px]' : 'top-0'
        }`}
      style={{ backgroundColor: 'var(--tenant-background-color)' }}
    >
      <div className="container mx-auto px-4">
        <div className="flex justify-between items-center h-16">
          <div className="flex items-center space-x-8">
            <Link href="/" className="flex items-center space-x-2">
              <OrganizationAwareLogo />
            </Link>
            <div className="flex items-center space-x-6">
              {navItems.map((item) => (
                <NavLink key={item.href} href={item.href}>
                  {item.label}
                </NavLink>
              ))}
            </div>
          </div>
          <div className="flex items-center space-x-4">
            <ThemeToggleButton />
            <UserDropdown />
          </div>
        </div>
      </div>
    </nav>
  );
}
