"use client";

import { createContext, useContext, useState, useCallback } from "react";
import type { ClientView } from "@/lib/client-view";

interface ChatContextValue {
  isOpen: boolean;
  selectedPhaseId: string | null;  // null = "Generale"
  phases: ClientView["phases"];
  clientId: string;
  openChat: (phaseId?: string) => void;
  closeChat: () => void;
}

const ChatContext = createContext<ChatContextValue | null>(null);

export function useChatContext() {
  const ctx = useContext(ChatContext);
  if (!ctx) throw new Error("useChatContext must be used inside ChatProvider");
  return ctx;
}

export function ChatProvider({
  children,
  phases,
  clientId,
}: {
  children: React.ReactNode;
  phases: ClientView["phases"];
  clientId: string;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedPhaseId, setSelectedPhaseId] = useState<string | null>(null);

  const openChat = useCallback((phaseId?: string) => {
    setSelectedPhaseId(phaseId ?? null);
    setIsOpen(true);
  }, []);

  const closeChat = useCallback(() => {
    setIsOpen(false);
  }, []);

  return (
    <ChatContext.Provider value={{ isOpen, selectedPhaseId, phases, clientId, openChat, closeChat }}>
      {children}
    </ChatContext.Provider>
  );
}
