import React, { createContext, useContext, useState, useEffect } from 'react';
import * as monaco from 'monaco-editor';

interface MonacoContextType {
  monaco: typeof monaco | null;
  isMonacoLoading: boolean;
}

const MonacoContext = createContext<MonacoContextType>({
  monaco: null,
  isMonacoLoading: true
});

export const useMonaco = () => useContext(MonacoContext);

export const MonacoProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
  const [monacoInstance, setMonacoInstance] = useState<typeof monaco | null>(null);
  const [isMonacoLoading, setIsMonacoLoading] = useState(true);

  useEffect(() => {
    if (!monacoInstance) {
      import('monaco-editor').then(monaco => {
        if (!monaco.languages.getLanguages().some(lang => lang.id === 'xml')) {
          monaco.languages.register({ id: 'xml' });
        }
        
        setMonacoInstance(monaco);
        setIsMonacoLoading(false);
      }).catch(error => {
        console.error('Failed to load Monaco editor:', error);
        setIsMonacoLoading(false);
      });
    }
  }, [monacoInstance]);

  return (
    <MonacoContext.Provider value={{ monaco: monacoInstance, isMonacoLoading }}>
      {children}
    </MonacoContext.Provider>
  );
};