<script setup lang="ts">
import { ref } from "vue";

const isLoading = ref(false);
const error = ref<string | null>(null);

const handleDownload = async () => {
    isLoading.value = true;
    error.value = null;

    try {
        const response = await fetch(`/api/resume/generate?t=${Date.now()}`);

        if (!response.ok) {
            throw new Error(
                `Failed to generate PDF: ${response.status} ${response.statusText}`,
            );
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);

        const link = document.createElement("a");
        link.href = url;
        link.download = "Atridad_Lahiji_Resume.pdf";
        document.body.appendChild(link);
        link.click();

        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (err) {
        console.error("Error downloading PDF:", err);
        error.value =
            err instanceof Error ? err.message : "Failed to download PDF";
    } finally {
        isLoading.value = false;
    }
};
</script>

<template>
    <div class="text-center mb-6 sm:mb-8">
        <button
            @click="handleDownload"
            :disabled="isLoading"
            class="btn btn-primary font-bold rounded-full inline-flex items-center gap-2 text-sm sm:text-base"
            :class="{
                'text-primary border-2 border-primary': isLoading,
            }"
        >
            <template v-if="isLoading">
                <span class="loading loading-spinner"></span>
                Generating PDF...
            </template>
            <template v-else> Download Resume </template>
        </button>
        <div v-if="error" class="mt-2 text-error text-sm">{{ error }}</div>
    </div>
</template>
