<template>
    <label class="input-image">
        <img class="input-image__image" :src="imageSrc" v-if="imageFile" />
        <FontAwesomeIcon class="input-image__icon" icon="user" v-else />
        <input class="input-image__input" type="file" accept=".jpg, .jpeg, .png, image/png, image/jpg, image/jpeg" @change="valueChanged" />
    </label>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { convertFileToBase64String } from "@/composables/utils";

const emit = defineEmits(["change"]);

const imageFile = ref<File | undefined>(undefined);
const imageSrc = ref("");

async function valueChanged(event: Event) {
    const inputElement = event.target as HTMLInputElement;
    const file = inputElement.files?.[0];

    if (file) {
        if (!file.type.includes("image")) {
            alert("Необходимо выбрать изображение");
            return;
        }

        imageFile.value = file;

        const fileString = await convertFileToBase64String(file);

        imageSrc.value = fileString;
        emit("change", file);
    }
}
</script>

<style lang="scss">
.input-image {
    display: flex;
    justify-content: center;
    align-items: center;
    width: r(100);
    height: r(100);
    margin: r(10);
    border-radius: 50%;
    border: r(1) solid color("ui-background");
    overflow: hidden;

    &__image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border: none;
        outline: none;
    }

    &__icon {
        height: 30%;
        width: 30%;
        color: color("ui-background");
    }

    &__input {
        display: none;
    }
}
</style>
