"use client";

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

const ITEMS = [
  { label: "About us", href: "/about" },
  { label: "Editorial team", href: "/about/team" },
  { label: "Contact", href: "https://relevantmediaproperties.com/contact" },
  { label: "Advertise", href: "/about/advertise" },
];

export default function AboutDropdown() {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (!wrapRef.current) return;
      if (!wrapRef.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  return (
    <div ref={wrapRef} className="relative flex items-stretch">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-haspopup="true"
        aria-expanded={open}
        className="bb-browse-item gap-1 focus:outline-none focus-visible:ring-1 focus-visible:ring-[#1D4ED8]"
      >
        <span>ABOUT</span>
        <span aria-hidden="true" className="text-[10px]">▾</span>
      </button>
      {open && (
        <div
          role="menu"
          aria-label="About"
          className="absolute left-0 top-full mt-1 min-w-[200px] z-50 bg-[var(--color-background-primary,#0a0a0a)] border border-[#DCE6F2] text-[#e5e7eb] shadow-xl py-1"
          style={{ borderRadius: "var(--border-radius-md,6px)" }}
        >
          {ITEMS.map((it) => (
            <Link
              key={it.href}
              href={it.href}
              role="menuitem"
              onClick={() => setOpen(false)}
              className="flex items-center justify-between px-4 py-2 text-sm hover:bg-[#FFFFFF] hover:text-[var(--color-text-info,#60a5fa)] focus:outline-none focus-visible:bg-[#FFFFFF] transition-colors"
            >
              <span>{it.label}</span>
              <span aria-hidden="true" className="text-[10px] text-[#6b7280]">›</span>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
