/**
 * KeyboardShortcutManager - Manage keyboard shortcuts for desktop users
 */
class KeyboardShortcutManager {
    constructor() {
        this.shortcuts = {
            'search': { keys: ['ctrl', 'k'], action: 'focusSearch' },
            'newPost': { keys: ['ctrl', 'alt', 'n'], action: 'createPost' },
            'bookmarks': { keys: ['ctrl', 'b'], action: 'toggleBookmarks' },
            'settings': { keys: ['ctrl', ','], action: 'toggleSettings' },
            'notifications': { keys: ['ctrl', 'shift', 'n'], action: 'toggleNotifications' },
            'profile': { keys: ['ctrl', 'shift', 'p'], action: 'openProfile' },
            'help': { keys: ['shift', '?'], action: 'showHelp' },
            'dashboard': { keys: ['ctrl', 'd'], action: 'goToDashboard' },
            'toggleTheme': { keys: ['ctrl', 'shift', 't'], action: 'toggleTheme' }
        };
        this.userShortcuts = {};
        this.init();
    }

    async init() {
        await this.loadUserShortcuts();
        this.setupKeyListeners();
    }

    async loadUserShortcuts() {
        try {
            const response = await fetch('/api/preferences');
            const prefs = await response.json();
            if (prefs.shortcuts) {
                this.userShortcuts = { ...this.shortcuts, ...prefs.shortcuts };
            } else {
                this.userShortcuts = { ...this.shortcuts };
            }
        } catch (e) {
            this.userShortcuts = { ...this.shortcuts };
        }
    }

    setupKeyListeners() {
        document.addEventListener('keydown', (e) => {
            const active = document.activeElement;
            if (['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName) || active.isContentEditable) {
                return;
            }

            const keys = [];
            if (e.ctrlKey || e.metaKey) keys.push('ctrl');
            if (e.shiftKey) keys.push('shift');
            if (e.altKey) keys.push('alt');
            keys.push(e.key.toLowerCase());

            for (const [name, shortcut] of Object.entries(this.userShortcuts)) {
                if (this.keysMatch(keys, shortcut.keys)) {
                    e.preventDefault();
                    this.executeAction(shortcut.action);
                    break;
                }
            }
        });
    }

    keysMatch(pressedKeys, shortcutKeys) {
        if (pressedKeys.length !== shortcutKeys.length) return false;
        return shortcutKeys.every(k => pressedKeys.includes(k));
    }

    executeAction(action) {
        const actions = {
            'focusSearch': () => {
                const search = document.querySelector('input[name="q"]');
                if (search) { search.focus(); search.select(); }
            },
            'toggleBookmarks': () => window.desktopFeatures?.togglePanel(),
            'toggleSettings': () => window.location.href = '/settings',
            'createPost': () => window.location.href = '/post/create',
            'toggleNotifications': () => window.location.href = '/notifications',
            'openProfile': () => window.location.href = '/u/current',
            'showHelp': () => this.showShortcutsHelp(),
            'goToDashboard': () => window.location.href = '/dashboard',
            'toggleTheme': () => window.themeManager?.toggle()
        };

        if (actions[action]) actions[action]();
    }

    showShortcutsHelp() {
        // Simple alert for now or implement a modal
        const list = Object.entries(this.userShortcuts).map(([name, sc]) => `${sc.keys.join('+')}: ${name}`).join('\n');
        alert("⌨️ Клавіатурні скорочення:\n" + list);
    }
}

/**
 * ThemeManager - Handle light/dark mode
 */
class ThemeManager {
    constructor() {
        this.currentTheme = localStorage.getItem('theme') || 'light';
        this.applyTheme(this.currentTheme);
    }

    applyTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('theme', theme);
        this.currentTheme = theme;
        document.documentElement.style.colorScheme = theme;
    }

    toggle() {
        const newTheme = this.currentTheme === 'dark' ? 'light' : 'dark';
        this.applyTheme(newTheme);
    }
}

/**
 * ContentUtilities - Handle post translation and TTS
 */
class ContentUtilities {
    constructor() {
        this.synth = window.speechSynthesis;
        this.isSpeaking = false;
        this.voices = [];
        this.init();
    }

