import { UniverDocsCorePreset } from '@univerjs/preset-docs-core'
import UniverPresetDocsCoreEnUS from '@univerjs/preset-docs-core/locales/en-US'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'

import '@univerjs/preset-docs-core/lib/index.css'

let univerInstance = null;
let univerAPIInstance = null;

export function initializeUniver(containerElement) {
  // Limpiar instancia anterior
  if (univerInstance) {
    try {
      univerInstance.dispose();
    } catch (error) {
      console.warn('Error disposing previous Univer instance:', error);
    }
    univerInstance = null;
  }

  if (univerAPIInstance) {
    try {
      univerAPIInstance.dispose();
    } catch (error) {
      console.warn('Error disposing previous Univer API instance:', error);
    }
    univerAPIInstance = null;
  }

  try {
    console.log('Initializing Univer with container:', containerElement);
    
    const { univer, univerAPI } = createUniver({
      locale: LocaleType.EN_US,
      locales: {
        [LocaleType.EN_US]: mergeLocales(
          UniverPresetDocsCoreEnUS,
        ),
      },
      presets: [
        UniverDocsCorePreset({
          container: containerElement,
        }),
      ],
    });

    // Crear documento inicial
    univerAPI.createUniverDoc({});

    univerInstance = univer;
    univerAPIInstance = univerAPI;
    
    console.log('Univer initialized successfully');
    return { univer, univerAPI };
  } catch (error) {
    console.error('Error initializing Univer:', error);
    return null;
  }
}

export function getUniverInstance() {
  return { univer: univerInstance, univerAPI: univerAPIInstance };
}

export function disposeUniver() {
  if (univerInstance) {
    try {
      univerInstance.dispose();
    } catch (error) {
      console.warn('Error disposing Univer:', error);
    }
    univerInstance = null;
  }

  if (univerAPIInstance) {
    try {
      univerAPIInstance.dispose();
    } catch (error) {
      console.warn('Error disposing Univer API:', error);
    }
    univerAPIInstance = null;
  }
}