<script setup>
// The attachment picker shared by every form that can carry a file.
//
// It only collects intent — a picked file, or a request to detach the existing
// one. Actually moving the bytes is the parent's job (applyAttachment), because
// the endpoint addresses a record that must already exist.
import { t, tSplit } from "../i18n";

defineProps({
  // The saved record, when editing; null while creating. Read for the name of
  // whatever is already attached.
  record: { type: Object, default: null },
  file: { type: Object, default: null },
  remove: { type: Boolean, default: false },
  // Null rather than a literal default: the fallback has to be resolved at
  // render time so it follows a language change, which a prop default evaluated
  // once at definition time would not.
  legend: { type: String, default: null },
  hint: { type: String, default: null },
});
const emit = defineEmits(["update:file", "update:remove"]);

function onFilePick(e) {
  const picked = e.target.files?.[0] || null;
  emit("update:file", picked);
  // Picking a replacement supersedes a pending detach.
  if (picked) emit("update:remove", false);
}
</script>

<template>
  <fieldset class="rounded-control border border-subtle p-3">
    <legend class="eyebrow px-1">{{ legend ?? t("attachment.legend") }}</legend>
    <input
      type="file"
      accept=".pdf,.jpg,.jpeg,.png,.webp,.heic"
      class="w-full text-sm text-body"
      @change="onFilePick"
    />
    <p v-if="record?.hasFile && !file && !remove" class="mt-2 flex items-center gap-2 text-xs text-muted">
      <span>{{ tSplit("attachment.attached", "name").before
        }}<span class="data text-strong">{{ record.fileName }}</span>{{ tSplit("attachment.attached", "name").after }}</span>
      <button type="button" class="font-medium text-danger hover:underline" @click="emit('update:remove', true)">
        {{ t("common.remove") }}
      </button>
    </p>
    <p v-else-if="remove" class="mt-2 flex items-center gap-2 text-xs text-muted">
      <span>{{ t("attachment.willBeRemoved") }}</span>
      <button type="button" class="font-medium text-brandtext hover:underline" @click="emit('update:remove', false)">
        {{ t("common.undo") }}
      </button>
    </p>
    <p class="mt-1.5 text-xs text-muted">{{ hint ?? t("attachment.hint") }}</p>
  </fieldset>
</template>