    init() {
        // Load voices
        const loadVoices = () => {
            this.voices = this.synth.getVoices();
        };
        loadVoices();
        if (this.synth.onvoiceschanged !== undefined) {
            this.synth.onvoiceschanged = loadVoices;
        }

        document.addEventListener('click', e => {
            const btn = e.target.closest('.btn-action-tts, .btn-action-translate');
            if (!btn) return;

            e.preventDefault();
            if (btn.classList.contains('btn-action-tts')) {
                this.handleTTS(btn);
            } else {
                this.handleTranslate(btn);
            }
        });
    }

    handleTTS(btn) {
        if (this.isSpeaking) {
            this.synth.cancel();
            this.isSpeaking = false;
            btn.innerHTML = '<i class="fas fa-volume-up"></i>';
            return;
        }

        const targetSelector = btn.getAttribute('data-target');
        let container = targetSelector === 'parent' ? 
            btn.closest('.comment-item')?.querySelector('.comment-markdown') : 
            document.querySelector(targetSelector);

        if (!container) return;

        // Clean text: remove links and extra whitespace
        let text = container.innerText.replace(/https?:\/\/\S+/g, '').trim();
        if (!text) return;

        const utterance = new SpeechSynthesisUtterance(text);
        
        // Language detection/mapping
        const docLang = document.documentElement.lang || 'en';
        const langMap = { 'ua': 'uk-UA', 'uk': 'uk-UA', 'ru': 'ru-RU', 'pl': 'pl-PL', 'en': 'en-US' };
        utterance.lang = langMap[docLang] || 'en-US';

        // Heuristic: if text contains Cyrillic but lang is EN, switch to UK/RU
        if (/[а-яА-ЯёЁіІїЇєЄ]/.test(text) && utterance.lang.startsWith('en')) {
            utterance.lang = 'uk-UA';
        }

        // Try to find a suitable voice
        if (this.voices.length > 0) {
            const voice = this.voices.find(v => v.lang === utterance.lang) || 
                         this.voices.find(v => v.lang.startsWith(utterance.lang.split('-')[0])) ||
                         (utterance.lang === 'uk-UA' ? this.voices.find(v => v.lang.startsWith('ru')) : null);
            
            if (voice) {
                utterance.voice = voice;
            }
        }

        utterance.onerror = (err) => {
            console.error('TTS Error:', err);
            this.isSpeaking = false;
            btn.innerHTML = '<i class="fas fa-volume-up"></i>';
        };

        utterance.onend = () => {
            this.isSpeaking = false;
            btn.innerHTML = '<i class="fas fa-volume-up"></i>';
        };

        this.synth.speak(utterance);
        this.isSpeaking = true;
        btn.innerHTML = '<i class="fas fa-stop"></i>';
    }

    async handleTranslate(btn) {
        const targetSelector = btn.getAttribute('data-target');
        let container = targetSelector === 'parent' ? 
            btn.closest('.comment-item')?.querySelector('.comment-markdown') : 
            document.querySelector(targetSelector);

        if (!container) return;

        if (container.hasAttribute('data-translated')) {
            const original = container.getAttribute('data-raw-content');
            container.innerHTML = original;
            container.removeAttribute('data-translated');
            btn.innerHTML = '<i class="fas fa-language"></i>';
            return;
        }

        const rawContent = btn.getAttribute('data-raw') || container.innerText;
        container.setAttribute('data-raw-content', container.innerHTML);

        const docLang = document.documentElement.lang || 'en';
        const targetLang = { 'ua': 'uk', 'uk': 'uk', 'ru': 'ru', 'pl': 'pl' }[docLang] || 'en';

        btn.disabled = true;
        const oldHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

        try {
            // Using Autodetect (case sensitive for some API versions) instead of auto
            const apiUri = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(rawContent.substring(0, 500))}&langpair=Autodetect|${targetLang}`;
            const response = await fetch(apiUri);
            const data = await response.json();
            
            if (data.responseData?.translatedText) {
                let translated = data.responseData.translatedText;
                
                // If the API returns an error message in translatedText (sometimes happens)
                if (translated.includes('INVALID SOURCE LANGUAGE')) {
                    // Fallback: try en|uk if autodetect fails
                    const fallbackUri = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(rawContent.substring(0, 500))}&langpair=en|${targetLang}`;
                    const fbResponse = await fetch(fallbackUri);
                    const fbData = await fbResponse.json();
                    if (fbData.responseData?.translatedText) {
                        translated = fbData.responseData.translatedText;
                    }
                }

