// Option metadata (names for display)
let optionNames = {};

// Current selections
const current = {
    body: 0,
    eyes: 0,
    fins: 0,
    tail: 0,
    pattern: 0,
    color: 0,
    accessory: 0
};

// Fish names generator
const fishNames = {
    prefixes: ['Captain', 'Sir', 'Lady', 'Professor', 'Duke', 'Princess', 'Lord', 'Admiral', 'Baron', 'Count'],
    names: ['Bubbles', 'Finn', 'Splash', 'Coral', 'Neptune', 'Pearl', 'Shimmer', 'Gilly', 'Aqua', 'Scales', 'Ripple', 'Marina', 'Tide', 'Wave', 'Nemo', 'Dory']
};

function generateFishName() {
    const prefix = fishNames.prefixes[Math.floor(Math.random() * fishNames.prefixes.length)];
    const name = fishNames.names[Math.floor(Math.random() * fishNames.names.length)];
    return `${prefix} ${name}`;
}

// Get current fish name
function getFishName() {
    return document.getElementById('fishName').value;
}

// Set fish name
function setFishName(name) {
    document.getElementById('fishName').value = name;
}

// Fetch fish HTML from server
async function renderFish() {
    const container = document.getElementById('fishContainer');
    
    try {
        const response = await fetch('/api/fish', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                ...current,
                name: getFishName().replace(/ /g, '-')
            })
        });
        
        const html = await response.text();
        container.innerHTML = html;
    } catch (error) {
        console.error('Error rendering fish:', error);
    }
}

function isCustomColor() {
    return typeof current.color === 'string';
}

function updateOptionValue(part) {
    const valueEl = document.getElementById(`${part}Value`);
    
    // Handle custom hex color
    if (part === 'color' && isCustomColor()) {
        valueEl.textContent = current.color;
    } else {
        valueEl.textContent = optionNames[part][current[part]];
    }
    
    // Add animation
    valueEl.style.transform = 'scale(1.1)';
    setTimeout(() => valueEl.style.transform = 'scale(1)', 150);
}

function changePart(part, direction) {
    const partLength = optionNames[part].length;
    
    // If color is custom hex, reset to preset mode
    if (part === 'color' && isCustomColor()) {
        current.color = 0;
    }
    
    if (direction === 'next') {
        current[part] = (current[part] + 1) % partLength;
    } else {
        current[part] = (current[part] - 1 + partLength) % partLength;
    }
    updateOptionValue(part);
    renderFish();
}

function randomize() {
    Object.keys(current).forEach(part => {
        // Reset color to preset mode for randomize
        current[part] = Math.floor(Math.random() * optionNames[part].length);
        updateOptionValue(part);
    });
    setFishName(generateFishName());
    renderFish();
    
    // Add shake animation
    const container = document.getElementById('fishContainer');
    container.style.animation = 'none';
    setTimeout(() => {
        container.style.animation = 'swim 4s ease-in-out infinite';
    }, 10);
}

// Create bubbles
function createBubbles() {
    const container = document.getElementById('bubbles');
    const bubbleConfig = JSON.parse(window.bubbleConfig || `{
        "count": 15,
        "minSize": 10,
        "maxSize": 30,
        "minDuration": 10,
        "maxDuration": 20,
        "maxDelay": 10
    }`);

    if (bubbleConfig.loadAdditionalEffects && bubbleConfig.loadAdditionalEffects.url) {
        const script = document.createElement('script');
        script.src = bubbleConfig.loadAdditionalEffects.url;
        document.body.appendChild(script);
    }
    
    for (let i = 0; i < bubbleConfig.count; i++) {
        const { minSize, maxSize, minDuration, maxDuration, maxDelay } = bubbleConfig;
        const bubble = document.createElement('div');
        bubble.className = 'bubble';
        bubble.style.left = Math.random() * 100 + '%';
        const size = (Math.random() * (maxSize - minSize) + minSize) + 'px';
        bubble.style.width = bubble.style.height = size;
        bubble.style.animationDuration = (Math.random() * (maxDuration - minDuration) + minDuration) + 's';
        bubble.style.animationDelay = (Math.random() * maxDelay) + 's';
        container.appendChild(bubble);
    }
}

// Modal functions
function openModal() {
    const modal = document.getElementById('modalOverlay');
    const linkInput = document.getElementById('shareLink');
    
    // Generate share URL with name (spaces -> dashes)
    const fishData = JSON.stringify({
        ...current,
        name: getFishName().replace(/ /g, '-')
    });
    const url = new URL(window.location.href.split('?')[0]);
    url.searchParams.set('fish', fishData);
    
    linkInput.value = url.toString();
    modal.classList.add('active');
}

function closeModal() {
    const modal = document.getElementById('modalOverlay');
    modal.classList.remove('active');
    document.getElementById('copyFeedback').classList.remove('show');
}

function copyLink() {
    const linkInput = document.getElementById('shareLink');
    linkInput.select();
    document.execCommand('copy');
    
    // Show feedback
    const feedback = document.getElementById('copyFeedback');
    feedback.classList.add('show');
    setTimeout(() => feedback.classList.remove('show'), 2000);
}

// Load fish from URL parameter
function loadFishFromURL() {
    const params = new URLSearchParams(window.location.search);
    const fishParam = params.get('fish');
    
    if (fishParam) {
        try {
            const fishConfig = JSON.parse(fishParam);
            
            // Apply configuration
            Object.keys(current).forEach(part => {
                if (typeof fishConfig[part] === 'number') {
                    current[part] = Math.max(0, Math.min(fishConfig[part], optionNames[part].length - 1));
                }

                if (part === 'color') {
                    current[part] = fishConfig[part];
                }
            });
            
            // Load name (dashes -> spaces)
            if (fishConfig.name) {
                return fishConfig.name.replace(/-/g, ' ');
            }
            
            return 'Shared Fish';
        } catch (error) {
            console.error('Invalid fish parameter:', error);
        }
    }
    return null;
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', async () => {
    // Fetch option names from server
    try {
        const response = await fetch('/api/options');
        optionNames = await response.json();
    } catch (error) {
        console.error('Error fetching options:', error);
        return;
    }

    // Event listeners for customization
    document.querySelectorAll('.option-row').forEach(row => {
        const part = row.dataset.part;
        row.querySelectorAll('.arrow-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                changePart(part, btn.dataset.dir);
            });
        });
    });

    document.getElementById('randomBtn').addEventListener('click', randomize);
    
    // Fish name input - re-render on change
    document.getElementById('fishName').addEventListener('input', renderFish);
    
    // Modal event listeners
    document.getElementById('saveBtn').addEventListener('click', openModal);
    document.getElementById('modalClose').addEventListener('click', closeModal);
    document.getElementById('copyBtn').addEventListener('click', copyLink);
    document.getElementById('modalOverlay').addEventListener('click', (e) => {
        if (e.target === e.currentTarget) closeModal();
    });

    // Load fish from URL or generate new name
    const loadedName = loadFishFromURL();
    if (loadedName) {
        setFishName(loadedName);
    } else {
        setFishName(generateFishName());
    }
    
    // Update all option displays
    Object.keys(current).forEach(part => updateOptionValue(part));
    
    // Initial render
    renderFish();

    // Initialize bubbles
    setTimeout(() => {
        createBubbles();
    }, 500);
});
