'use client';

import { useState, useEffect } from 'react';
import type * as MonacoEditor from 'monaco-editor';

import { setupMonacoWorkers } from '../workers/setup';
import type { UseMonacoReturn } from '../types';

/**
 * Hook to load and access Monaco Editor instance
 *
 * Handles:
 * - Dynamic import of Monaco (client-side only)
 * - Web worker configuration
 * - Loading state management
 *
 * @example
 * ```tsx
 * const { monaco, isLoading, error } = useMonaco();
 *
 * if (isLoading) return <Spinner />;
 * if (error) return <Error message={error.message} />;
 *
 * // Use monaco API
 * monaco.editor.create(...)
 * ```
 */
export function useMonaco(): UseMonacoReturn {
  const [monaco, setMonaco] = useState<typeof MonacoEditor | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let mounted = true;

    async function loadMonaco() {
      try {
        // Setup workers first
        setupMonacoWorkers();

        // Dynamic import Monaco
        const monacoModule = await import('monaco-editor');

        if (mounted) {
          setMonaco(monacoModule);
          setIsLoading(false);
        }
      } catch (err) {
        if (mounted) {
          setError(err instanceof Error ? err : new Error('Failed to load Monaco Editor'));
          setIsLoading(false);
        }
      }
    }

    loadMonaco();

    return () => {
      mounted = false;
    };
  }, []);

  return { monaco, isLoading, error };
}
