<script setup lang="ts">
import ShuffleCardPresentation from '@/components/organism/ShuffleCard/ShuffleCardPresentation.vue';
import LandingLayout from '@/layouts/app/LandingLayout.vue';
import { useTarotStore } from '@/stores/tarot';
import axios from 'axios';
import { onMounted, ref, watchEffect } from 'vue'; // Import watchEffect
import cardSelection from './cardSelection.vue';

const cardComponent = ref();
const tarotStore = useTarotStore();
const isSelectionScreen = ref(true);
const loading = ref(false);
const error = ref<string | null>(null);

const drawCount = ref(0);
const cards = ref([]);

const params = new URLSearchParams(window.location.search);
const clientSessionId = params.get('client_session_id');

// Use watchEffect to handle state changes from Pinia
watchEffect(() => {
    // Check if there are paid draws available and no free draws, and transition automatically
    if (tarotStore.paidDrawsRemaining > 0 && tarotStore.freeDrawsRemaining === 0) {
        isSelectionScreen.value = false;
        drawCount.value = tarotStore.paidDrawsRemaining; // Set the drawCount to the available paid draws
    }
});

onMounted(async () => {
    if (clientSessionId) {
        try {
            const response = await axios.get(`/api/get-cards?client_session_id=${clientSessionId}`);
            if (response.data.success) {
                cards.value = response.data.cards;
                if (cardComponent.value) {
                    cardComponent.value.setDrawnCards(cards.value);
                }
            } else {
                error.value = response.data.message || 'An error occurred while validating payment.';
            }
        } catch (err) {
            console.error(err);
            error.value = 'Failed to get cards from the server. Please contact support.';
        } finally {
            loading.value = false;
        }
    }
});

const handleSelection = async (count: number) => {
    drawCount.value = count;
    loading.value = true;
    error.value = null;

    // Check if it's a free draw and there's one available
    if (count === 1) {
        if (tarotStore.freeDrawsRemaining > 0) {
            try {
                // Make the API call for the free draw
                const response = await axios.get('/api/get-cards', {
                    params: { count: 1 },
                });
                if (response.data.success) {
                    cards.value = response.data.cards;
                    // Only use the free draw after a successful API call
                    tarotStore.useFreeDraw();
                    isSelectionScreen.value = false;
                } else {
                    error.value = response.data.message || 'An error occurred while getting cards.';
                }
            } catch (err) {
                console.error(err);
                error.value = 'Failed to get cards from the server. Please contact support.';
            } finally {
                loading.value = false;
            }
        } else {
            alert("You don't have any free draws left. Please choose a paid option.");
            loading.value = false;
        }
    } else {
        // This is the paid draw logic, which remains mostly the same
        if (tarotStore.paidDrawsRemaining >= count) {
            // Here, you would also make an API call to get the paid cards
            try {
                const response = await axios.get('/api/get-cards', {
                    params: { count: count },
                });
                if (response.data.success) {
                    cards.value = response.data.cards;
                    tarotStore.usePaidDraw(count);
                    isSelectionScreen.value = false;
                } else {
                    error.value = response.data.message || 'An error occurred while getting cards.';
                }
            } catch (err) {
                console.error(err);
                error.value = 'Failed to get cards from the server. Please contact support.';
            } finally {
                loading.value = false;
            }
        } else {
            alert("You don't have enough paid draws. Please proceed with payment.");
            loading.value = false;
        }
    }
};
</script>

<template>
    <LandingLayout>
        <card-selection @selectDraw="handleSelection" v-if="isSelectionScreen && !clientSessionId" />
        <ShuffleCardPresentation v-else ref="cardComponent" :drawn-cards="cards" :client-session-id="clientSessionId" />
    </LandingLayout>
</template>
