"use client";

import { useEffect } from "react";
import { useUser } from "@/hooks/useUser";
import { useQueryClient } from "@tanstack/react-query";
import {
  acquireChatSocket,
  joinUserRoom,
  releaseChatSocket,
} from "@/lib/chat/socketClient";

type IncomingNotification = {
  type?: string;
  title?: string;
  description?: string;
};

/**
 * Always-mounted, app-wide bridge: asks for browser Notification permission
 * once per user, then shows every live 'notification' socket event (emitted
 * server-side alongside NotificationModel.create) as an OS-level Notification.
 */
export default function NotificationBridge() {
  const user = useUser();
  const queryClient = useQueryClient();

  useEffect(() => {
    if (!user?._id) return;
    if (typeof Notification === "undefined") return;
    if (Notification.permission === "default") {
      void Notification.requestPermission();
    }
  }, [user?._id]);

  useEffect(() => {
    if (!user?._id) return;

    const socket = acquireChatSocket();
    const uid = String(user._id);
    const join = () => joinUserRoom(uid);
    socket.on("connect", join);
    if (socket.connected) join();

    const handleNotification = (payload: IncomingNotification) => {
      queryClient.invalidateQueries({ queryKey: ["notifications"] });

      if (
        typeof Notification === "undefined" ||
        Notification.permission !== "granted"
      ) {
        return;
      }

      try {
        const browserNotif = new Notification(payload.title || "مدستاگرام", {
          body: payload.description || "",
          icon: "/favicon.png",
        });
        browserNotif.onclick = () => window.focus();
      } catch {
        // برخی مرورگرها/وب‌ویوها از Notification API پشتیبانی نمی‌کنند
      }
    };

    socket.on("notification", handleNotification);

    return () => {
      socket.off("connect", join);
      socket.off("notification", handleNotification);
      releaseChatSocket();
    };
  }, [user?._id, queryClient]);

  return null;
}
