<script setup lang="ts">
import { useTarotStore } from '@/stores/tarot';
import { loadStripe } from '@stripe/stripe-js';
import axios from 'axios';
import { computed, ref } from 'vue';

const tarotStore = useTarotStore();
const isSelectionScreen = ref(true);
const loading = ref(false);

const drawCount = ref(0);

// Emits the draw selection back to parent
const emit = defineEmits<{
    (e: 'selectDraw', count: number): void;
}>();

const handleSelection = async (count: number) => {
    drawCount.value = count;

    if (count == 1 && tarotStore.freeDrawsRemaining <= 0) {
        alert('You have used your free draw. Please choose a paid option to unlock more.');
        return;
    }
    if (count > 1 && tarotStore.paidDrawsRemaining < count) {
        await redirectToStripeCheckout(count);
        return;
    }
    emit('selectDraw', count);
};

const redirectToStripeCheckout = async (count: number) => {
    loading.value = true;
    try {
        // 1. Send request to your Laravel backend to create a Stripe Checkout Session
        const res = await axios.post('/create-checkout-session', { count });
        const { sessionId } = res.data;

        // 2. Load Stripe.js with your publishable key
        const stripe = await loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY!);

        // 3. Redirect to Stripe Checkout using the session ID from the backend
        if (stripe) {
            const { error } = await stripe.redirectToCheckout({ sessionId });

            if (error) {
                console.error('Stripe redirect error:', error.message);
                alert('Payment failed. Please try again.');
            }
        }
    } catch (error) {
        console.error('Error initiating Stripe checkout:', error);
        alert('Payment processing failed. Please try again.');
    } finally {
        loading.value = false;
    }
};

// Computed to disable the free draw button if used
const isFreeDrawUsed = computed(() => tarotStore.freeDrawsRemaining <= 0);
</script>

<template>
    <section class="py-20 sm:py-24">
        <h2 class="mb-16 text-center text-4xl font-bold text-[var(--midnight-blue)] md:text-5xl">Explorez Nos Lectures</h2>

        <p v-if="isFreeDrawUsed" class="mb-8 text-center text-lg font-semibold text-[var(--spiritual-earth)]">
            Vous avez utilisé votre tirage gratuit ! Choisissez une option payante pour continuer.
        </p>

        <div class="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
            <!-- Free draw -->
            <div
                class="flex flex-col gap-6 rounded-2xl border border-[var(--linen)] bg-[var(--pure-white)] p-8 shadow-lg transition-all duration-300 hover:-translate-y-2 hover:shadow-2xl"
            >
                <div class="text-center">
                    <h3 class="text-2xl font-bold text-[var(--midnight-blue)]">Lecture Gratuite</h3>
                    <p class="mt-2 text-5xl font-bold text-[var(--subtle-gold)]">Gratuit</p>
                </div>
                <button
                    :disabled="isFreeDrawUsed"
                    class="mt-4 flex h-12 w-full items-center justify-center rounded-full bg-[var(--linen)] px-8 font-bold tracking-wide text-[var(--midnight-blue)] transition-all duration-300 hover:bg-[var(--spiritual-earth)] hover:text-[var(--pure-white)] disabled:cursor-not-allowed disabled:opacity-50"
                    @click="handleSelection(1)"
                >
                    Commencer
                </button>
            </div>

            <!-- Paid options -->
            <div
                class="flex scale-105 flex-col gap-6 rounded-2xl bg-[var(--midnight-blue)] p-8 shadow-lg ring-2 ring-[var(--subtle-gold)] transition-all duration-300 hover:-translate-y-2 hover:shadow-2xl"
            >
                <div class="text-center">
                    <h3 class="text-2xl font-bold text-[var(--pure-white)]">Profilage</h3>
                    <p class="mt-2 text-5xl font-bold text-[var(--subtle-gold)]">29€</p>
                </div>
                <button
                    class="mt-4 flex h-12 w-full items-center justify-center rounded-full bg-[var(--subtle-gold)] px-8 font-bold tracking-wide text-[var(--midnight-blue)] transition-all duration-300 hover:bg-[var(--pure-white)]"
                    @click="handleSelection(3)"
                >
                    Découvrir
                </button>
            </div>

            <div
                class="flex flex-col gap-6 rounded-2xl border border-[var(--linen)] bg-[var(--pure-white)] p-8 shadow-lg transition-all duration-300 hover:-translate-y-2 hover:shadow-2xl"
            >
                <div class="text-center">
                    <h3 class="text-2xl font-bold text-[var(--midnight-blue)]">Quadrige Doré</h3>
                    <p class="mt-2 text-5xl font-bold text-[var(--subtle-gold)]">99€</p>
                </div>
                <button
                    class="mt-4 flex h-12 w-full items-center justify-center rounded-full bg-[var(--linen)] px-8 font-bold tracking-wide text-[var(--midnight-blue)] transition-all duration-300 hover:bg-[var(--spiritual-earth)] hover:text-[var(--pure-white)]"
                    @click="handleSelection(4)"
                >
                    Explorer
                </button>
            </div>
        </div>
    </section>
</template>
