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

function initializeGame() {
    if (isChatEnabled && typeof initializeChat === 'function') {
        initializeChat();
    }

    const cards = document.querySelectorAll('.card');
    const drawAgainButton = document.getElementById('drawAgainButton');

    cards.forEach(card => {
        card.addEventListener('click', handleCardClick);
    });

    if (drawAgainButton) {
        drawAgainButton.addEventListener('click', resetGame);
    }
}

function handleCardClick(event) {
    const card = event.currentTarget;
    selectCard(card);
}

function selectCard(card) {
    if (card.classList.contains('selected') || card.classList.contains('unselectable')) return;

    cardCounter++;
    card.classList.add('selected');

    if (cardCounter < 3) {
        card.classList.add('unselectable', 'raised');
    }

    if (cardCounter === 3) {
        processCardSelection();
    }
}

function processCardSelection() {
    const cards = document.querySelectorAll('.card');

    cards.forEach(c => {
        c.style.opacity = '0';
        c.style.pointerEvents = 'none';
    });

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

        fetch(threecardData.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=threecard_api_call&security=${threecardData.nonce}`
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                return response.json();
            })
            .then(results => {
                if (!Array.isArray(results) || results.length !== 3 || !results.every(r => r.cardName && r.cardPic)) {
                    throw new Error('Invalid API response format');
                }

                results.forEach((result, index) => {
                    const cardNumber = index + 1;
                    const nameElement = document.getElementById(`selected-card-name${cardNumber}`);
                    const imageElement = document.getElementById(`selected-card${cardNumber}`);
                    const meaningElement = document.getElementById(`selected-card-meaning${cardNumber}`);

                    if (nameElement) nameElement.textContent = result.cardName;
                    if (imageElement) imageElement.src = `${threecardData.image_base}${result.cardPic}`;

                    if (meaningElement && result.cardMeaning) {
                        meaningElement.innerHTML = result.cardMeaning;
                    }
                });

                const detailsSection = document.querySelector('.selected-card-details');
                const drawButton = document.getElementById('drawAgainButton');

                if (detailsSection) {
                    detailsSection.style.display = 'block';
                    setTimeout(() => detailsSection.style.opacity = '1', 50);
                }

                if (drawButton) {
                    drawButton.style.display = 'block';
                    setTimeout(() => drawButton.style.opacity = '1', 50);
                }
            })
            .catch(error => {
                alert('Failed to load card data. Please try again.');
            });
    }, 1000);
}

function resetGame() {
    if (isChatEnabled && typeof socket !== 'undefined' && socket?.readyState === WebSocket.OPEN) {
        socket.close();
    }

    fetch(threecardData.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=tarotxhoroscope_reset_threecard_game_and_chat&security=${threecardData.nonce}`
    })
        .then(response => {
            if (!response.ok) throw new Error('Reset failed');
            return response.text();
        })
        .then(html => {
            const container = document.getElementById('threecard-game');
            const containerTopPosition = container.offsetTop;
            window.scrollTo(0, containerTopPosition - 20);
            if (container) {
                container.innerHTML = html;
                cardCounter = 0;
                initializeGame();

                if (isChatEnabled && typeof resetChat === 'function') {
                    resetChat();
                }
            }
        })
        .catch(error => {
            console.error('Reset error:', error);
            alert('Error resetting game. Please refresh the page.');
        });
}

initializeGame();