<script setup>
import { useWindowSize } from '@vueuse/core'
import { watch } from 'vue';
import { Carousel, Navigation, Slide } from 'vue3-carousel'
import 'vue3-carousel/dist/carousel.css'
import logo from "@images/logo.png"
const userData = useCookie('userData').value
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const vagas = ref([])
const { width: windowWidth } = useWindowSize();

const isMobile = ref(false)
isMobile.value = windowWidth.value < 768

watch(windowWidth, () => {
    isMobile.value = windowWidth.value < 768
})

// Ícones
const icon = "tabler-briefcase";
const icon2 = "tabler-map-pin";
const icon3 = "tabler-device-laptop";
const icon4 = "tabler-eye";
const icon5 = "tabler-search";

onMounted(() => {
    buscarTodos()
})

const buscarTodos = async () => {
    try {

        loading.value = true;

        let body = {};

        body.prazo = true;
        body.itensPerPage = 12;

        let data = null;
        if (userData && userData.id !== undefined && userData.id !== null) {
            data = userData
            body.userData = JSON.stringify(data)
        } else if (useCookie('permEndereco').value && useCookie('permEndereco').value.geolocation !== undefined && useCookie('permEndereco').value.geolocation !== null) {
            let perm = useCookie('permEndereco').value
            data = {
                endereco: { geolocation: perm.geolocation }
            }
            body.userData = JSON.stringify(data)
        }

        const response = await $api("/vagas/getApprovedUsers", {
            method: "POST",
            body: body,
        });

        if (!response) {
            loading.value = false;
            return;
        }

        console.log('Resposne API', response);

        vagas.value = response.vagas
            .filter(vaga => vaga && vaga.createdAt) // Filtrar itens inválidos
            .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
        loading.value = false;

    } catch (error) {
        console.error("Erro ao obter dados da API:", error, error.response);
    }
};

const detalhesVaga = (id) => {
    router.push({ name: "DetalhesVaga", params: { slug: id } });
};

const formatDate = (date) => {
    return new Date(date).toLocaleDateString("pt-BR");
};

const currentSlideModel = ref(0);

const nextSlide = () => {
    currentSlideModel.value += isMobile ? 1 : 2;
    if (currentSlideModel.value >= vagas.value.length) {
        currentSlideModel.value = 0;
    }
};

const prevSlide = () => {
    currentSlideModel.value -= isMobile ? 1 : 2;
    if (currentSlideModel.value < 0) {
        currentSlideModel.value = vagas.value.length - 1;
    }
};

const truncateTitle = (title) => {
    if (title.length > 45) {
        return title.substring(0, 45) + "...";
    }
    return title;
};
//as
</script>
<template>


    <div v-if="vagas.length > 0 || loading" class="position-relative">

        <Carousel :items-to-show="isMobile ? 1 : 4" ref="carousel" v-model="currentSlideModel" :autoplay="4000"
            :style="!isMobile ? 'margin-left: 45px; margin-right: 45px;' : ''">
            <template #slides="{ slideWidth, currentSlide }">
                <Slide v-for="(vaga, index) in vagas" :key="vaga.id">
                    <div class="pa-3 w-100 h-100" style="min-height: 190px;">
                        <VCard class="pa-0" :elevation="index === currentSlide ? 4 : 2"
                            @click="detalhesVaga(vaga.slug)">
                            <VCardText
                                class="pa-4 cursor-pointer position-relative flex-column text-left d-flex justify-start">
                                <VChip color="primary" class="mb-2 position-absolute" label
                                    style="font-size: 12px; width: fit-content !important; bottom: 10px; right: 10px;"
                                    v-if="vaga.distance">
                                    {{ vaga.distance.replace(' ', '') }} de você
                                </VChip>

                                <div class="d-flex flex-row align-center gap-2 mb-3">
                                    <img :src="vaga.logo" alt="Logo da Empresa" width="30px" height="30px"
                                        v-if="vaga.logo && vaga.logo !== 'none'" style="border-radius: 5px;" />
                                    <img :src="logo" alt="Logo da Empresa" width="30px" height="30px"
                                        style="border-radius: 5px;" v-if="!vaga.logo || vaga.logo == 'none'" />
                                    <div>
                                        <h4 class="font-weight-bold mb-0 d-flex align-center" style="min-height: 45px;">
                                            {{ truncateTitle(vaga.funcao) }}
                                        </h4>
                                        <p class="mb-0 text-caption">
                                            {{ vaga.empresa }}
                                        </p>
                                    </div>
                                </div>
                                <div class="d-flex flex-column gap-2 mb-2">
                                    <p class="mb-0 font-weight-bold" style="font-size: 13px;">
                                        <VIcon :icon="icon2" class="mr-1" />
                                        {{ vaga.addressVaga?.city + '/' + vaga.addressVaga?.state }}
                                    </p>
                                    <p class="mb-0" style="font-size: 13px;">
                                        <VIcon :icon="icon3" class="mr-1" />
                                        {{ vaga.formaContrato }}
                                    </p>
                                    <p class="mb-0" style="font-size: 13px;">
                                        <VIcon :icon="icon" class="mr-1" />
                                        {{ vaga.tipoVaga }}
                                    </p>
                                </div>
                            </VCardText>
                        </VCard>
                    </div>
                </Slide>
            </template>
        </Carousel>

        <div class="d-flex justify-space-between align-center flex-row w-100 position-absolute" style="top: 45%;"
            v-if="!isMobile">
            <v-btn variant="elevated" icon @click="prevSlide" color="primary" size="small">
                <v-icon icon="tabler-caret-left-filled" color="white" size="25" />
            </v-btn>

            <v-btn variant="elevated" icon @click="nextSlide" color="primary" size="small">
                <v-icon icon="tabler-caret-right-filled" color="white" size="25" />
            </v-btn>
        </div>

    </div>

    <h3 class="text-center font-weight-bold" v-if="vagas.length === 0 && !loading">
        <VIcon icon="tabler-mood-sad" size="22" color="primary" />
        Nenhuma vaga disponível no momento.
    </h3>
</template>