"use client";

import { createContext, ReactNode, useContext } from "react";

import {
  useChatsSocket,
  UseChatsSocketOptions,
} from "@/hooks/chats/useChatsSocket";

type ChatsContextValue = ReturnType<typeof useChatsSocket>;

const ChatsContext = createContext<ChatsContextValue | null>(null);

export function useChats() {
  const ctx = useContext(ChatsContext);
  if (!ctx) {
    throw new Error("useChats must be used within <ChatsProvider>");
  }
  return ctx;
}

interface ChatsProviderProps extends UseChatsSocketOptions {
  children: ReactNode;
}

export function ChatsProvider({ children, initialChats }: ChatsProviderProps) {
  const value = useChatsSocket({
    initialChats,
  });

  return (
    <ChatsContext.Provider value={value}>{children}</ChatsContext.Provider>
  );
}
