"use client"

import Image from "next/image";
import Link from "next/link";
import { useState, useEffect, useRef} from "react";

export default function Navbar() {
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                dropdownRef.current &&
                !dropdownRef.current.contains(event.target as Node)
            ) {
                setIsDropdownOpen(false);
            }
        };
    
        const handleEscapeKey = (event: KeyboardEvent) => {
            if (event.key === "Escape") {
                setIsDropdownOpen(false);
            }
        };
    
        document.addEventListener("mousedown", handleClickOutside);
        document.addEventListener("keydown", handleEscapeKey);
    
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
            document.removeEventListener("keydown", handleEscapeKey);
        };
    }, []);

    return (
        <div className="w-full flex h-14 border-b border-neutral-300 text-black">
            <div className="my-1 flex aspect-square ml-2 mr-4">
                <Link href="/">
                    <Image height={2000} width={2000} alt="Background Image" src="/logo.png"></Image>
                </Link>
                {/* <p className="m-auto text-sm">Logo</p> */}
            </div>
            <div className="flex">
                <button className="px-6">Earthquakes</button>
                <button className="px-6">Observatories</button>
                <button className="px-6">Warehouse</button>
                <button className="px-6">Shop</button>

                <div className="my-auto relative">
                    <button
                        className="px-6"
                        onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                    >
                        About Us
                    </button>

                    {isDropdownOpen && (
                        <div ref={dropdownRef} className="absolute top-full left-0 mt-4 w-40 bg-white border border-neutral-300 rounded-lg shadow-lg z-50">
                            <ul>
                                <li className="px-4 py-2 hover:bg-neutral-100 rounded-lg cursor-pointer">Our Mission</li>
                                <li className="px-4 py-2 hover:bg-neutral-100 cursor-pointer">The Team</li>
                                <li className="px-4 py-2 hover:bg-neutral-100 rounded-lg cursor-pointer">Contact Us</li>
                            </ul>
                        </div>
                    )}
                </div>
            </div>
            <div className="flex-grow"></div>
            <div className="my-2 mr-2 w-10 flex border rounded-full">
                <p className="m-auto text-sm">User</p>
            </div>
        </div>
    );
}
