/*
 * Wikipedia Explorer - Advanced Educational Tool
 * Enhanced JavaScript with Premium Features
 * Developed by RSK World (https://rskworld.in)
 * Founder: Molla Samser
 * Designer & Tester: Rima Khatun
 * Contact: info@rskworld.com, +91 93305 39277
 * Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
 * © 2026 RSK World. All rights reserved.
 * Content used for educational purposes only.
 */

class WikipediaExplorer {
    constructor() {
        this.apiBaseUrl = 'https://en.wikipedia.org/api/rest_v1';
        this.wikiApiUrl = 'https://en.wikipedia.org/w/api.php';
        this.currentSearch = '';
        this.currentResults = [];
        this.currentArticle = null;
        this.debounceTimer = null;
        this.bookmarks = this.loadBookmarks();
        this.history = this.loadHistory();
        this.settings = this.loadSettings();
        this.currentTheme = this.settings.theme || 'light';
        this.fontSize = this.settings.fontSize || 16;
        this.speechSynthesis = window.speechSynthesis;
        this.currentUtterance = null;
        this.readingProgress = 0;
        
        this.init();
    }

    init() {
        this.applyTheme();
        this.applyFontSize();
        this.bindEvents();
        this.setupSearchSuggestions();
        this.setupCategoryCards();
        this.setupModals();
        this.setupDarkMode();
        this.setupTextToSpeech();
        this.setupKeyboardShortcuts();
        this.trackPageView();
    }

