
"use client";

import React, { createContext, useContext, useState, useRef } from "react";
import type { ReplyTo, Message, UserProfile } from "@/lib/types";

// This is the most basic context for app-wide state that doesn't fit elsewhere.
interface AppContextType {
    replyTo: ReplyTo | null;
    setReplyTo: React.Dispatch<React.SetStateAction<ReplyTo | null>>;
    privateReplyTo: UserProfile | null;
    setPrivateReplyTo: React.Dispatch<React.SetStateAction<UserProfile | null>>;
    messageCache: React.MutableRefObject<Map<string, Message[]>>;
}

const AppContext = createContext<AppContextType | null>(null);

export function useAppContext() {
    const context = useContext(AppContext);
    if (!context) {
        throw new Error("useAppContext must be used within an AppProvider");
    }
    return context;
}

export function AppProvider({ children }: { children: React.ReactNode }) {
    const [replyTo, setReplyTo] = useState<ReplyTo | null>(null);
    const [privateReplyTo, setPrivateReplyTo] = useState<UserProfile | null>(null);
    const messageCache = useRef(new Map<string, Message[]>());

    return (
        <AppContext.Provider value={{ replyTo, setReplyTo, privateReplyTo, setPrivateReplyTo, messageCache }}>
            {children}
        </AppContext.Provider>
    );
}
