"use client";

import { useEffect } from "react";
import { useUser } from "@/hooks/useUser";
import {
  acquireChatSocket,
  joinUserRoom,
  releaseChatSocket,
} from "@/lib/chat/socketClient";
import { ensureIdentityKeys } from "@/lib/e2ee";

export default function ChatSocketProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = useUser();

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

    const socket = acquireChatSocket();
    const uid = String(user._id);

    void ensureIdentityKeys(uid);

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

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

  return children;
}