                if (window.marked) {
                    container.innerHTML = window.marked.parse(translated);
                } else {
                    container.innerText = translated;
                }
                container.setAttribute('data-translated', 'true');
                btn.innerHTML = '<i class="fas fa-undo"></i>';
            } else if (data.responseStatus === 403 || data.responseStatus === '403') {
                console.error('Translation quota exceeded or blocked');
                btn.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
            }
        } catch (e) {
            console.error('Translation failed', e);
            btn.innerHTML = oldHtml;
        } finally {
            btn.disabled = false;
        }
    }
}

/**
 * DesktopFeatures - Premium Personal Hub (Bookmarks, History, Quick Notes)
 */
class DesktopFeatures {
    constructor() {
        this.historyLimit = 20;
        this.activeTab = 'bookmarks';
        this.init();
    }

    init() {
        this.setupBookmarks();
        this.trackHistory();
        this.injectStyles();
    }

    trackHistory() {
        if (window.location.pathname === '/login' || window.location.pathname === '/register') return;
        
        const history = JSON.parse(localStorage.getItem('view_history') || '[]');
        const page = {
            title: document.title.split('-')[0].trim(),
            url: window.location.pathname + window.location.search,
            time: new Date().getTime()
        };

        // Remove duplicate and add to start
        const filtered = history.filter(item => item.url !== page.url);
        filtered.unshift(page);
        
        localStorage.setItem('view_history', JSON.stringify(filtered.slice(0, this.historyLimit)));
    }

    setupBookmarks() {
        const btn = document.getElementById('bookmarks-btn');
        if (btn) btn.addEventListener('click', e => {
            e.preventDefault();
            this.togglePanel();
        });

        // Delegate deletion
        document.addEventListener('click', e => {
            if (e.target.closest('.btn-remove-hub-item')) {
                const btn = e.target.closest('.btn-remove-hub-item');
                this.removeItem(btn.dataset.type, btn.dataset.index);
            }
            if (e.target.closest('.hub-tab')) {
                const tab = e.target.closest('.hub-tab');
                this.switchTab(tab.dataset.tab);
            }
        });
    }

    togglePanel() {
        let panel = document.getElementById('desktop-hub-panel');
        if (panel) {
            panel.classList.toggle('visible');
            if (panel.classList.contains('visible')) this.render();
            return;
        }

        panel = document.createElement('div');
        panel.id = 'desktop-hub-panel';
        panel.className = 'desktop-hub-panel';
        document.body.appendChild(panel);
        
        setTimeout(() => panel.classList.add('visible'), 10);
        this.render();
    }

    switchTab(tab) {
        this.activeTab = tab;
        this.render();
    }

    addBookmark() {
        const bookmarks = JSON.parse(localStorage.getItem('bookmarks') || '[]');
        const page = {
            title: document.title.split('-')[0].trim(),
            url: window.location.pathname + window.location.search
        };

        if (!bookmarks.some(b => b.url === page.url)) {
            bookmarks.unshift(page);
            localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
            this.render();
            
            // Visual feedback
            const addBtn = document.querySelector('.hub-add-btn');
            if (addBtn) {
                addBtn.innerHTML = '<i class="fas fa-check"></i>';
                setTimeout(() => this.render(), 1000);
            }
        }
    }

    removeItem(type, index) {
        const key = type === 'bookmarks' ? 'bookmarks' : 'view_history';
        const items = JSON.parse(localStorage.getItem(key) || '[]');
        items.splice(index, 1);
        localStorage.setItem(key, JSON.stringify(items));
        this.render();
    }

