// One Card Tarot Game JS
// Check if the chatbox is available in the DOM
const isChatEnabled = !!document.querySelector('.tah_chat-wrapper');

// Function to draw cards
function drawCards() {
    const selectedCardDetails = document.querySelector('.selected-card-details');
    const drawAgainButton = document.getElementById("drawAgainButton");
    const cards = document.querySelectorAll('.card');

    // Hide cards with a fade-out effect
    cards.forEach(card => {
        card.style.opacity = 0;
    });

    setTimeout(() => {
        cards.forEach(card => {
            card.style.display = 'none';
        });

        // Fetch card data from the server
        fetch(onecardData.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=onecard_api_call&security=${onecardData.nonce}`
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                return response.json();
            })
            .then(results => {
                // Validate the results before proceeding
                if (!results || !results.cardName || !results.cardPic) {
                    throw new Error('Invalid card data received');
                }

                // Update the card details
                document.getElementById("oneCardName").innerHTML = results.cardName;
                document.getElementById("oneCardPicture").src = onecardData.image_base + results.cardPic;

                // Update card meaning if the element exists
                const oneCardMeaning = document.getElementById("oneCardMeaning");
                if (oneCardMeaning) {
                    oneCardMeaning.innerHTML = results.cardMeaning;
                }

                // Show selected card details and "Draw Again" button
                selectedCardDetails.style.display = 'block';
                drawAgainButton.style.display = 'block';

                // Fade in the selected card details
                setTimeout(() => {
                    selectedCardDetails.style.opacity = 1;
                    drawAgainButton.style.opacity = 1;
                }, 100);
            })
            .catch(error => {
                alert('Failed to load card data. Please try again.');
            });
    }, 1000);
}

// Function to reset the game
function resetGame() {
    // Close WebSocket connection if chat is enabled and if it's open
    if (isChatEnabled && typeof socket !== 'undefined' && socket && socket.readyState === WebSocket.OPEN) {
        socket.close();
    }

    // Fetch the reset game content from the server
    fetch(onecardData.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=reset_onecard_game_and_chat&security=${onecardData.nonce}`
    })
        .then(response => response.text())
        .then(html => {
            // Update the card container with the new content
            const cardContainer = document.getElementById('card-container');
            cardContainer.innerHTML = html;

            // Scroll to the top of the card container
            const containerTopPosition = cardContainer.offsetTop;
            window.scrollTo(0, containerTopPosition - 20);

            // Reinitialize chat if enabled
            if (isChatEnabled) {
                resetChat();
                initializeChat();
            }
        })
        .catch(error => console.error('Error resetting game and chat:', error));
}