// Original document text
const originalText = `Shrimp are small ocean creatures that swim close to the sea floor. They have long antennae, tiny legs, and curved bodies that help them move quickly through the water.

You can find shrimp hiding in rocks, coral, and seaweed. They spend most of their time searching for food and cleaning the ocean bottom. Even though they are small, shrimp are very important to the underwater world.

Some shrimp live alone, while others travel in groups. They flick their tails to escape danger and use their eyes to spot movement around them.

Catch your rhythm, type fast, and swim with the shrimp!`;

// Extract words from text for the word pool
const wordPool = [...new Set(
    originalText
        .replace(/[^\w\s]/g, '')
        .split(/\s+/)
        .filter(w => w.length >= 3)
)];

const colors = ['#ff6b9d', '#ff8c42', '#fcd34d', '#2dd4bf', '#7dd3fc', '#a78bfa', '#f472b6'];

// Game state
let gameRunning = false;
let timeLeft = 60;
let timerInterval = null;
let fishCount = 0;
let score = 0;
let combo = 0;
let bestCombo = 0;
let misses = 0;
let comboTimeout = null;
let currentSelectedWord = '';
let iframeReady = false;

const aquariumFrame = document.getElementById('aquariumFrame');
const editor = document.getElementById('editor');
const wordInput = document.getElementById('wordInput');
const selectionStatus = document.getElementById('selectionStatus');

// Initialize editor
editor.contentEditable = 'true';
editor.innerHTML = originalText.replace(/\n/g, '<br>');

// Prevent direct editing
editor.addEventListener('keydown', (e) => {
    if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(e.key)) {
        e.preventDefault();
    }
});

editor.addEventListener('paste', (e) => e.preventDefault());
editor.addEventListener('cut', (e) => e.preventDefault());
editor.addEventListener('drop', (e) => e.preventDefault());

// Listen for messages from iframe
window.addEventListener('message', (e) => {
    if (e.source !== aquariumFrame.contentWindow) {
        console.warn('Message rejected: not from iframe');
        return;
    }

    console.log('[message]> Valid message received, processing...');
    const { type, data } = e.data;
    
    if (type === 'IFRAME_READY') {
        iframeReady = true;
        console.log('Iframe is ready');
    } else if (type === 'FISH_CLICKED') {
        handleFishClick(data);
    }
});

function handleFishClick(data) {
    const { command, value, points, targetWord, fishId } = data;
    console.log("[handleFishClick]>", JSON.stringify(data));

    // TODO: Safely implement insertHtml command
    if (command.toLowerCase() === 'inserthtml') {
        return;
    }

    if (currentSelectedWord.toLowerCase() === targetWord.toLowerCase()) {
        selectTextInEditor(currentSelectedWord);

        try {
            document.execCommand(command, false, value);
        } catch (e) {
            console.log('ExecCommand error:', command, e);
        }

        wordInput.value = '';
        currentSelectedWord = '';
        selectionStatus.textContent = 'No selection';
        selectionStatus.className = 'selected-word-display';

        const isNegative = points < 0;
        fishCount++;
        
        let earnedPoints;
        if (isNegative) {
            earnedPoints = points;
            combo = 0;
            document.getElementById('combo').classList.remove('show');
        } else {
            combo++;
            const comboMultiplier = Math.min(combo, 5);
            earnedPoints = points * comboMultiplier;
            
            if (combo > bestCombo) {
                bestCombo = combo;
                document.getElementById('bestCombo').textContent = bestCombo;
            }

            if (combo > 1) {
                const comboEl = document.getElementById('combo');
                comboEl.textContent = `COMBO x${combo}! +${earnedPoints}`;
                comboEl.classList.add('show');
            }

            clearTimeout(comboTimeout);
            comboTimeout = setTimeout(() => {
                combo = 0;
                document.getElementById('combo').classList.remove('show');
            }, 3000);
        }
        
        score += earnedPoints;
        document.getElementById('fishCount').textContent = fishCount;
        document.getElementById('score').textContent = score;

        aquariumFrame.contentWindow.postMessage({
            type: 'CATCH_RESULT',
            data: { fishId, success: true, earnedPoints, isNegative }
        }, "*");

        wordInput.focus();
    } else {
        misses++;
        combo = 0;
        document.getElementById('combo').classList.remove('show');
        
        const penalty = -5;
        score += penalty;
        document.getElementById('score').textContent = score;

        aquariumFrame.contentWindow.postMessage({
            type: 'CATCH_RESULT',
            data: { fishId, success: false, earnedPoints: penalty, isNegative: false }
        }, "*");
    }
}

