import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import ElementPlus from 'element-plus';
import { createApp, h } from 'vue';
import ContactUs from '@/components/ContactUs/index.vue';
import type { ContactScenario, ContactType } from '@/components/ContactUs/index.vue';
import router from '@/routers';
import store from '@/stores';

export interface ShowContactUsOptions {
  scenario?: ContactScenario;
  customTypes?: ContactType;
}

export function showContactUs(options: ShowContactUsOptions = {}) {
  const div = document.createElement('div');
  document.body.appendChild(div);

  const app = createApp({
    render() {
      return h(ContactUs, {
        scenario: options.scenario || 'regular',
        customTypes: options.customTypes,
        onClose: () => {
          app.unmount();
          div.remove();
        },
      });
    },
  });

  // 关键：必须在 mount 之前按顺序注册所有依赖
  app.use(store);      // 1. 先注册 store
  app.use(router);     // 2. 再注册 router
  app.use(ElementPlus); // 3. 最后注册 ElementPlus

  // 注册 Element Plus 图标
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
  }

  // 最后才挂载应用
  app.mount(div);
}
