import { createApp, h } from 'vue';

import ImageCompressModal, {
  type ImageCompressModalResult,
} from '#/components/modal/ImageCompressModal.vue';

import type { PrepareImageUploadMeta } from '#/utils/prepare-image-upload';

export interface OpenImageCompressModalResult {
  file: File | null;
  meta?: PrepareImageUploadMeta;
}

export function openImageCompressModal(
  file: File,
): Promise<OpenImageCompressModalResult> {
  return new Promise((resolve) => {
    const container = document.createElement('div');
    document.body.append(container);

    const app = createApp({
      render() {
        return h(ImageCompressModal, {
          file,
          onResolve: (result: ImageCompressModalResult) => {
            app.unmount();
            container.remove();

            if (result.choice === 'cancel' || !result.file) {
              resolve({ file: null });
              return;
            }

            resolve({
              file: result.file,
              meta: result.meta,
            });
          },
        });
      },
    });

    app.mount(container);
  });
}