function createBubbles() {
    const bubblesContainer = document.getElementById('bubbles');
    for (let i = 0; i < 20; i++) {
        const bubble = document.createElement('div');
        bubble.className = 'bubble';
        bubble.style.left = Math.random() * 100 + '%';
        bubble.style.width = bubble.style.height = (Math.random() * 20 + 5) + 'px';
        bubble.style.animationDuration = (Math.random() * 5 + 5) + 's';
        bubble.style.animationDelay = (Math.random() * 10) + 's';
        bubblesContainer.appendChild(bubble);
    }
}

function selectWordInEditor(word) {
    if (!word) {
        clearHighlight();
        currentSelectedWord = '';
        selectionStatus.textContent = 'No selection';
        selectionStatus.className = 'selected-word-display';
        return;
    }

    const text = editor.innerText || editor.textContent;
    const regex = new RegExp(`\\b${escapeRegex(word)}\\b`, 'gi');
    const match = regex.exec(text);

    if (match) {
        currentSelectedWord = match[0];
        highlightWord(word);
        selectionStatus.textContent = `"${currentSelectedWord}"`;
        selectionStatus.className = 'selected-word-display matched';
        selectTextInEditor(match[0]);
    } else {
        currentSelectedWord = '';
        clearHighlight();
        selectionStatus.textContent = 'Not found';
        selectionStatus.className = 'selected-word-display no-match';
    }
}

function escapeRegex(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function highlightWord(word) {
    const currentHTML = editor.innerHTML;
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = currentHTML;
    tempDiv.querySelectorAll('.highlight').forEach(el => {
        el.outerHTML = el.innerHTML;
    });
    const regex = new RegExp(`(\\b${escapeRegex(word)}\\b)`, 'gi');
    tempDiv.innerHTML = tempDiv.innerHTML.replace(regex, '<span class="highlight">$1</span>');
    editor.innerHTML = tempDiv.innerHTML;
}

function clearHighlight() {
    const highlights = editor.querySelectorAll('.highlight');
    highlights.forEach(el => { el.outerHTML = el.innerHTML; });
}

function selectTextInEditor(word) {
    const highlight = editor.querySelector('.highlight');
    if (highlight) {
        const range = document.createRange();
        range.selectNodeContents(highlight);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

wordInput.addEventListener('input', (e) => {
    const word = e.target.value.trim();
    selectWordInEditor(word);
});

function startGame() {
    if (!iframeReady) {
        console.log('Waiting for iframe to be ready...');
        setTimeout(startGame, 100);
        return;
    }

    gameRunning = true;
    timeLeft = 60;
    fishCount = 0;
    score = 0;
    combo = 0;
    bestCombo = 0;
    misses = 0;
    currentSelectedWord = '';

    document.getElementById('timer').textContent = timeLeft;
    document.getElementById('fishCount').textContent = 0;
    document.getElementById('score').textContent = 0;
    document.getElementById('bestCombo').textContent = 0;
    document.getElementById('timerBox').classList.remove('warning');
    document.getElementById('gameOver').classList.remove('show');
    document.getElementById('startBtn').textContent = '🎮 Playing...';
    document.getElementById('startBtn').disabled = true;

    wordInput.value = '';
    selectionStatus.textContent = 'No selection';
    selectionStatus.className = 'selected-word-display';

    wordInput.focus();

    aquariumFrame.contentWindow.postMessage({
        type: 'START_GAME',
        data: { wordPool }
    }, "*");

    timerInterval = setInterval(() => {
        timeLeft--;
        document.getElementById('timer').textContent = timeLeft;

        if (timeLeft <= 10) {
            document.getElementById('timerBox').classList.add('warning');
        }

        if (timeLeft <= 0) {
            endGame();
        }
    }, 1000);
}

function endGame() {
    gameRunning = false;
    clearInterval(timerInterval);

    aquariumFrame.contentWindow.postMessage({ type: 'END_GAME' }, "*");

    document.getElementById('finalScore').textContent = score;
    document.getElementById('finalFish').textContent = fishCount;
    document.getElementById('finalCombo').textContent = bestCombo;
    document.getElementById('finalMisses').textContent = misses;
    document.getElementById('gameOver').classList.add('show');

    document.getElementById('startBtn').textContent = '▶️ Start Game';
    document.getElementById('startBtn').disabled = false;
}

function restartGame() {
    document.getElementById('gameOver').classList.remove('show');
    startGame();
}

createBubbles();
wordInput.value = 'shrimp';
selectWordInEditor('shrimp');
setTimeout(() => wordInput.focus(), 100);