    bindEvents() {
        // Search form submission
        const searchForm = document.getElementById('searchForm');
        if (searchForm) {
            searchForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleSearch();
            });
        }

        // Search input for suggestions
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.handleSearchSuggestions(e.target.value);
            });

            // Hide suggestions when clicking outside
            document.addEventListener('click', (e) => {
                if (!e.target.closest('#searchInput') && !e.target.closest('#suggestions')) {
                    this.hideSuggestions();
                }
            });
        }

        // Quick tags
        document.querySelectorAll('.quick-tag').forEach(tag => {
            tag.addEventListener('click', () => {
                const query = tag.dataset.query;
                document.getElementById('searchInput').value = query;
                this.handleSearch();
            });
        });

        // Advanced filters
        const filterBtn = document.getElementById('filterBtn');
        if (filterBtn) {
            filterBtn.addEventListener('click', () => {
                this.toggleAdvancedFilters();
            });
        }

        // Sort filter
        const sortFilter = document.getElementById('sortFilter');
        if (sortFilter) {
            sortFilter.addEventListener('change', () => {
                if (this.currentResults.length > 0) {
                    this.sortResults(sortFilter.value);
                }
            });
        }

        // Back button
        const backBtn = document.getElementById('backBtn');
        if (backBtn) {
            backBtn.addEventListener('click', () => {
                this.showResults();
            });
        }

        // Bookmark button
        const bookmarkBtn = document.getElementById('bookmarkBtn');
        if (bookmarkBtn) {
            bookmarkBtn.addEventListener('click', () => {
                this.toggleBookmark();
            });
        }

        // Text-to-speech button
        const ttsBtn = document.getElementById('ttsBtn');
        if (ttsBtn) {
            ttsBtn.addEventListener('click', () => {
                this.toggleTextToSpeech();
            });
        }

        // Font size controls
        const fontSizeIncrease = document.getElementById('fontSizeIncrease');
        const fontSizeDecrease = document.getElementById('fontSizeDecrease');
        if (fontSizeIncrease) {
            fontSizeIncrease.addEventListener('click', () => {
                this.changeFontSize(1);
            });
        }
        if (fontSizeDecrease) {
            fontSizeDecrease.addEventListener('click', () => {
                this.changeFontSize(-1);
            });
        }

        // Print button
        const printBtn = document.getElementById('printBtn');
        if (printBtn) {
            printBtn.addEventListener('click', () => {
                this.printArticle();
            });
        }

        // Share buttons
        const shareBtn = document.getElementById('shareBtn');
        const shareArticleBtn = document.getElementById('shareArticleBtn');
        if (shareBtn) {
            shareBtn.addEventListener('click', () => {
                this.shareApp();
            });
        }
        if (shareArticleBtn) {
            shareArticleBtn.addEventListener('click', () => {
                this.shareArticle();
            });
        }

        // Export button
        const exportBtn = document.getElementById('exportBtn');
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                this.exportResults();
            });
        }

        // Bookmark all button
        const bookmarkAllBtn = document.getElementById('bookmarkAllBtn');
        if (bookmarkAllBtn) {
            bookmarkAllBtn.addEventListener('click', () => {
                this.bookmarkAllResults();
            });
        }

        // User menu items
        const bookmarksBtn = document.getElementById('bookmarksBtn');
        const historyBtn = document.getElementById('historyBtn');
        const settingsBtn = document.getElementById('settingsBtn');

        if (bookmarksBtn) {
            bookmarksBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.showBookmarksModal();
            });
        }
        if (historyBtn) {
            historyBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.showHistoryModal();
            });
        }
        if (settingsBtn) {
            settingsBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.showSettingsModal();
            });
        }

        // Quick action buttons
        const translateBtn = document.getElementById('translateBtn');
        const citeBtn = document.getElementById('citeBtn');
        const summaryBtn = document.getElementById('summaryBtn');

        if (translateBtn) {
            translateBtn.addEventListener('click', () => {
                this.translateArticle();
            });
        }
        if (citeBtn) {
            citeBtn.addEventListener('click', () => {
                this.generateCitation();
            });
        }
        if (summaryBtn) {
            summaryBtn.addEventListener('click', () => {
                this.generateSummary();
            });
        }

        // Modal buttons
        const clearBookmarksBtn = document.getElementById('clearBookmarksBtn');
        const exportBookmarksBtn = document.getElementById('exportBookmarksBtn');
        const clearHistoryBtn = document.getElementById('clearHistoryBtn');
        const exportHistoryBtn = document.getElementById('exportHistoryBtn');
        const saveSettingsBtn = document.getElementById('saveSettingsBtn');

        if (clearBookmarksBtn) {
            clearBookmarksBtn.addEventListener('click', () => {
                this.clearBookmarks();
            });
        }
        if (exportBookmarksBtn) {
            exportBookmarksBtn.addEventListener('click', () => {
                this.exportBookmarks();
            });
        }
        if (clearHistoryBtn) {
            clearHistoryBtn.addEventListener('click', () => {
                this.clearHistory();
            });
        }
        if (exportHistoryBtn) {
            exportHistoryBtn.addEventListener('click', () => {
                this.exportHistory();
            });
        }
        if (saveSettingsBtn) {
            saveSettingsBtn.addEventListener('click', () => {
                this.saveSettings();
            });
        }

        // Footer links
        const aboutLink = document.getElementById('aboutLink');
        const featuresLink = document.getElementById('featuresLink');
        const helpLink = document.getElementById('helpLink');
        const privacyLink = document.getElementById('privacyLink');

        if (aboutLink) {
            aboutLink.addEventListener('click', (e) => {
                e.preventDefault();
                this.showAbout();
            });
        }
        if (featuresLink) {
            featuresLink.addEventListener('click', (e) => {
                e.preventDefault();
                this.showFeatures();
            });
        }
        if (helpLink) {
            helpLink.addEventListener('click', (e) => {
                e.preventDefault();
                this.showHelp();
            });
        }
        if (privacyLink) {
            privacyLink.addEventListener('click', (e) => {
                e.preventDefault();
                this.showPrivacy();
            });
        }

        // Reading progress tracking
        window.addEventListener('scroll', () => {
            this.updateReadingProgress();
        });
    }

    setupDarkMode() {
        const darkModeToggle = document.getElementById('darkModeToggle');
        if (darkModeToggle) {
            darkModeToggle.checked = this.currentTheme === 'dark';
            darkModeToggle.addEventListener('change', () => {
                this.toggleTheme();
            });
        }
    }

    setupTextToSpeech() {
        if ('speechSynthesis' in window) {
            // Initialize voices
            const loadVoices = () => {
                this.voices = this.speechSynthesis.getVoices();
            };
            loadVoices();
            this.speechSynthesis.onvoiceschanged = loadVoices;
        }
    }

    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + K for search focus
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                document.getElementById('searchInput')?.focus();
            }
            
            // Escape to close modals
            if (e.key === 'Escape') {
                const modals = document.querySelectorAll('.modal.show');
                modals.forEach(modal => {
                    const bsModal = bootstrap.Modal.getInstance(modal);
                    if (bsModal) bsModal.hide();
                });
            }
            
            // Ctrl/Cmd + P for print
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                if (this.currentArticle) {
                    e.preventDefault();
                    this.printArticle();
                }
            }
        });
    }

    setupModals() {
        // Initialize Bootstrap modals
        this.bookmarksModal = new bootstrap.Modal(document.getElementById('bookmarksModal'));
        this.historyModal = new bootstrap.Modal(document.getElementById('historyModal'));
        this.settingsModal = new bootstrap.Modal(document.getElementById('settingsModal'));
    }

    toggleTheme() {
        this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
        this.applyTheme();
        this.saveSettings();
        this.trackEvent('theme_toggle', this.currentTheme);
    }

    applyTheme() {
        document.documentElement.setAttribute('data-theme', this.currentTheme);
        const darkModeToggle = document.getElementById('darkModeToggle');
        if (darkModeToggle) {
            darkModeToggle.checked = this.currentTheme === 'dark';
        }
    }

    changeFontSize(delta) {
        this.fontSize = Math.max(12, Math.min(24, this.fontSize + delta));
        this.applyFontSize();
        this.saveSettings();
    }

    applyFontSize() {
        const articleContent = document.getElementById('articleContent');
        if (articleContent) {
            articleContent.style.fontSize = `${this.fontSize}px`;
        }
    }

    toggleAdvancedFilters() {
        const advancedFilters = document.getElementById('advancedFilters');
        const filterBtn = document.getElementById('filterBtn');
        
        if (advancedFilters.classList.contains('d-none')) {
            advancedFilters.classList.remove('d-none');
            filterBtn.classList.add('active');
        } else {
            advancedFilters.classList.add('d-none');
            filterBtn.classList.remove('active');
        }
    }

    async handleSearch() {
        const searchInput = document.getElementById('searchInput');
        const searchTerm = searchInput.value.trim();
        
        if (!searchTerm) {
            this.showError('Please enter a search term');
            return;
        }

        this.currentSearch = searchTerm;
        this.showLoading();
        this.hideSuggestions();
        this.addToHistory(searchTerm);

        try {
            const results = await this.searchWikipedia(searchTerm);
            this.currentResults = results;
            this.displayResults(results);
            this.trackEvent('search', searchTerm);
        } catch (error) {
            this.showError('Failed to search Wikipedia. Please try again.');
            console.error('Search error:', error);
            this.trackEvent('search_error', error.message);
        } finally {
            this.hideLoading();
        }
    }

    async handleSearchSuggestions(query) {
        if (query.length < 2) {
            this.hideSuggestions();
            return;
        }

        // Clear previous timer
        if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
        }

        // Debounce search suggestions
        this.debounceTimer = setTimeout(async () => {
            try {
                const suggestions = await this.getSearchSuggestions(query);
                this.displaySuggestions(suggestions);
            } catch (error) {
                console.error('Suggestions error:', error);
            }
        }, 300);
    }

    async getSearchSuggestions(query) {
        const url = `${this.wikiApiUrl}?action=query&list=search&srlimit=10&srsearch=${encodeURIComponent(query)}&format=json&origin=*`;
        
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('Failed to fetch suggestions');
        }
        
        const data = await response.json();
        return data.query.search.map(item => item.title);
    }

    displaySuggestions(suggestions) {
        const suggestionsContainer = document.getElementById('suggestions');
        
        if (suggestions.length === 0) {
            this.hideSuggestions();
            return;
        }

        suggestionsContainer.innerHTML = suggestions.map(suggestion => `
            <div class="suggestion-item" data-suggestion="${this.escapeHtml(suggestion)}">
                <i class="fas fa-search me-2 text-muted"></i>
                ${this.escapeHtml(suggestion)}
            </div>
        `).join('');

        // Add click handlers to suggestions
        suggestionsContainer.querySelectorAll('.suggestion-item').forEach(item => {
            item.addEventListener('click', () => {
                const suggestion = item.dataset.suggestion;
                document.getElementById('searchInput').value = suggestion;
                this.hideSuggestions();
                this.handleSearch();
            });
        });

        suggestionsContainer.style.display = 'block';
    }

    hideSuggestions() {
        const suggestionsContainer = document.getElementById('suggestions');
        suggestionsContainer.style.display = 'none';
        suggestionsContainer.innerHTML = '';
    }

    async searchWikipedia(query) {
        const url = `${this.wikiApiUrl}?action=query&list=search&srlimit=20&srsearch=${encodeURIComponent(query)}&format=json&origin=*`;
        
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('Failed to search Wikipedia');
        }
        
        const data = await response.json();
        const searchResults = data.query.search;

        // Get detailed information for each result
        const detailedResults = await Promise.all(
            searchResults.map(async (result) => {
                try {
                    const details = await this.getArticleDetails(result.pageid);
                    return {
                        ...result,
                        ...details
                    };
                } catch (error) {
                    console.error('Error getting details for page:', result.pageid, error);
                    return result;
                }
            })
        );

        return detailedResults;
    }

    async getArticleDetails(pageId) {
        const url = `${this.wikiApiUrl}?action=query&pageids=${pageId}&prop=extracts|info|pageimages|categories&inprop=url|displaytitle|lastrevid&explaintext=true&piprop=original&format=json&origin=*`;
        
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('Failed to get article details');
        }
        
        const data = await response.json();
        const page = data.query.pages[pageId];
        
        return {
            url: page.fullurl,
            displaytitle: page.displaytitle,
            extract: page.extract,
            thumbnail: page.original ? page.original.source : null,
            length: page.length,
            lastmodified: page.touched,
            categories: page.categories ? page.categories.map(cat => cat.title) : []
        };
    }

    sortResults(sortBy) {
        switch (sortBy) {
            case 'relevance':
                // Default order
                break;
            case 'recent':
                this.currentResults.sort((a, b) => new Date(b.lastmodified) - new Date(a.lastmodified));
                break;
            case 'size':
                this.currentResults.sort((a, b) => (b.length || 0) - (a.length || 0));
                break;
            case 'alphabetical':
                this.currentResults.sort((a, b) => a.title.localeCompare(b.title));
                break;
        }
        this.displayResults(this.currentResults);
    }

    displayResults(results) {
        const resultsSection = document.getElementById('resultsSection');
        const searchResults = document.getElementById('searchResults');
        const resultsCount = document.getElementById('resultsCount');
        
        if (results.length === 0) {
            searchResults.innerHTML = `
                <div class="col-12">
                    <div class="alert alert-info text-center">
                        <i class="fas fa-info-circle me-2"></i>
                        No results found for "${this.escapeHtml(this.currentSearch)}"
                    </div>
                </div>
            `;
        } else {
            searchResults.innerHTML = results.map(result => this.createResultCard(result)).join('');
            
            // Add click handlers to result cards
            searchResults.querySelectorAll('.search-result-card').forEach((card, index) => {
                card.addEventListener('click', () => {
                    this.showArticle(results[index]);
                });
            });
        }

        // Update results count
        if (resultsCount) {
            resultsCount.textContent = results.length;
        }

        this.showResults();
    }

    createResultCard(result) {
        const thumbnail = result.thumbnail ? 
            `<img src="${result.thumbnail}" class="card-img-top" alt="${this.escapeHtml(result.title)}">` : 
            `<div class="card-img-top d-flex align-items-center justify-content-center bg-light">
                <i class="fas fa-book fa-3x text-muted"></i>
            </div>`;

        const extract = result.extract ? 
            result.extract.substring(0, 200) + (result.extract.length > 200 ? '...' : '') : 
            'No description available';

        const isBookmarked = this.bookmarks.some(bookmark => bookmark.pageid === result.pageid);

        return `
            <div class="col-lg-6 col-md-12">
                <div class="card search-result-card fade-in gpu-accelerated">
                    ${thumbnail}
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h5 class="card-title">${this.escapeHtml(result.title)}</h5>
                            <button class="btn btn-sm btn-outline-primary bookmark-result-btn" data-pageid="${result.pageid}" title="Bookmark">
                                <i class="fas fa-bookmark ${isBookmarked ? 'text-primary' : ''}"></i>
                            </button>
                        </div>
                        <p class="card-text text-truncate-3">${this.escapeHtml(extract)}</p>
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">
                                <i class="fas fa-file-alt me-1"></i>
                                ${this.formatFileSize(result.length || 0)}
                            </small>
                            <div>
                                ${result.categories && result.categories.length > 0 ? 
                                    `<span class="badge bg-secondary me-1">${result.categories[0].replace('Category:', '')}</span>` : 
                                    ''}
                                <span class="badge bg-primary">Read More</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    async showArticle(result) {
        this.showLoading();
        
        try {
            const articleData = await this.getFullArticle(result.pageid);
            this.currentArticle = articleData;
            this.displayArticle(articleData);
            
            // Get related articles
            this.getRelatedArticles(result.title);
            
            // Update bookmark button
            this.updateBookmarkButton();
            
            // Track article view
            this.trackEvent('article_view', result.title);
            
        } catch (error) {
            this.showError('Failed to load article. Please try again.');
            console.error('Article load error:', error);
            this.trackEvent('article_error', error.message);
        } finally {
            this.hideLoading();
        }
    }

    async getFullArticle(pageId) {
        const url = `${this.wikiApiUrl}?action=query&pageids=${pageId}&prop=extracts|info|categories|revisions&inprop=url|displaytitle|lastrevid&explaintext=true&format=json&origin=*`;
        
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('Failed to get full article');
        }
        
        const data = await response.json();
        const page = data.query.pages[pageId];
        
        return {
            pageid: pageId,
            title: page.displaytitle || page.title,
            content: page.extract,
            url: page.fullurl,
            categories: page.categories ? page.categories.map(cat => cat.title) : [],
            lastModified: page.touched,
            length: page.length
        };
    }

    displayArticle(article) {
        const articleSection = document.getElementById('articleSection');
        const articleContent = document.getElementById('articleContent');
        
        const content = `
            <div class="article-header">
                <h1 class="article-title">${this.escapeHtml(article.title)}</h1>
                <div class="article-meta">
                    <small>
                        <i class="fas fa-calendar me-1"></i>
                        Last modified: ${new Date(article.lastModified).toLocaleDateString()}
                        <span class="ms-3">
                            <i class="fas fa-file-alt me-1"></i>
                            ${this.formatFileSize(article.length)}
                        </span>
                        <span class="ms-3">
                            <i class="fas fa-clock me-1"></i>
                            ${this.calculateReadingTime(article.content)} min read
                        </span>
                    </small>
                </div>
            </div>
            <div class="article-content">
                ${this.formatArticleContent(article.content)}
            </div>
            <div class="article-footer mt-4">
                <a href="${article.url}" target="_blank" class="btn btn-outline-primary">
                    <i class="fas fa-external-link-alt me-2"></i>
                    View on Wikipedia
                </a>
            </div>
        `;
        
        articleContent.innerHTML = content;
        
        // Update article stats
        this.updateArticleStats(article);
        
        // Apply font size
        this.applyFontSize();
        
        // Reset reading progress
        this.readingProgress = 0;
        this.updateReadingProgress();
        
        this.showArticleView();
    }

    formatArticleContent(content) {
        if (!content) return '<p>No content available.</p>';
        
        // Convert plain text to HTML paragraphs
        return content
            .split('\n\n')
            .filter(paragraph => paragraph.trim())
            .map(paragraph => `<p>${this.escapeHtml(paragraph)}</p>`)
            .join('');
    }

    updateArticleStats(article) {
        const readingTime = document.getElementById('readingTime');
        const wordCount = document.getElementById('wordCount');
        const lastUpdated = document.getElementById('lastUpdated');
        
        if (readingTime) {
            readingTime.textContent = `${this.calculateReadingTime(article.content)} min`;
        }
        if (wordCount) {
            wordCount.textContent = this.countWords(article.content);
        }
        if (lastUpdated) {
            lastUpdated.textContent = new Date(article.lastModified).toLocaleDateString();
        }
    }

    calculateReadingTime(content) {
        if (!content) return 0;
        const wordsPerMinute = 200;
        const words = this.countWords(content);
        return Math.ceil(words / wordsPerMinute);
    }

    countWords(text) {
        if (!text) return 0;
        return text.split(/\s+/).filter(word => word.length > 0).length;
    }

    updateReadingProgress() {
        if (!this.currentArticle) return;
        
        const articleContent = document.getElementById('articleContent');
        const progressBar = document.getElementById('readingProgress');
        
        if (!articleContent || !progressBar) return;
        
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const scrollHeight = articleContent.offsetHeight;
        const clientHeight = window.innerHeight;
        
        this.readingProgress = Math.min(100, Math.max(0, (scrollTop / (scrollHeight - clientHeight)) * 100));
        progressBar.style.width = `${this.readingProgress}%`;
    }

    async getRelatedArticles(title) {
        try {
            const related = await this.searchWikipedia(`${title} related`);
            const relatedArticles = document.getElementById('relatedArticles');
            
            if (related.length > 0) {
                relatedArticles.innerHTML = related.slice(0, 5).map(article => `
                    <a href="#" class="related-article" data-pageid="${article.pageid}">
                        <i class="fas fa-book-open me-2"></i>
                        ${this.escapeHtml(article.title)}
                    </a>
                `).join('');
                
                // Add click handlers
                relatedArticles.querySelectorAll('.related-article').forEach(link => {
                    link.addEventListener('click', (e) => {
                        e.preventDefault();
                        const pageId = e.target.dataset.pageid;
                        const article = related.find(a => a.pageid == pageId);
                        if (article) {
                            this.showArticle(article);
                        }
                    });
                });
            } else {
                relatedArticles.innerHTML = '<p class="text-muted">No related articles found.</p>';
            }
        } catch (error) {
            console.error('Error getting related articles:', error);
            document.getElementById('relatedArticles').innerHTML = '<p class="text-muted">Unable to load related articles.</p>';
        }
    }

    async searchByCategory(category) {
        const categoryTerms = {
            science: 'science technology physics chemistry biology',
            history: 'history ancient medieval modern war',
            technology: 'technology computers internet software',
            arts: 'art music literature painting sculpture',
            geography: 'geography countries cities nature',
            sports: 'sports games athletes olympics',
            health: 'health medicine fitness wellness',
            education: 'education schools learning research'
        };
        
        const searchTerm = categoryTerms[category] || category;
        document.getElementById('searchInput').value = searchTerm;
        this.handleSearch();
    }

    setupCategoryCards() {
        const categoryCards = document.querySelectorAll('.category-card');
        categoryCards.forEach(card => {
            card.addEventListener('click', () => {
                const category = card.dataset.category;
                this.searchByCategory(category);
                this.trackEvent('category_search', category);
            });
        });
    }

    // Bookmark functionality
    toggleBookmark() {
        if (!this.currentArticle) return;
        
        const existingIndex = this.bookmarks.findIndex(b => b.pageid === this.currentArticle.pageid);
        
        if (existingIndex > -1) {
            this.bookmarks.splice(existingIndex, 1);
            this.showNotification('Bookmark removed', 'info');
        } else {
            this.bookmarks.push({
                ...this.currentArticle,
                bookmarkedAt: new Date().toISOString()
            });
            this.showNotification('Article bookmarked', 'success');
        }
        
        this.saveBookmarks();
        this.updateBookmarkButton();
        this.trackEvent('bookmark_toggle', this.currentArticle.title);
    }

    updateBookmarkButton() {
        const bookmarkBtn = document.getElementById('bookmarkBtn');
        if (!bookmarkBtn || !this.currentArticle) return;
        
        const isBookmarked = this.bookmarks.some(b => b.pageid === this.currentArticle.pageid);
        
        if (isBookmarked) {
            bookmarkBtn.innerHTML = '<i class="fas fa-bookmark-fill"></i>';
            bookmarkBtn.classList.remove('btn-outline-primary');
            bookmarkBtn.classList.add('btn-primary');
        } else {
            bookmarkBtn.innerHTML = '<i class="fas fa-bookmark"></i>';
            bookmarkBtn.classList.remove('btn-primary');
            bookmarkBtn.classList.add('btn-outline-primary');
        }
    }

    bookmarkAllResults() {
        if (this.currentResults.length === 0) return;
        
        let addedCount = 0;
        this.currentResults.forEach(result => {
            if (!this.bookmarks.some(b => b.pageid === result.pageid)) {
                this.bookmarks.push({
                    ...result,
                    bookmarkedAt: new Date().toISOString()
                });
                addedCount++;
            }
        });
        
        this.saveBookmarks();
        this.showNotification(`${addedCount} articles bookmarked`, 'success');
        this.trackEvent('bookmark_all', addedCount);
    }

    // Text-to-speech functionality
    toggleTextToSpeech() {
        if (!this.currentArticle) return;
        
        if (this.speechSynthesis.speaking) {
            if (this.speechSynthesis.paused) {
                this.speechSynthesis.resume();
                this.updateTTSButton('playing');
            } else {
                this.speechSynthesis.pause();
                this.updateTTSButton('paused');
            }
        } else {
            this.startTextToSpeech();
        }
    }

    startTextToSpeech() {
        if (!this.currentArticle || !this.speechSynthesis) return;
        
        const text = this.currentArticle.content;
        if (!text) return;
        
        this.currentUtterance = new SpeechSynthesisUtterance(text);
        this.currentUtterance.rate = 0.9;
        this.currentUtterance.pitch = 1;
        this.currentUtterance.volume = 1;
        
        // Select voice
        if (this.voices && this.voices.length > 0) {
            const preferredVoice = this.voices.find(voice => voice.lang.startsWith('en'));
            this.currentUtterance.voice = preferredVoice || this.voices[0];
        }
        
        this.currentUtterance.onend = () => {
            this.updateTTSButton('stopped');
        };
        
        this.currentUtterance.onerror = (event) => {
            console.error('Speech synthesis error:', event);
            this.updateTTSButton('error');
            this.showNotification('Text-to-speech error occurred', 'error');
        };
        
        this.speechSynthesis.speak(this.currentUtterance);
        this.updateTTSButton('playing');
        this.trackEvent('tts_start', this.currentArticle.title);
    }

    updateTTSButton(state) {
        const ttsBtn = document.getElementById('ttsBtn');
        if (!ttsBtn) return;
        
        switch (state) {
            case 'playing':
                ttsBtn.innerHTML = '<i class="fas fa-pause"></i>';
                ttsBtn.classList.remove('btn-outline-info');
                ttsBtn.classList.add('btn-info');
                break;
            case 'paused':
                ttsBtn.innerHTML = '<i class="fas fa-play"></i>';
                ttsBtn.classList.remove('btn-info');
                ttsBtn.classList.add('btn-outline-info');
                break;
            case 'stopped':
            case 'error':
                ttsBtn.innerHTML = '<i class="fas fa-volume-up"></i>';
                ttsBtn.classList.remove('btn-info');
                ttsBtn.classList.add('btn-outline-info');
                break;
        }
    }

    // History functionality
    addToHistory(searchTerm) {
        if (!this.settings.autoSaveBookmarks) return;
        
        // Remove existing entry if present
        this.history = this.history.filter(item => item.term !== searchTerm);
        
        // Add to beginning
        this.history.unshift({
            term: searchTerm,
            timestamp: new Date().toISOString()
        });
        
        // Keep only last 50 entries
        this.history = this.history.slice(0, 50);
        
        this.saveHistory();
    }

    // Modal functionality
    showBookmarksModal() {
        const bookmarksList = document.getElementById('bookmarksList');
        
        if (this.bookmarks.length === 0) {
            bookmarksList.innerHTML = '<p class="text-muted text-center">No bookmarks yet. Start exploring and bookmark your favorite articles!</p>';
        } else {
            bookmarksList.innerHTML = this.bookmarks.map(bookmark => `
                <div class="d-flex justify-content-between align-items-center p-2 border-bottom">
                    <div class="flex-grow-1">
                        <h6 class="mb-1">${this.escapeHtml(bookmark.title)}</h6>
                        <small class="text-muted">${new Date(bookmark.bookmarkedAt).toLocaleDateString()}</small>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-sm btn-outline-primary" onclick="explorer.showArticleFromBookmark(${bookmark.pageid})">
                            <i class="fas fa-external-link-alt"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="explorer.removeBookmark(${bookmark.pageid})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `).join('');
        }
        
        this.bookmarksModal.show();
    }

    showHistoryModal() {
        const historyList = document.getElementById('historyList');
        
        if (this.history.length === 0) {
            historyList.innerHTML = '<p class="text-muted text-center">No reading history yet. Start exploring Wikipedia articles!</p>';
        } else {
            historyList.innerHTML = this.history.map(item => `
                <div class="d-flex justify-content-between align-items-center p-2 border-bottom">
                    <div class="flex-grow-1">
                        <h6 class="mb-1">${this.escapeHtml(item.term)}</h6>
                        <small class="text-muted">${new Date(item.timestamp).toLocaleString()}</small>
                    </div>
                    <button class="btn btn-sm btn-outline-primary" onclick="explorer.searchFromHistory('${this.escapeHtml(item.term)}')">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            `).join('');
        }
        
        this.historyModal.show();
    }

    showSettingsModal() {
        // Load current settings
        document.getElementById('defaultLanguage').value = this.settings.language || 'en';
        document.getElementById('resultsPerPage').value = this.settings.resultsPerPage || '20';
        document.getElementById('autoSaveBookmarks').checked = this.settings.autoSaveBookmarks !== false;
        document.getElementById('enableNotifications').checked = this.settings.enableNotifications || false;
        
        this.settingsModal.show();
    }

    showArticleFromBookmark(pageId) {
        const bookmark = this.bookmarks.find(b => b.pageid === pageId);
        if (bookmark) {
            this.bookmarksModal.hide();
            this.showArticle(bookmark);
        }
    }

    removeBookmark(pageId) {
        this.bookmarks = this.bookmarks.filter(b => b.pageid !== pageId);
        this.saveBookmarks();
        this.showBookmarksModal(); // Refresh modal
        this.showNotification('Bookmark removed', 'info');
    }

    searchFromHistory(term) {
        this.historyModal.hide();
        document.getElementById('searchInput').value = term;
        this.handleSearch();
    }

    // Export functionality
    exportResults() {
        if (this.currentResults.length === 0) return;
        
        const data = {
            search: this.currentSearch,
            timestamp: new Date().toISOString(),
            results: this.currentResults.map(result => ({
                title: result.title,
                extract: result.extract,
                url: result.url,
                pageid: result.pageid
            }))
        };
        
        this.downloadJSON(data, `wikipedia-search-${Date.now()}.json`);
        this.showNotification('Results exported successfully', 'success');
        this.trackEvent('export_results', this.currentSearch);
    }

    exportBookmarks() {
        if (this.bookmarks.length === 0) return;
        
        const data = {
            exportDate: new Date().toISOString(),
            bookmarks: this.bookmarks
        };
        
        this.downloadJSON(data, `wikipedia-bookmarks-${Date.now()}.json`);
        this.showNotification('Bookmarks exported successfully', 'success');
        this.trackEvent('export_bookmarks', this.bookmarks.length);
    }

    exportHistory() {
        if (this.history.length === 0) return;
        
        const data = {
            exportDate: new Date().toISOString(),
            history: this.history
        };
        
        this.downloadJSON(data, `wikipedia-history-${Date.now()}.json`);
        this.showNotification('History exported successfully', 'success');
        this.trackEvent('export_history', this.history.length);
    }

    downloadJSON(data, filename) {
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // Share functionality
    shareApp() {
        if (navigator.share) {
            navigator.share({
                title: 'Wikipedia Explorer - Advanced Educational Tool',
                text: 'Search and explore Wikipedia articles with AI-powered search and features',
                url: window.location.href
            }).catch(err => console.log('Share error:', err));
        } else {
            // Fallback: copy to clipboard
            this.copyToClipboard(window.location.href);
            this.showNotification('Link copied to clipboard', 'success');
        }
        this.trackEvent('share_app');
    }

    shareArticle() {
        if (!this.currentArticle) return;
        
        const shareData = {
            title: this.currentArticle.title,
            text: `Check out this Wikipedia article: ${this.currentArticle.title}`,
            url: this.currentArticle.url
        };
        
        if (navigator.share) {
            navigator.share(shareData).catch(err => console.log('Share error:', err));
        } else {
            this.copyToClipboard(this.currentArticle.url);
            this.showNotification('Article link copied to clipboard', 'success');
        }
        this.trackEvent('share_article', this.currentArticle.title);
    }

    copyToClipboard(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }

    // Quick actions
    translateArticle() {
        if (!this.currentArticle) return;
        
        // Open Google Translate with article URL
        const translateUrl = `https://translate.google.com/translate?sl=en&tl=es&u=${encodeURIComponent(this.currentArticle.url)}`;
        window.open(translateUrl, '_blank');
        this.trackEvent('translate_article', this.currentArticle.title);
    }

    generateCitation() {
        if (!this.currentArticle) return;
        
        const citation = this.generateCitationFormat(this.currentArticle);
        this.copyToClipboard(citation);
        this.showNotification('Citation copied to clipboard', 'success');
        this.trackEvent('generate_citation', this.currentArticle.title);
    }

    generateCitationFormat(article) {
        const date = new Date().toLocaleDateString();
        const authors = 'Wikipedia Contributors';
        
        return `${authors}. (${date}). "${article.title}". In *Wikipedia*. Retrieved ${date}, from ${article.url}`;
    }

    generateSummary() {
        if (!this.currentArticle) return;
        
        // Simple summary: first few sentences
        const content = this.currentArticle.content;
        if (!content) return;
        
        const sentences = content.split('.').filter(s => s.trim().length > 0);
        const summary = sentences.slice(0, 3).join('.') + '.';
        
        this.showNotification('Summary: ' + summary, 'info', 10000);
        this.trackEvent('generate_summary', this.currentArticle.title);
    }

    printArticle() {
        if (!this.currentArticle) return;
        
        window.print();
        this.trackEvent('print_article', this.currentArticle.title);
    }

    // Info pages
    showAbout() {
        const aboutContent = `
            <h3>About Wikipedia Explorer</h3>
            <p>Wikipedia Explorer is an advanced educational tool developed by RSK World to help students, teachers, and researchers explore Wikipedia articles with enhanced features.</p>
            <h5>Features:</h5>
            <ul>
                <li>AI-powered search with suggestions</li>
                <li>Advanced filtering and sorting</li>
                <li>Bookmarking and reading history</li>
                <li>Text-to-speech functionality</li>
                <li>Dark mode support</li>
                <li>Export and sharing options</li>
                <li>Mobile-responsive design</li>
            </ul>
            <p><strong>Developed by RSK World</strong><br>
            Founder: Molla Samser<br>
            Designer & Tester: Rima Khatun<br>
            © 2026 RSK World. All rights reserved.</p>
        `;
        this.showModal('About Wikipedia Explorer', aboutContent);
    }

    showFeatures() {
        const featuresContent = `
            <h3>Features</h3>
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="fas fa-search text-primary me-2"></i>Advanced Search</h5>
                    <p>AI-powered search with real-time suggestions and advanced filtering options.</p>
                    
                    <h5><i class="fas fa-bookmark text-warning me-2"></i>Bookmarks</h5>
                    <p>Save your favorite articles for easy access later.</p>
                    
                    <h5><i class="fas fa-history text-info me-2"></i>Reading History</h5>
                    <p>Track your search history and recently viewed articles.</p>
                </div>
                <div class="col-md-6">
                    <h5><i class="fas fa-volume-up text-success me-2"></i>Text-to-Speech</h5>
                    <p>Listen to articles with our built-in text-to-speech feature.</p>
                    
                    <h5><i class="fas fa-moon text-secondary me-2"></i>Dark Mode</h5>
                    <p>Comfortable reading experience with dark theme support.</p>
                    
                    <h5><i class="fas fa-share-alt text-danger me-2"></i>Share & Export</h5>
                    <p>Share articles and export your bookmarks and history.</p>
                </div>
            </div>
        `;
        this.showModal('Features', featuresContent);
    }

    showHelp() {
        const helpContent = `
            <h3>Help & Support</h3>
            <h5>Keyboard Shortcuts</h5>
            <ul>
                <li><kbd>Ctrl/Cmd + K</kbd> - Focus search box</li>
                <li><kbd>Ctrl/Cmd + P</kbd> - Print current article</li>
                <li><kbd>Esc</kbd> - Close modals</li>
            </ul>
            
            <h5>How to Use</h5>
            <ol>
                <li>Enter your search query in the search box</li>
                <li>Use advanced filters to narrow down results</li>
                <li>Click on any result to view the full article</li>
                <li>Use the toolbar buttons for additional features</li>
                <li>Bookmark articles for later reference</li>
            </ol>
            
            <h5>Contact Support</h5>
            <p>Email: <a href="mailto:support@rskworld.in">support@rskworld.in</a><br>
            Phone: <a href="tel:+919330539277">+91 93305 39277</a></p>
        `;
        this.showModal('Help & Support', helpContent);
    }

    showPrivacy() {
        const privacyContent = `
            <h3>Privacy Policy</h3>
            <p><strong>Last Updated:</strong> March 8, 2026</p>
            
            <h5>Data Collection</h5>
            <p>Wikipedia Explorer respects your privacy. We only collect:</p>
            <ul>
                <li>Search queries (stored locally in your browser)</li>
                <li>Bookmarks and reading history (stored locally)</li>
                <li>Application settings and preferences</li>
            </ul>
            
            <h5>Data Usage</h5>
            <p>All data is stored locally in your browser and is never transmitted to our servers, except for:</p>
            <ul>
                <li>Anonymous usage analytics for improving the service</li>
                <li>Error reporting for troubleshooting</li>
            </ul>
            
            <h5>Third-Party Services</h5>
            <p>This application uses Wikipedia's public API to fetch article content. We do not share your personal information with third parties.</p>
            
            <h5>Contact</h5>
            <p>For privacy-related questions, contact us at: <a href="mailto:privacy@rskworld.in">privacy@rskworld.in</a></p>
        `;
        this.showModal('Privacy Policy', privacyContent);
    }

    showModal(title, content) {
        const modalHtml = `
            <div class="modal fade" id="infoModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            ${content}
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing modal if present
        const existingModal = document.getElementById('infoModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // Add new modal to body
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('infoModal'));
        modal.show();
        
        // Remove modal from DOM after hidden
        document.getElementById('infoModal').addEventListener('hidden.bs.modal', function() {
            this.remove();
        });
    }

    // Storage functions
    loadBookmarks() {
        try {
            return JSON.parse(localStorage.getItem('wikipedia-explorer-bookmarks') || '[]');
        } catch (e) {
            console.error('Error loading bookmarks:', e);
            return [];
        }
    }

    saveBookmarks() {
        try {
            localStorage.setItem('wikipedia-explorer-bookmarks', JSON.stringify(this.bookmarks));
        } catch (e) {
            console.error('Error saving bookmarks:', e);
            this.showNotification('Failed to save bookmarks', 'error');
        }
    }

    loadHistory() {
        try {
            return JSON.parse(localStorage.getItem('wikipedia-explorer-history') || '[]');
        } catch (e) {
            console.error('Error loading history:', e);
            return [];
        }
    }

    saveHistory() {
        try {
            localStorage.setItem('wikipedia-explorer-history', JSON.stringify(this.history));
        } catch (e) {
            console.error('Error saving history:', e);
        }
    }

    loadSettings() {
        try {
            return JSON.parse(localStorage.getItem('wikipedia-explorer-settings') || '{}');
        } catch (e) {
            console.error('Error loading settings:', e);
            return {};
        }
    }

    saveSettings() {
        try {
            this.settings = {
                theme: this.currentTheme,
                fontSize: this.fontSize,
                language: document.getElementById('defaultLanguage')?.value || 'en',
                resultsPerPage: document.getElementById('resultsPerPage')?.value || '20',
                autoSaveBookmarks: document.getElementById('autoSaveBookmarks')?.checked !== false,
                enableNotifications: document.getElementById('enableNotifications')?.checked || false
            };
            
            localStorage.setItem('wikipedia-explorer-settings', JSON.stringify(this.settings));
            this.showNotification('Settings saved successfully', 'success');
            this.trackEvent('settings_saved');
        } catch (e) {
            console.error('Error saving settings:', e);
            this.showNotification('Failed to save settings', 'error');
        }
    }

    clearBookmarks() {
        if (confirm('Are you sure you want to clear all bookmarks? This action cannot be undone.')) {
            this.bookmarks = [];
            this.saveBookmarks();
            this.showBookmarksModal(); // Refresh modal
            this.showNotification('All bookmarks cleared', 'info');
            this.trackEvent('clear_bookmarks');
        }
    }

    clearHistory() {
        if (confirm('Are you sure you want to clear all history? This action cannot be undone.')) {
            this.history = [];
            this.saveHistory();
            this.showHistoryModal(); // Refresh modal
            this.showNotification('History cleared', 'info');
            this.trackEvent('clear_history');
        }
    }

    // UI helper functions
    showLoading() {
        document.getElementById('loadingIndicator').classList.remove('d-none');
    }

    hideLoading() {
        document.getElementById('loadingIndicator').classList.add('d-none');
    }

    showResults() {
        document.getElementById('resultsSection').classList.remove('d-none');
        document.getElementById('articleSection').classList.add('d-none');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    showArticleView() {
        document.getElementById('resultsSection').classList.add('d-none');
        document.getElementById('articleSection').classList.remove('d-none');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    showError(message) {
        this.showNotification(message, 'error');
    }

    showNotification(message, type = 'info', duration = 5000) {
        const alertClass = {
            'success': 'alert-success',
            'error': 'alert-danger',
            'warning': 'alert-warning',
            'info': 'alert-info'
        }[type] || 'alert-info';

        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3" style="z-index: 9999;" role="alert">
                <i class="fas fa-${type === 'error' ? 'exclamation-triangle' : type === 'success' ? 'check-circle' : 'info-circle'} me-2"></i>
                ${this.escapeHtml(message)}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        // Remove existing notifications
        document.querySelectorAll('.alert.position-fixed').forEach(alert => alert.remove());
        
        // Add new notification
        document.body.insertAdjacentHTML('beforeend', alertHtml);
        
        // Auto-remove after duration
        setTimeout(() => {
            const alert = document.querySelector('.alert.position-fixed');
            if (alert) {
                alert.remove();
            }
        }, duration);
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 bytes';
        const k = 1024;
        const sizes = ['bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Analytics functions
    trackPageView() {
        if (typeof gtag !== 'undefined') {
            gtag('config', 'GA_MEASUREMENT_ID', {
                page_title: 'Wikipedia Explorer',
                page_location: window.location.href
            });
        }
    }

    trackEvent(action, label = null, value = null) {
        if (typeof gtag !== 'undefined') {
            gtag('event', action, {
                'event_label': label,
                'value': value
            });
        }
        
        // Also log to console for debugging
        console.log('Analytics Event:', action, label, value);
    }

    setupSearchSuggestions() {
        // Setup is handled in handleSearchSuggestions method
    }
}

// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.explorer = new WikipediaExplorer();
});

// Add some utility functions
window.WikipediaExplorer = {
    // Global utility for external access if needed
    formatText: (text) => {
        return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
    },
    
    // Analytics placeholder (could be integrated with Google Analytics, etc.)
    trackEvent: (action, label) => {
        console.log('Analytics Event:', action, label);
        // In a real implementation, this would send data to analytics service
    }
};
