<script setup lang="ts">
import { ref } from 'vue';
import { Save } from 'lucide-vue-next';
import Button from '../ui/button/Button.vue';
import Input from '../ui/input/Input.vue';
import { httpApi } from '@/lib/utils';
import { useResumesStore } from '@/stores/resume';

const resumeStore = useResumesStore();
const resume = resumeStore.currentResume;

const resumeTitle = resumeStore.currentResumeName;
const originalTitle = ref<string>(resumeTitle.value);
const titleChanged = ref<boolean>(false);

function saveTitle() {
    const resumeCopy = { ...resume.value, name: resumeTitle.value };
    resumeCopy['components_placements'] = null;

    httpApi(route('resumes.update', resume.value), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
            'Accept': 'application/json'
        },
        body: JSON.stringify({ ...resumeCopy, _method: 'PUT' })
    }).then(() => {
        originalTitle.value = resumeTitle.value;
        titleChanged.value = false;
    });
}
</script>

<template>
    <div class="flex gap-1" >
        <Input type="text" v-model="resumeTitle" placeholder="Sans titre" class="border p-2 rounded" @input="(event) => {resumeStore.setCurrentResumeName(event.target.value); titleChanged = (event.target.value !== originalTitle)}" />
        <Transition>
            <Button v-if="titleChanged" variant="outline" class="cursor-pointer transition" @click="saveTitle"><Save /></Button>
        </Transition>
    </div>
</template>

<style lang="css" scoped>
    .v-enter-active,
    .v-leave-active {
    transition: opacity 0.3s ease;
    }

    .v-enter-from,
    .v-leave-to {
    opacity: 0;
    }
</style>
