<script lang="ts" setup>
    import { ref, watch } from 'vue';
    import { Nullable, UIColorName, UIColorValues } from '@/UI-kit/types';
    import { UIColor } from '@/UI-kit/constants';
    import UILoader from '@/UI-kit/components/UI/loader/UILoader.vue';

    const props = withDefaults(
        defineProps<{
            src: string;
            alt?: string;
            loading?: 'lazy' | 'eager';
            loaderBorderColor?: Nullable<UIColorValues> | string;
            openOnClick?: boolean;
            objectFit?: 'cover' | 'contain';
        }>(),
        {
            alt: '',
            loading: 'lazy',
            loaderBorderColor: UIColor[UIColorName.Blue500],
            openOnClick: false,
            objectFit: 'cover',
        },
    );

    const emit = defineEmits<{
        load: [];
        click: [typeof props];
    }>();

    const isLoaded = ref(false);

    const onImageLoad = (): void => {
        isLoaded.value = true;
        emit('load');
    };

    const onImageClick = (): void => {
        if (!props.openOnClick || !props.src) {
            return;
        }
        emit('click', props);
    };

    watch(
        () => props.src,
        () => {
            isLoaded.value = false;
        },
        { immediate: true },
    );
</script>

<template>
    <div class="ui-image-with-loader">
        <img
            class="ui-image-with-loader__img"
            :class="{
                'ui-image-with-loader__img--blur': !isLoaded,
                'ui-image-with-loader__img--clickable': openOnClick,
            }"
            :src="src"
            :alt="alt"
            :loading="loading"
            :style="{ objectFit }"
            @load="onImageLoad"
            @click="onImageClick"
        />
        <div v-if="!isLoaded" class="ui-image-with-loader__overlay">
            <UILoader :border-color="loaderBorderColor" class="ui-image-with-loader__loader" />
        </div>
    </div>
</template>

<style lang="scss" scoped>
    .ui-image-with-loader {
        position: relative;
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    .ui-image-with-loader__img {
        display: block;
        width: 100%;
        height: 100%;
        transition: filter 0.2s ease;
    }

    .ui-image-with-loader__img--blur {
        filter: blur(4px) brightness(0.95);
    }

    .ui-image-with-loader__img--clickable {
        cursor: pointer;
    }

    .ui-image-with-loader__overlay {
        position: absolute;
        z-index: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgb(255 255 255 / 55%);
        inset: 0;
    }

    .ui-image-with-loader__loader {
        transform: scale(0.65);
    }
</style>
