document.addEventListener('DOMContentLoaded', function() {

    document.addEventListener('contextmenu', function(e) {
        e.preventDefault();
        return false;
    });

    document.addEventListener('keydown', function(e) {
        if (e.keyCode === 123 || 
            (e.ctrlKey && e.shiftKey && e.keyCode === 73) || 
            (e.ctrlKey && e.shiftKey && e.keyCode === 74) || 
            (e.ctrlKey && e.keyCode === 85)) { 
            e.preventDefault();
            return false;
        }
    });

    initExtension();
    
    function initExtension() {
        if (!localStorage.getItem('2059_theme')) {
            localStorage.setItem('2059_theme', 'light');
        }
        const savedTheme = localStorage.getItem('2059_theme');
        document.documentElement.setAttribute('data-theme', savedTheme);
        updateThemeIcon(savedTheme);
        
        initAccuratePersianDateTime();
        

        const searchInput = document.getElementById('searchInput');
        

        setTimeout(() => {
            searchInput.focus();
        }, 300);

        setupEventListeners();

        setupPlaceholderSuggestions();

        setupFeatureCards();
    }
    
    function initAccuratePersianDateTime() {

        function gregorianToJalali(gy, gm, gd) {

            let jy, jm, jd;
            let g_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            let j_days_in_month = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];

            if ((gy % 4 === 0 && gy % 100 !== 0) || gy % 400 === 0) {
                g_days_in_month[1] = 29;
            }

            let gy2 = gy - 621;
            let g_days = 0;

            for (let i = 0; i < gy2 - 1; i++) {
                g_days += 365;
                if ((i % 4 === 0 && i % 100 !== 0) || i % 400 === 0) {
                    g_days++;
                }
            }

            for (let i = 0; i < gm - 1; i++) {
                g_days += g_days_in_month[i];
            }
            
            g_days += gd;

            let j_days = g_days - 79; 
            jy = 1;

            while (j_days > 365) {
     
                if (isJalaliLeapYear(jy)) {
                    if (j_days > 366) {
                        j_days -= 366;
                        jy++;
                    } else {
                        break;
                    }
                } else {
                    j_days -= 365;
                    jy++;
                }
            }

            jm = 1;
            while (j_days > j_days_in_month[jm - 1]) {

                if (jm === 12 && isJalaliLeapYear(jy)) {
                    if (j_days > 30) {
                        j_days -= 30;
                        jm++;
                    } else {
                        break;
                    }
                } else {
                    j_days -= j_days_in_month[jm - 1];
                    jm++;
                }
            }
            
            jd = j_days;
            return [jy, jm, jd];
        }
        

        function isJalaliLeapYear(jy) {

            const leapYears = [1, 5, 9, 13, 17, 22, 26, 30];
            const pattern = jy % 33;
            return leapYears.includes(pattern);
        }
        

        const persianMonths = [
            'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور',
            'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
        ];
        

        const persianDays = [
            'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 
            'پنجشنبه', 'جمعه', 'شنبه'
        ];

        function toPersianDigits(number) {
            const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
            return number.toString().replace(/\d/g, function(digit) {
                return persianDigits[digit];
            });
        }

        function getPersianDayOfWeek(gregorianDate) {
            const day = gregorianDate.getDay();
            return persianDays[day];
        }

        function updateDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const day = now.getDate();
            const hour = now.getHours();
            const minute = now.getMinutes();
            const second = now.getSeconds();

            const [persianYear, persianMonth, persianDay] = gregorianToJalali(year, month, day);

            const persianDayName = getPersianDayOfWeek(now);

            const monthName = persianMonths[persianMonth - 1];

            const yearDigits = toPersianDigits(persianYear);

            const hours = toPersianDigits(hour.toString().padStart(2, '0'));
            const minutes = toPersianDigits(minute.toString().padStart(2, '0'));
            const seconds = toPersianDigits(second.toString().padStart(2, '0'));

            document.getElementById('dateDisplay').textContent = 
                `${persianDayName} ${toPersianDigits(persianDay)} ${monthName} ${yearDigits}`;

            document.getElementById('timeDisplay').textContent = 
                `${hours}:${minutes}:${seconds}`;

            console.log(`📅 تاریخ میلادی: ${year}-${month}-${day}`);
            console.log(`📅 تاریخ شمسی: ${persianYear}-${persianMonth}-${persianDay}`);
            console.log(`📅 نمایش: ${persianDayName} ${persianDay} ${monthName} ${persianYear}`);
        }
        

        updateDateTime();
        setInterval(updateDateTime, 1000);
    }
    
    function setupEventListeners() {
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const clearBtn = document.getElementById('clearBtn');
        const themeBtn = document.getElementById('themeBtn');
        const loginBtn = document.getElementById('loginBtn');
        const quickLinks = document.querySelectorAll('.link-btn');
        

        searchBtn.addEventListener('click', performSearch);
        

        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        

        clearBtn.addEventListener('click', function() {
            searchInput.value = '';
            searchInput.focus();
            this.style.opacity = '0';
            this.style.visibility = 'hidden';
        });
        

        searchInput.addEventListener('input', function() {
            const hasValue = searchInput.value.trim().length > 0;
            clearBtn.style.opacity = hasValue ? '1' : '0';
            clearBtn.style.visibility = hasValue ? 'visible' : 'hidden';
        });

        themeBtn.addEventListener('click', toggleTheme);

        loginBtn.addEventListener('click', function() {
            window.open('https://2059.ir/p/login.php', '_blank');
        });

        quickLinks.forEach(btn => {
            btn.addEventListener('click', function(e) {
                const query = this.getAttribute('data-query');
                searchInput.value = query;
                performSearch();
            });
        });

        searchInput.addEventListener('focus', function() {
            this.parentElement.style.borderColor = 'var(--primary)';
            this.parentElement.style.boxShadow = '0 0 0 3px rgba(79, 70, 229, 0.15)';
        });
        
        searchInput.addEventListener('blur', function() {
            this.parentElement.style.borderColor = 'transparent';
            this.parentElement.style.boxShadow = 'none';
        });
    }
    
    function setupPlaceholderSuggestions() {
        const searchInput = document.getElementById('searchInput');
        const suggestions = [
			'جستجو در سراسر وب',
            'آخرین اخبار ایران',
            'قیمت دلار و ارز',
            'آب و هوای شهرها',
            'فیلم و سریال جدید',
            'خرید اینترنتی',
            'آموزش برنامه نویسی',
            'نتایج ورزشی',
            'فال حافظ امروز'
        ];
        
        let currentIndex = 0;
        
        function updatePlaceholder() {
            searchInput.placeholder = ` ${suggestions[currentIndex]}...`;
            currentIndex = (currentIndex + 1) % suggestions.length;
        }
        
        updatePlaceholder();
        setInterval(updatePlaceholder, 4000);
    }
    
    function setupFeatureCards() {
        document.querySelectorAll('.feature-card').forEach((card, index) => {
            card.style.setProperty('--delay', `${index * 0.05}s`);
            
            // Add hover effect
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-4px) scale(1.03)';
            });
            
            card.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0) scale(1)';
            });
        });
    }
    
    function performSearch() {
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const query = searchInput.value.trim();
        
        if (!query) {
            searchInput.focus();
            return;
        }

        const originalText = searchBtn.innerHTML;
        searchBtn.innerHTML = '<span>در حال جستجو...</span>';
        searchBtn.disabled = true;

        saveToHistory(query);

        setTimeout(() => {
            const encodedQuery = encodeURIComponent(query);
            window.open(`https://2059.ir/index.php?q=${encodedQuery}&type=all`, '_blank');
            

            searchBtn.innerHTML = originalText;
            searchBtn.disabled = false;
        }, 300);
    }
    
    function toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('2059_theme', newTheme);
        updateThemeIcon(newTheme);
    }
    
    function updateThemeIcon(theme) {
        const themeIcon = document.getElementById('themeIcon');
        themeIcon.textContent = theme === 'dark' ? '☀️' : '🌙';
        themeBtn.title = theme === 'dark' ? 'تم روشن' : 'تم تاریک';
    }
    
    function saveToHistory(query) {
        try {
            let history = JSON.parse(localStorage.getItem('2059_search_history') || '[]');
            

            history = history.filter(item => item !== query);
            

            history.unshift(query);
            if (history.length > 10) {
                history = history.slice(0, 10);
            }
            
            localStorage.setItem('2059_search_history', JSON.stringify(history));
        } catch (e) {
        }
    }
    
    console.log('2059');
});