"use client";

import { useEffect, useRef, useState } from "react";
import { useUnreadCount } from "@/lib/queries/use-notifications";
import { NotificationDropdown } from "./notification-dropdown";

export interface NotificationBellProps {
  seeAllHref?: string;
}

export function NotificationBell({ seeAllHref = "/notifications" }: NotificationBellProps = {}) {
  const [open, setOpen] = useState(false);
  const { data: unread = 0 } = useUnreadCount();
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const badgeText = unread > 9 ? "9+" : String(unread);

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-label={`Notifications${unread > 0 ? ` (${unread} unread)` : ""}`}
        className="relative text-lg text-bone/80 hover:text-terracotta"
      >
        <span aria-hidden>🔔</span>
        {unread > 0 ? (
          <span className="absolute -top-1 -right-2 min-w-[1.25rem] h-5 px-1 rounded-full bg-terracotta text-[10px] font-semibold text-bone flex items-center justify-center">
            {badgeText}
          </span>
        ) : null}
      </button>
      {open ? <NotificationDropdown onClose={() => setOpen(false)} seeAllHref={seeAllHref} /> : null}
    </div>
  );
}
