<template>
  <div
    class="simple-file-upload"
    ref="upload"
  >
    <component
      :is="button"
      @click="clickUploadCare"
    />
    <simple-file-upload-hidden-input @link-change-url="$emit('link-change-url', $event)" />
  </div>
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, ref } from 'vue';
export interface Props {
  value: string;
  withText: boolean;
}
const SimpleFileUploadHiddenInput = defineAsyncComponent(
  () => import('@/components/ui/file-upload/SimpleFileUploadHiddenInput.vue')
);
const SimpleFileUploadIcon = defineAsyncComponent(() => import('@/components/ui/file-upload/SimpleFileUploadIcon.vue'));
const SimpleFileUploadIconAndText = defineAsyncComponent(
  () => import('@/components/ui/file-upload/SimpleFileUploadIconAndText.vue')
);

const props = withDefaults(defineProps<Props>(), {
  value: '',
  withText: false,
});

const button = computed(() => {
  if (props.withText) {
    return SimpleFileUploadIconAndText;
  }
  return SimpleFileUploadIcon;
});

const upload = ref<HTMLElement | null>(null);

const clickUploadCare = () => {
  // workaround for styling the uploadcare widget
  const el = upload.value;
  if (el) {
    let btn: HTMLElement = el.querySelector('.uploadcare--widget__button') as HTMLElement;
    if (btn) {
      btn.click();
    }
  }
};
</script>

<style lang="scss">
// todo: re-add scoped when we're on vite
@import 'styles/_helpers';

.simple-file-upload {
  height: 25px;
  overflow: hidden;
  cursor: pointer;

  &__link {
    display: inline-block;
    overflow: hidden;
    width: 25px;
    height: 25px;
  }
}

/* :deep(.uploadcare--widget) { */
.uploadcare--widget {
  display: none;
}
</style>
