<template>
  <!-- Visually hidden; opened via openPicker() from a separate toolbar button -->
  <input
    ref="nativeInput"
    type="file"
    class="raclette-file-upload-input"
    :accept="accept"
    @change="handleNativeChange"
  />
</template>

<script setup lang="ts">
import { useTemplateRef } from "vue"

const props = defineProps({
  onFileLoaded: {
    type: Function,
    required: true,
  },
  accept: {
    type: String,
    default: "*/*",
  },
  readAs: {
    type: String,
    default: "text",
    validator: (value: string) => ["text", "arrayBuffer"].includes(value),
  },
})

const nativeInput = useTemplateRef<HTMLInputElement>("nativeInput")

const handleNativeChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) {
    input.value = ""
    return
  }

  const reader = new FileReader()

  reader.onload = () => {
    ;(props.onFileLoaded as (c: string | ArrayBuffer, f: File) => void)(
      reader.result as string | ArrayBuffer,
      file,
    )
    input.value = ""
  }

  reader.onerror = () => {
    input.value = ""
  }

  if (props.readAs === "arrayBuffer") {
    reader.readAsArrayBuffer(file)
  } else {
    reader.readAsText(file)
  }
}

/** Programmatically open the file picker (toolbar button should call this). */
const openPicker = () => {
  nativeInput.value?.click()
}

defineExpose({ openPicker, trigger: openPicker })
</script>

<style scoped>
.raclette-file-upload-input {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style>

