const fishTypes = [
    { emoji: '🐡', command: 'bold', label: 'BOLD', points: 10 },
    { emoji: '🐠', command: 'italic', label: 'ITALIC', points: 10 },
    { emoji: '🐟', command: 'underline', label: 'UNDERLINE', points: 10 },
    { emoji: '🐙', command: 'foreColor', label: 'COLOR', points: 15, value: null },
    { emoji: '🦈', command: 'strikeThrough', label: 'STRIKE', points: 20 },
    { emoji: '🐳', command: 'fontSize', label: 'BIG', points: 15, value: '6' },
    { emoji: '🦐', command: 'fontSize', label: 'SMALL', points: 15, value: '2' },
    { emoji: '🪼', command: 'removeFormat', label: 'REMOVE', points: -15, negative: true },
    { emoji: '🦑', command: 'delete', label: 'DELETE', points: -20, negative: true },
];

const colors = ['#ff6b9d', '#ff8c42', '#fcd34d', '#2dd4bf', '#7dd3fc', '#a78bfa', '#f472b6'];
let wordPool = [];
let gameRunning = false;
let activeFish = [];
let spawnInterval = null;

// Get parent origin
const PARENT_ORIGIN = window.location.origin;

// Listen for messages from parent
window.addEventListener('message', (e) => {
    // Verify origin - only accept from parent
    if (e.source !== window.parent) return;
    
    // Verify origin matches
    if (e.origin !== PARENT_ORIGIN) {
        console.warn('Message rejected: invalid origin', e.origin);
        return;
    }
    
    const { type, data } = e.data;
    
    if (type === 'START_GAME') {
        wordPool = data.wordPool;
        startSpawning();
    } else if (type === 'END_GAME') {
        stopSpawning();
    } else if (type === 'CATCH_RESULT') {
        handleCatchResult(data);
    }
});

// Notify parent that iframe is ready
window.parent.postMessage({ type: 'IFRAME_READY' }, PARENT_ORIGIN);

function startSpawning() {
    gameRunning = true;
    activeFish.forEach(f => f.element.remove());
    activeFish = [];
    
    spawnFish();
    spawnFish();
    spawnFish();
    
    spawnInterval = setInterval(() => {
        if (activeFish.length < 5) {
            spawnFish();
        }
    }, 2000);
}

function stopSpawning() {
    gameRunning = false;
    clearInterval(spawnInterval);
    
    activeFish.forEach(f => {
        f.element.style.transition = 'all 0.5s';
        f.element.style.opacity = '0';
        setTimeout(() => f.element.remove(), 500);
    });
    activeFish = [];
}

function spawnFish() {
    if (!gameRunning || wordPool.length === 0) return;

    const fishType = fishTypes[Math.floor(Math.random() * fishTypes.length)];
    const targetWord = wordPool[Math.floor(Math.random() * wordPool.length)];
    
    const fish = document.createElement('div');
    fish.className = fishType.negative ? 'fish negative' : 'fish';
    
    const goingRight = Math.random() > 0.5;
    let value = fishType.value;
    if (fishType.command === 'foreColor') {
        value = colors[Math.floor(Math.random() * colors.length)];
    }

    fish.innerHTML = `
        <div class="fish-body" style="transform: ${goingRight ? 'scaleX(1)' : 'scaleX(-1)'}">
            <span class="fish-icon">${fishType.emoji}</span>
        </div>
        <div class="fish-word">${targetWord}</div>
        <div class="fish-command">${fishType.label}</div>
    `;

    const fishData = {
        element: fish,
        command: fishType.command,
        value: value,
        points: fishType.points,
        targetWord: targetWord,
        negative: fishType.negative || false
    };

    const swimDuration = 10000 + Math.random() * 5000;
    const startX = goingRight ? -120 : window.innerWidth + 120;
    const endX = goingRight ? window.innerWidth + 120 : -120;
    const swimY = 30 + Math.random() * (window.innerHeight - 120);
    
    fish.style.left = startX + 'px';
    fish.style.top = swimY + 'px';
    
    const startTime = Date.now();
    
    function swim() {
        if (!gameRunning) {
            fish.remove();
            activeFish = activeFish.filter(f => f !== fishData);
            return;
        }

        const elapsed = Date.now() - startTime;
        const progress = elapsed / swimDuration;
        
        if (progress >= 1 || !fish.parentElement) {
            if (fish.parentElement) {
                fish.remove();
                activeFish = activeFish.filter(f => f !== fishData);
            }
            return;
        }

        const currentX = startX + (endX - startX) * progress;
        const waveY = swimY + Math.sin(elapsed / 400) * 12;
        
        fish.style.left = currentX + 'px';
        fish.style.top = waveY + 'px';
        
        requestAnimationFrame(swim);
    }

    fish.addEventListener('click', (e) => {
        e.stopPropagation();
        if (gameRunning) {
            // Send message to parent with fish data
            window.parent.postMessage({
                type: 'FISH_CLICKED',
                data: {
                    command: fishData.command,
                    value: fishData.value,
                    points: fishData.points,
                    targetWord: fishData.targetWord,
                    negative: fishData.negative,
                    fishId: activeFish.indexOf(fishData),
                    x: e.clientX,
                    y: e.clientY
                }
            }, PARENT_ORIGIN);
        }
    });

    document.body.appendChild(fish);
    activeFish.push(fishData);
    swim();
}

function handleCatchResult(data) {
    const { fishId, success, earnedPoints, isNegative } = data;
    const fishData = activeFish[fishId];
    if (!fishData) return;

    const fish = fishData.element;
    const rect = fish.getBoundingClientRect();

    if (success) {
        // Show catch effect
        const effect = document.createElement('div');
        effect.className = 'effect';
        effect.textContent = isNegative ? `${earnedPoints} 💀` : `+${earnedPoints} ✓`;
        effect.style.color = isNegative ? '#ef4444' : colors[Math.floor(Math.random() * colors.length)];
        effect.style.left = (rect.left + 20) + 'px';
        effect.style.top = rect.top + 'px';
        document.body.appendChild(effect);
        setTimeout(() => effect.remove(), 800);

        // Remove fish
        fish.style.transition = 'all 0.2s';
        fish.style.transform = 'scale(0) rotate(360deg)';
        fish.style.opacity = '0';
        
        setTimeout(() => {
            fish.remove();
            activeFish = activeFish.filter(f => f !== fishData);
        }, 200);
    } else {
        // Miss effect
        const effect = document.createElement('div');
        effect.className = 'effect';
        effect.textContent = `${earnedPoints} ❌`;
        effect.style.color = '#ef4444';
        effect.style.left = (rect.left + 20) + 'px';
        effect.style.top = rect.top + 'px';
        document.body.appendChild(effect);
        setTimeout(() => effect.remove(), 600);

        // Shake fish
        fish.style.animation = 'shake 0.3s ease-in-out';
        setTimeout(() => { fish.style.animation = ''; }, 300);
    }
}