    render() {
        const panel = document.getElementById('desktop-hub-panel');
        if (!panel) return;

        const bookmarks = JSON.parse(localStorage.getItem('bookmarks') || '[]');
        const history = JSON.parse(localStorage.getItem('view_history') || '[]');
        const t = window.translations || {};

        const currentUrl = window.location.pathname + window.location.search;
        const isBookmarked = bookmarks.some(b => b.url === currentUrl);

        panel.innerHTML = `
            <div class="hub-backdrop" onclick="this.parentElement.classList.remove('visible')"></div>
            <div class="hub-content">
                <div class="hub-header">
                    <div class="hub-tabs">
                        <button class="hub-tab ${this.activeTab === 'bookmarks' ? 'active' : ''}" data-tab="bookmarks">
                            <i class="fas fa-bookmark"></i> ${t.bookmarks || 'Bookmarks'}
                        </button>
                        <button class="hub-tab ${this.activeTab === 'history' ? 'active' : ''}" data-tab="history">
                            <i class="fas fa-history"></i> ${t.history || 'History'}
                        </button>
                    </div>
                    <button class="hub-close" onclick="this.closest('.desktop-hub-panel').classList.remove('visible')">×</button>
                </div>

                <div class="hub-body">
                    ${this.activeTab === 'bookmarks' ? `
                        <button class="hub-add-btn" onclick="window.desktopFeatures.addBookmark()" ${isBookmarked ? 'disabled' : ''}>
                            <i class="fas fa-${isBookmarked ? 'check' : 'plus'}"></i>
                            ${isBookmarked ? (t.saved || 'Saved') : (t.add_current_page || 'Add Current Page')}
                        </button>
                        <div class="hub-list">
                            ${bookmarks.length ? bookmarks.map((item, i) => `
                                <div class="hub-item">
                                    <a href="${item.url}" class="hub-item-link">
                                        <span class="hub-item-icon"><i class="fas fa-link"></i></span>
                                        <span class="hub-item-title">${item.title}</span>
                                    </a>
                                    <button class="btn-remove-hub-item" data-type="bookmarks" data-index="${i}"><i class="fas fa-times"></i></button>
                                </div>
                            `).join('') : `<div class="hub-empty">${t.empty || 'Empty'}</div>`}
                        </div>
                    ` : `
                        <div style="display: flex; justify-content: flex-end; margin-bottom: 1rem;">
                            <button class="hub-item-clear" onclick="window.desktopFeatures.clearHistory()">
                                <i class="fas fa-trash-sweep"></i> ${t.clear_all || 'Clear All'}
                            </button>
                        </div>
                        <div class="hub-list">
                            ${history.length ? history.map((item, i) => `
                                <div class="hub-item">
                                    <a href="${item.url}" class="hub-item-link">
                                        <span class="hub-item-icon"><i class="fas fa-clock"></i></span>
                                        <div class="hub-item-details">
                                            <span class="hub-item-title">${item.title}</span>
                                            <span class="hub-item-meta">${new Date(item.time).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                                        </div>
                                    </a>
                                    <button class="btn-remove-hub-item" data-type="history" data-index="${i}"><i class="fas fa-trash-alt"></i></button>
                                </div>
                            `).join('') : `<div class="hub-empty">${t.empty || 'Empty'}</div>`}
                        </div>
                    `}
                </div>
            </div>
        `;
    }

    clearHistory() {
        localStorage.removeItem('view_history');
        this.render();
    }

