
// Режим бегущей строки - полная перезапись
let tickerModeActive = false;
let tickerWords = [];
let tickerConfig = null;
let tickerInterval = null;
let globalTickerStep = 0; // Глобальный счетчик шагов

// Запуск режима бегущей строки
function startTickerMode(config) {
    debugLog('=== ЗАПУСК БЕГУЩЕЙ СТРОКИ ===');
    
    stopTickerMode();
    
    tickerModeActive = true;
    tickerWords = config.words || [];
    tickerConfig = config;
    globalTickerStep = 0;
    
    if (tickerWords.length === 0) {
        debugLog('ОШИБКА: Нет слов для бегущей строки');
        showError('Нет слов для бегущей строки');
        return;
    }
    
    const deviceId = getDeviceId();
    const totalDevices = parseInt(config.total_devices) || 4;
    const speed = parseFloat(config.speed) || 1;
    const speedMs = speed * 1000;
    
    debugLog('Устройство: ' + deviceId + ', всего устройств: ' + totalDevices + ', скорость: ' + speedMs + 'мс');
    debugLog('Слова: [' + tickerWords.join(', ') + ']');
    
    // Показываем начальное состояние
    updateTickerDisplay(deviceId);
    
    // Запускаем движение
    tickerInterval = setInterval(() => {
        if (!tickerModeActive) return;
        
        globalTickerStep++;
        updateTickerDisplay(deviceId);
        
        // Проверяем завершение (все слова прошли через все устройства)
        if (globalTickerStep > tickerWords.length + totalDevices) {
            debugLog('Бегущая строка завершена, перезапуск...');
            globalTickerStep = 0; // Перезапускаем
        }
        
    }, speedMs);
}

// Обновление дисплея устройства
function updateTickerDisplay(deviceId) {
    if (!tickerModeActive) return;
    
    // Вычисляем какое слово должно показывать это устройство
    const wordIndex = globalTickerStep - (deviceId - 1);
    
    // ДИАГНОСТИКА - выводим подробную информацию
    const totalDevices = parseInt(tickerConfig.total_devices) || 4;
    debugLog('=== ДИАГНОСТИКА ===');
    debugLog('Глобальный шаг: ' + globalTickerStep);
    debugLog('ID устройства: ' + deviceId);
    debugLog('Всего устройств: ' + totalDevices);
    debugLog('Вычисленный индекс слова: ' + wordIndex);
    debugLog('Всего слов: ' + tickerWords.length);
    debugLog('================');
    
    if (wordIndex >= 0 && wordIndex < tickerWords.length) {
        // Показываем слово
        const word = tickerWords[wordIndex];
        showTickerWordOnScreen(word, wordIndex);
        debugLog('✅ Устройство ' + deviceId + ' ПОКАЗЫВАЕТ: "' + word + '" (индекс ' + wordIndex + ')');
    } else {
        // Пустой экран
        showEmptyTickerScreen();
        debugLog('⭕ Устройство ' + deviceId + ' ПУСТОЕ (индекс ' + wordIndex + ' вне диапазона 0-' + (tickerWords.length-1) + ')');
    }
    
    // Дополнительная проверка - покажем что должны показывать все устройства на этом шаге
    debugLog('--- Состояние всех устройств на шаге ' + globalTickerStep + ' ---');
    for (let i = 1; i <= totalDevices; i++) {
        const idx = globalTickerStep - (i - 1);
        if (idx >= 0 && idx < tickerWords.length) {
            debugLog('Устройство ' + i + ': "' + tickerWords[idx] + '" (индекс ' + idx + ')');
        } else {
            debugLog('Устройство ' + i + ': ПУСТОЕ (индекс ' + idx + ')');
        }
    }
    debugLog('----------------------------------------');
}

// Показать слово на экране
function showTickerWordOnScreen(word, index) {
    if (!tickerModeActive || !word) return;
    
    const display = document.getElementById('content-display');
    if (!display) {
        debugLog('ОШИБКА: элемент content-display не найден');
        return;
    }
    
    // Размер шрифта в зависимости от длины слова
    let fontSize = tickerConfig.font_size || 50;
    if (word.length > 15) fontSize = Math.max(fontSize * 0.4, 25);
    else if (word.length > 10) fontSize = Math.max(fontSize * 0.6, 35);
    else if (word.length > 6) fontSize = Math.max(fontSize * 0.8, 45);
    
    // Цвета
    let backgroundColor = tickerConfig.background || '#001100';
    let textColor = tickerConfig.text_color || '#00ff00';
    
    if (tickerConfig.random_colors) {
        const colors = generateRandomTickerColors();
        backgroundColor = colors.background;
        textColor = colors.text;
    }
    
    display.style.backgroundColor = backgroundColor;
    display.innerHTML = `
        <div style="
            color: ${textColor};
            font-size: ${Math.floor(fontSize)}px;
            font-weight: bold;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100vh;
            word-wrap: break-word;
            line-height: 1.2;
        ">
            ${word}
        </div>
    `;
    
    // Звук если включен
    if (tickerConfig.beep_enabled) {
        playTickerSound();
    }
}

// Показать пустой экран
function showEmptyTickerScreen() {
    if (!tickerModeActive) return;
    
    const display = document.getElementById('content-display');
    if (display) {
        display.style.backgroundColor = tickerConfig.background || '#001100';
        display.innerHTML = '';
    }
}

// Генерация случайных цветов
function generateRandomTickerColors() {
    const hue = Math.floor(Math.random() * 360);
    const saturation = 60 + Math.floor(Math.random() * 40); // 60-100%
    const lightness = 20 + Math.floor(Math.random() * 30); // 20-50% для фона
    const textLightness = 80 + Math.floor(Math.random() * 20); // 80-100% для текста
    
    return {
        background: `hsl(${hue}, ${saturation}%, ${lightness}%)`,
        text: `hsl(${(hue + 180) % 360}, ${saturation}%, ${textLightness}%)`
    };
}

// Воспроизведение звука
function playTickerSound() {
    if (!tickerConfig || !tickerConfig.beep_enabled) return;
    
    try {
        initAudioContext();
        if (!audioContext) return;
        
        const frequency = tickerConfig.beep_frequency || 600;
        const duration = tickerConfig.beep_duration || 0.2;
        
        let soundType = tickerConfig.beep_sound_type || 'triangle';
        if (tickerConfig.random_beep_sounds) {
            const types = ['sine', 'square', 'sawtooth', 'triangle'];
            soundType = types[Math.floor(Math.random() * types.length)];
        }
        
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.type = soundType;
        oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.2, audioContext.currentTime + 0.02);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + duration);
        
        debugLog('Звук: ' + soundType + ' ' + frequency + 'Hz');
        
    } catch (e) {
        debugLog('Ошибка звука: ' + e.message);
    }
}

// Остановка режима
function stopTickerMode() {
    if (tickerInterval) {
        clearInterval(tickerInterval);
        tickerInterval = null;
    }
    tickerModeActive = false;
    globalTickerStep = 0;
    debugLog('=== БЕГУЩАЯ СТРОКА ОСТАНОВЛЕНА ===');
}

// Функции для совместимости (заглушки)
function showTickerWord() {
    // Заглушка - функционал перенесен в showTickerWordOnScreen
}

function showEmptyTickerDisplay() {
    showEmptyTickerScreen();
}

function playTickerBeep() {
    playTickerSound();
}