import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import { getConfig } from './core/config';
import { registerManifests } from './core/widgets';
import { setDictionary } from './core/i18n';
import { useDocumentStore } from './stores/document';
import { useGlobalStore } from './stores/global';
import { useEditorStore } from './stores/editor';
import { vInlineEdit } from './canvas/inlineEdit';
import './styles/editor.css';

export const pinia = createPinia();

export function bootEditor(target: string | Element = '#zadex-editor') {
  const config = getConfig();
  setDictionary(config.i18n ?? {});
  registerManifests(config.widgets, config.commonControls);

  const app = createApp(App);
  app.use(pinia);
  app.directive('inline-edit', vInlineEdit);

  const global = useGlobalStore(pinia);
  global.loadFromConfig(config);
  const doc = useDocumentStore(pinia);
  doc.load(config.document, { postId: config.postId, title: config.postTitle, status: config.postStatus });
  // The page template lives in _wp_page_template (WordPress), not in the page settings meta.
  doc.loadPageSettings(config.pageSettings, typeof config.template === 'string' ? { page_template: config.template } : {});
  const editor = useEditorStore(pinia);
  document.documentElement.classList.toggle('zx-dark', editor.darkMode);
  document.documentElement.dir = config.isRtl ? 'rtl' : 'ltr';

  if (typeof window !== 'undefined' && window.location) {
    const params = new URLSearchParams(window.location.search);
    const panel = params.get('zx_panel');
    if (panel === 'global' || panel === 'settings' || panel === 'page' || panel === 'history' || panel === 'notes') {
      editor.setPanel(panel);
    }
  }

  app.mount(target);
  return app;
}

if (typeof window !== 'undefined' && window.ZADEX && document.getElementById('zadex-editor') && !(window as any).__ZADEX_MANUAL_BOOT__) {
  bootEditor();
}
