
// Обработка различных типов контента
function handleContent(content) {
    const display = document.getElementById('content-display');
    
    switch(content.type) {
        case 'color':
            handleColorContent(content, display);
            break;
            
        case 'text':
            handleTextContent(content, display);
            break;
            
        case 'sound':
            handleSoundContent(content, display);
            break;
            
        case 'words':
            handleWordsContent(content, display);
            break;
            
        case 'story':
            handleStoryContent(content, display);
            break;
            
        case 'ticker':
            handleTickerContent(content, display);
            break;
            
        case 'device_number':
            handleDeviceNumberContent(content, display);
            break;
            
        default:
            debugLog('Неизвестный тип контента: ' + content.type);
            showError('Неизвестный тип контента');
    }
}

// Обработка цвета
function handleColorContent(content, display) {
    debugLog('Установка цвета: ' + content.data.color);
    display.style.backgroundColor = content.data.color;
    display.innerHTML = '';
}

// Обработка текста
function handleTextContent(content, display) {
    debugLog('Установка текста');
    display.style.backgroundColor = content.data.background || '#000000';
    display.innerHTML = `
        <div class="text-display" style="
            color: ${content.data.text_color || '#ffffff'}; 
            font-size: ${content.data.font_size || '48'}px;
        ">
            ${content.data.text || ''}
        </div>
    `;
}

// Обработка звука
function handleSoundContent(content, display) {
    debugLog('Воспроизведение звука: ' + content.data.frequency + 'Hz');
    display.style.backgroundColor = content.data.background || '#000000';
    display.innerHTML = '<div class="sound-indicator">♪ Воспроизведение звука ♪</div>';
    playSound(content.data.frequency, content.data.duration, content.data.wave_type);
}

// Обработка режима слов
function handleWordsContent(content, display) {
    debugLog('Режим слов: получены данные');
    
    if (!content.data || !content.data.words || !Array.isArray(content.data.words)) {
        debugLog('Ошибка: некорректные данные для режима слов');
        showError('Ошибка данных слов');
        return;
    }
    
    startWordMode(content.data);
}

// Обработка режима истории
function handleStoryContent(content, display) {
    debugLog('Режим истории: получены данные');
    
    if (!content.data || !content.data.words || !Array.isArray(content.data.words)) {
        debugLog('Ошибка: некорректные данные для режима истории');
        showError('Ошибка данных истории');
        return;
    }
    
    startStoryMode(content.data);
}

// Обработка режима бегущей строки
function handleTickerContent(content, display) {
    debugLog('Режим бегущей строки: получены данные');
    
    if (!content.data || !content.data.words || !Array.isArray(content.data.words)) {
        debugLog('Ошибка: некорректные данные для бегущей строки');
        showError('Ошибка данных бегущей строки');
        return;
    }
    
    startTickerMode(content.data);
}

// Обработка показа номера устройства
function handleDeviceNumberContent(content, display) {
    debugLog('Показ номера устройства');
    const deviceId = getDeviceId();
    
    display.style.backgroundColor = content.data.background || '#000000';
    display.innerHTML = `
        <div class="device-number-display" style="color: ${content.data.color || '#ffffff'};">
            ${deviceId}
        </div>
    `;
}

// Воспроизведение звука
function playSound(frequency, duration, waveType) {
    try {
        initAudioContext();
        
        if (!audioContext) {
            debugLog('Аудио контекст недоступен');
            return;
        }
        
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.type = waveType || 'sine';
        oscillator.frequency.setValueAtTime(frequency || 440, audioContext.currentTime);
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.3, audioContext.currentTime + 0.1);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + duration);
        
        currentOscillator = oscillator;
        debugLog('Звук запущен');
        
    } catch (e) {
        debugLog('Ошибка воспроизведения звука: ' + e.message);
    }
}

// Режим слов (старый функционал)
function startWordMode(config) {
    debugLog('Запуск режима слов');
    stopWordMode();
    
    wordModeActive = true;
    currentWords = config.words || [];
    
    if (currentWords.length === 0) {
        debugLog('Список слов пуст');
        return;
    }
    
    // Логика инициализации индекса (упрощенная версия)
    currentWordIndex = 0;
    if (config.random_mode) {
        currentWordIndex = Math.floor(Math.random() * currentWords.length);
    }
    
    displayCurrentWord(config);
    
    if (config.auto_change) {
        const interval = (config.interval || 3) * 1000;
        wordInterval = setInterval(() => {
            if (config.random_mode) {
                let newIndex;
                do {
                    newIndex = Math.floor(Math.random() * currentWords.length);
                } while (newIndex === currentWordIndex && currentWords.length > 1);
                currentWordIndex = newIndex;
            } else {
                currentWordIndex = (currentWordIndex + 1) % currentWords.length;
            }
            displayCurrentWord(config);
        }, interval);
    }
    
    currentConfig = config;
}

function stopWordMode() {
    if (wordInterval) {
        clearInterval(wordInterval);
        wordInterval = null;
    }
    if (wordSyncTimeout) {
        clearTimeout(wordSyncTimeout);
        wordSyncTimeout = null;
    }
    wordModeActive = false;
}

function displayCurrentWord(config) {
    if (!wordModeActive || currentWords.length === 0) return;
    
    const word = currentWords[currentWordIndex];
    const display = document.getElementById('content-display');
    
    let fontSize = config.font_size || 48;
    
    if (word.length > 15) {
        fontSize = Math.max(fontSize * 0.4, 24);
    } else if (word.length > 10) {
        fontSize = Math.max(fontSize * 0.6, 32);
    } else if (word.length > 6) {
        fontSize = Math.max(fontSize * 0.8, 40);
    }
    
    let backgroundColor = config.background || '#000000';
    let textColor = config.text_color || '#ffffff';
    
    if (config.random_colors) {
        const colors = generateContrastColors();
        backgroundColor = colors.background;
        textColor = colors.text;
    }
    
    display.style.backgroundColor = backgroundColor;
    display.innerHTML = `
        <div class="text-display" style="
            color: ${textColor}; 
            font-size: ${Math.floor(fontSize)}px;
        ">
            ${word}
        </div>
    `;
    
    debugLog('Показано слово: "' + word + '"');
}

// Генерация контрастных цветов
function generateContrastColors() {
    const backgroundHue = Math.floor(Math.random() * 360);
    const backgroundSat = Math.floor(Math.random() * 40) + 60;
    const backgroundLight = Math.floor(Math.random() * 30) + 20;
    
    let textLight = 85 + Math.floor(Math.random() * 15);
    
    if (Math.random() > 0.7) {
        const lightBackground = 70 + Math.floor(Math.random() * 25);
        const darkText = 10 + Math.floor(Math.random() * 20);
        
        return {
            background: `hsl(${backgroundHue}, ${backgroundSat}%, ${lightBackground}%)`,
            text: `hsl(${(backgroundHue + 180) % 360}, ${Math.min(backgroundSat + 20, 100)}%, ${darkText}%)`
        };
    }
    
    return {
        background: `hsl(${backgroundHue}, ${backgroundSat}%, ${backgroundLight}%)`,
        text: `hsl(${(backgroundHue + 180) % 360}, ${Math.min(backgroundSat + 20, 100)}%, ${textLight}%)`
    };
}

// Упрощенные заглушки для совместимости
function startSyncBeep() { /* TODO */ }
function stopSyncBeep() { /* TODO */ }
function startSpecialWordMode() { /* TODO */ }
function stopSpecialWordMode() { /* TODO */ }