    injectStyles() {
        if (document.getElementById('desktop-hub-styles')) return;
        const style = document.createElement('style');
        style.id = 'desktop-hub-styles';
        style.textContent = `
            .desktop-hub-panel {
                position: fixed;
                top: 0; right: 0; width: 100%; height: 100%;
                z-index: 10000;
                pointer-events: none;
                display: flex;
                justify-content: flex-end;
            }
            .desktop-hub-panel.visible { pointer-events: auto; }
            
            .hub-backdrop {
                position: absolute;
                inset: 0;
                background: rgba(0,0,0,0.2);
                backdrop-filter: blur(4px);
                opacity: 0;
                transition: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .desktop-hub-panel.visible .hub-backdrop { opacity: 1; }

            .hub-content {
                position: relative;
                width: 380px;
                height: 100%;
                background: rgba(var(--card-rgb, 255, 255, 255), 0.85);
                backdrop-filter: blur(20px) saturate(180%);
                -webkit-backdrop-filter: blur(20px) saturate(180%);
                border-left: 1px solid rgba(255, 255, 255, 0.1);
                box-shadow: -10px 0 30px rgba(0,0,0,0.1);
                display: flex;
                flex-direction: column;
                transform: translateX(100%);
                transition: 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
                overflow: hidden;
            }
            [data-theme="dark"] .hub-content {
                background: rgba(30, 41, 59, 0.8);
                border-left: 1px solid rgba(255, 255, 255, 0.05);
            }
            .desktop-hub-panel.visible .hub-content { transform: translateX(0); }

            .hub-header {
                padding: 1.5rem;
                display: flex;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1px solid rgba(0,0,0,0.05);
            }

            .hub-tabs {
                display: flex;
                background: rgba(0,0,0,0.05);
                padding: 0.25rem;
                border-radius: 12px;
                gap: 0.25rem;
            }
            .hub-tab {
                border: none;
                background: transparent;
                padding: 0.5rem 1rem;
                border-radius: 9px;
                font-size: 0.85rem;
                font-weight: 600;
                color: var(--text-muted);
                cursor: pointer;
                transition: 0.3s;
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
            .hub-tab.active {
                background: var(--card);
                color: var(--primary);
                box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            }

            .hub-close {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                border: none;
                background: rgba(0,0,0,0.05);
                color: var(--text);
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 1.2rem;
                transition: 0.3s;
            }
            .hub-close:hover { background: #ef4444; color: white; transform: rotate(90deg); }

            .hub-body {
                flex: 1;
                overflow-y: auto;
                padding: 1.5rem;
            }

            .hub-add-btn {
                width: 100%;
                padding: 1rem;
                border-radius: 14px;
                border: 2px dashed var(--primary);
                background: rgba(99, 102, 241, 0.05);
                color: var(--primary);
                font-weight: 700;
                cursor: pointer;
                transition: 0.3s;
                margin-bottom: 2rem;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 0.75rem;
            }
            .hub-add-btn:hover:not(:disabled) { background: var(--primary); color: white; border-style: solid; }
            .hub-add-btn:disabled { opacity: 0.6; cursor: default; border-color: var(--border); color: var(--text-muted); }

            .hub-list { display: flex; flex-direction: column; gap: 0.75rem; }
            
            .hub-item {
                display: flex;
                align-items: center;
                gap: 0.75rem;
                padding: 0.75rem;
                background: var(--card);
                border: 1px solid var(--border);
                border-radius: 12px;
                transition: 0.3s;
                animation: slideIn 0.4s ease forwards;
            }
            .hub-item:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.05); border-color: var(--primary); }
            
            .hub-item-link {
                flex: 1;
                display: flex;
                align-items: center;
                gap: 1rem;
                text-decoration: none;
                color: inherit;
                overflow: hidden;
            }
            
            .hub-item-icon {
                width: 36px;
                height: 36px;
                background: rgba(99, 102, 241, 0.1);
                color: var(--primary);
                border-radius: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
            }
            
            .hub-item-details { display: flex; flex-direction: column; overflow: hidden; }
            .hub-item-title { font-weight: 600; font-size: 0.95rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
            .hub-item-meta { font-size: 0.75rem; color: var(--text-muted); }

            .btn-remove-hub-item {
                background: transparent;
                border: none;
                color: #ef4444;
                opacity: 0.2;
                cursor: pointer;
                padding: 0.5rem;
                transition: 0.3s;
            }
            .btn-remove-hub-item:hover { opacity: 1; }
            
            .hub-item-clear {
                background: transparent;
                border: none;
                color: var(--text-muted);
                font-size: 0.75rem;
                font-weight: 600;
                cursor: pointer;
                padding: 0.5rem;
                border-radius: 8px;
                transition: 0.3s;
                display: flex;
                align-items: center;
                gap: 0.4rem;
            }
            .hub-item-clear:hover { background: rgba(239, 68, 68, 0.1); color: #ef4444; }

            .hub-empty {
                text-align: center;
                padding: 4rem 2rem;
                color: var(--text-muted);
                font-style: italic;
            }

            @keyframes slideIn {
                from { opacity: 0; transform: translateX(20px); }
                to { opacity: 1; transform: translateX(0); }
            }
        `;
        document.head.appendChild(style);
    }
}

// Update KeyboardShortcutManager to use the new toggle
// And other existing classes...


// Init
document.addEventListener('DOMContentLoaded', () => {
    window.themeManager = new ThemeManager();
    window.keyboardManager = new KeyboardShortcutManager();
    window.contentUtils = new ContentUtilities();
    window.desktopFeatures = new DesktopFeatures();
});
