'use client';

import { createContext, useContext, useCallback, useRef, ReactNode } from 'react';
import type { VoiceCommandHandlers } from '@/hooks/useVoiceCommand';

// ─── Context 타입 정의 ───────────────────────────────────────────────
interface VoiceCommandContextType {
    /** 페이지별 핸들러 등록 */
    registerHandlers: (handlers: Partial<VoiceCommandHandlers>) => void;
    /** 핸들러 해제 */
    unregisterHandlers: () => void;
    /** 현재 등록된 핸들러 가져오기 */
    getHandlers: () => Partial<VoiceCommandHandlers>;
}

const VoiceCommandContext = createContext<VoiceCommandContextType | null>(null);

/**
 * 음성 명령 컨텍스트 프로바이더
 * 
 * 페이지별로 음성 명령 핸들러를 등록/해제할 수 있게 합니다.
 * 예: DocumentClient에서 편집/저장/공개 명령 핸들러 등록
 */
export function VoiceCommandContextProvider({ children }: { children: ReactNode }) {
    const handlersRef = useRef<Partial<VoiceCommandHandlers>>({});

    const registerHandlers = useCallback((handlers: Partial<VoiceCommandHandlers>) => {
        handlersRef.current = { ...handlersRef.current, ...handlers };
    }, []);

    const unregisterHandlers = useCallback(() => {
        handlersRef.current = {};
    }, []);

    const getHandlers = useCallback(() => {
        return handlersRef.current;
    }, []);

    return (
        <VoiceCommandContext.Provider value={{ registerHandlers, unregisterHandlers, getHandlers }}>
            {children}
        </VoiceCommandContext.Provider>
    );
}

/**
 * 음성 명령 컨텍스트 사용 훅
 */
export function useVoiceCommandContext() {
    const context = useContext(VoiceCommandContext);
    if (!context) {
        throw new Error('useVoiceCommandContext must be used within VoiceCommandContextProvider');
    }
    return context;
}
