<!DOCTYPE html>
<html lang="ru">
<head>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Бутик</title>
    <style>

    @media screen and (max-width: 768px) {
        nav {
            position: sticky;
            z-index: 1000;
            transition: transform 0.3s ease-in-out;
        }

        .nav-container {
            display: flex;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        }

        .nav-links {
            display: flex;
            gap: 1rem;
            flex-wrap: nowrap;
            white-space: nowrap;
        }

        .nav-links::-webkit-scrollbar {
            display: none;
        }
        
        .nav-links.active {
            display: flex;
        }
    }

    .news-section {
        padding: 1rem;
        margin-top: 1rem;
        font-size: 0.9rem;
    }

    .news-list {
        gap: 1rem;
    }

    .news-card {
        padding: 1rem;
        font-size: 1rem;
    }

    .news-card h3 { 
        font-size: 1.2rem;
    }
    
    @media (hover: none) and (pointer: coarse) {
        .nav-links button, 
        .main-button, 
        .product-button {
            min-height: 44px;
            min-width: 44px;
        }
    }

    body {
        -webkit-text-size-adjust: 100%;
        overflow: auto;
        overscroll-behavior-y: auto;
        -ms-text-size-adjust: 100%;
        text-size-adjust: 100%;
        overscroll-behavior-y: none;
    }

    * {
        -webkit-tap-highlight-color: transparent;
        tap-highlight-color: transparent;
    }

    input, textarea, button {
        -webkit-appearance: none;
        appearance: none;
    }

        :root {
        --bg-dark: #121620;                 /* Немного темнее для большей глубины */
        --bg-dark-secondary: #1f2937;        /* Более мягкий темно-синий оттенок */
        --text-light: #f0f4ff;               /* Слегка холодный белый для лучшей читаемости */
        --accent-purple: #3b82f6;            /* Более насыщенный синий для акцента */
        --accent-light-purple: #38bdf8;      /* Более яркий голубой */
        --accent-green: #56d9fa;             /* Более изумрудный зеленый */
        }

        html { scrollbar-gutter: stable; }

        body {
        background-color: var(--bg-dark);
        color: var(--text-light);
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        overflow: hidden scroll;
        transition: background-color 0.3s, color 0.3s;
        }

        /* Анимации */
        .fade-out {
            animation: fadeOut 0.3s ease forwards;
        }

        .fade-in {
            animation: fadeIn 0.5s ease forwards;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes fadeOut {
            from { opacity: 1; transform: scale(1); }
            to { opacity: 0; transform: scale(0.9); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.9); }
            to { opacity: 1; transform: scale(1); }
        }

        @keyframes slideInFromRight {
            from { opacity: 0; transform: translateX(50px); }
            to { opacity: 1; transform: translateX(0); }
        }

        @keyframes fadeIn { 
        from { opacity: 0; } 
        to { opacity: 1; } 
        }

        @keyframes fadeInUp {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
        }

        @keyframes zoomIn {
        from { opacity: 0; transform: scale(0.8); }
        to { opacity: 1; transform: scale(1); }
        }

        @keyframes fadeInZoom {
        from { opacity: 0; transform: scale(0.8); }
        to { opacity: 1; transform: scale(1); }
        }

        @keyframes slideDown {
        from { transform: translateY(-100%); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
        }

        @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
        }

        /* Состояния отображения */
        .hidden { display: none; opacity: 0; animation: none; }
        .visible { 
        display: block; 
        animation: fadeInUp 1s ease-out; 
        }
        .products.visible {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        }
        .contact.visible { animation: fadeIn 2s ease-in-out; }

        /* Навигация */
        nav {
        background-color: rgba(39, 39, 39, 0.5);
        backdrop-filter: blur(10px);
        box-shadow: 0 4px 15px rgba(0, 89, 255, 0.5);
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 1000;
        animation: slideDown 1s ease-in-out;
        transition: all 0.3s;
        }

        .nav-container {
        max-width: 1200px;
        margin: 0 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 1.5rem;
            font-weight: bold;
        }
        
        .logo span { 
            color: var(--accent-purple); 
            margin-left: 8px; 
        }
        
        .logo img {
            width: 32px;
            height: 32px;
            color: #008cff;
        }

        .nav-links {
        display: flex;
        justify-content: center;
        gap: 2rem;
        }

        .nav-links button {
        position: relative;
        background: transparent;
        border: none;
        font-size: 1rem;
        color: var(--text-light);
        cursor: pointer;
        transition: color 0.3s;
        }

        .nav-links button::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: 0;
        width: 100%;
        height: 2px;
        background: linear-gradient(90deg, 
            var(--accent-purple), 
            var(--accent-light-purple), 
            var(--accent-green), 
            var(--accent-purple)
        );
        background-size: 400% 100%;
        transition: all 0.3s ease;
        opacity: 0;
        box-shadow: 0 0 10px var(--accent-light-purple);
        transform: scaleX(0.7);
        }

        .nav-links button:hover::after {
            opacity: 1;
            height: 3px;
            transform: scaleX(1);
            box-shadow: 0 0 15px var(--accent-purple);
        }

        /* Основные элементы */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 8px;
            color: white;
            animation: slideIn 0.3s ease;
        }

        .notification.success {
            background: linear-gradient(145deg, #4CAF50, #45a049);
        }

        .notification.error {
            background: linear-gradient(145deg, #f44336, #e53935);
        }

        .main {
        transition: background-color 0.3s;
        padding: 6rem 2rem 2rem;
        max-width: 1200px;
        margin: 0 auto;
        animation: fadeInUp 1s ease;
        }

        header {
        text-align: center;
        background: linear-gradient(135deg, var(--accent-light-purple), rgba(56, 189, 248, 0.3));
        padding: 3rem 1rem;
        border-radius: 10px;
        margin-bottom: 2rem;
        animation: zoomIn 1s ease-in-out;
        }

        header h1 { animation: fadeInZoom 2s ease-in-out; }
        header p { 
        font-size: 1.2rem; 
        color: #e2e8f0; 
        }

        /* Кнопки */
        .main-button, .product-button {
        background-color: var(--accent-purple);
        color: white;
        border: none;
        padding: 1rem 2rem;
        border-radius: 9999px;
        cursor: pointer;
        transition: all 0.3s;
        }

        .main-button:hover, .product-button:hover {
        transform: scale(1.1);
        background-color: #3f82ff;
        box-shadow: 0 0 10px var(--accent-light-purple), 0 0 20px var(--accent-purple);
        }

        .product-button:hover {
        box-shadow: 0 0 20px var(--accent-light-purple);
        animation: pulse 1.5s infinite;
        }

        /* Additional styles for news section */
        
        .news-section {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
            background-color: var(--bg-dark-secondary);
            padding: 2rem;
            border-radius: 10px;
            margin-top: 2rem;
        }

        .news-section.expanded {
            padding-bottom: 3rem;
        }

        .news-list {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .news-card {
            position: relative;
            padding: 1rem;
            margin-bottom: 1rem;
            background-color: var(--bg-dark);
            border-radius: 10px;
            padding: 1.5rem;
            transition: transform 0.3s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .news-card:hover {
            transform: translateY(-5px);
        }
        .news-card h4 {
            margin-top: 1.5rem;
            margin-bottom: 1rem;
            color: var(--text-primary);
        }

        .news-card p {
            margin-bottom: 1rem;
            line-height: 1.6;
            color: var(--text-secondary);
        }
        

        .news-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .read-more {
            display: inline-block;
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
            margin-top: 1rem;
        }

        .read-more:hover {
            text-decoration: underline;
        }

        .original-text {
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        details summary {
            cursor: pointer;
            color: var(--accent);
            margin-bottom: 1rem;
        }

        details summary:hover {
            text-decoration: underline;
        }

        .date {
            position: relative;
            display: inline-block;
            top: 0;
            right: 0;
            color: var(--text-secondary);
            background-color: var(--bg-dark-secondary);
            padding: 0.5rem 1rem;
            border-radius: 5px;
            margin-bottom: 1rem;
        }


        .crypto-widget {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: var(--bg-dark-secondary);
            padding: 1rem;
            border-radius: 10px;
            margin-top: 1rem;
        }

        .crypto-price {
            font-weight: bold;
            color: var(--accent-green);
        }

        /* Продукты */

        .products-container {
            display: flex;
            max-width: 1200px;
            margin: 0 auto;
            gap: 2rem;
            position: relative;
            top: 5rem;
        }

        .sorting-panel {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
            width: 250px;
            background-color: var(--bg-dark-secondary);
            padding: 1rem;
            border-radius: 10px;
            height: fit-content;
        }

        .sorting-panel h4 {
            margin-bottom: 1rem;
            color: var(--accent-light-purple);
        }

        .sorting-panel select {
            width: 100%;
            padding: 0.5rem;
            background-color: var(--bg-dark);
            color: var(--text-light);
            border: 1px solid var(--accent-purple);
            border-radius: 5px;
        }

        .products-grid {
            animation: slideInFromRight 0.5s ease forwards;
            opacity: 0;
            flex-grow: 1;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
        }

        .product-compact {
            animation: slideInFromRight 0.5s ease forwards;
            opacity: 0;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: var(--bg-dark-secondary);
            padding: 1rem;
            border-radius: 10px;
            text-align: center;
            transition: transform 0.3s;
        }

        .pagination-button {
            transition: all 0.3s ease;
            animation: fadeInUp 0.5s ease;
        }

        .pagination-button:hover {
            transform: scale(1.1);
        }

        .product-compact:hover {
            transform: scale(1.05);
        }

        .product-compact i {
            font-size: 3rem;
            color: var(--accent-purple);
            margin-bottom: 0.5rem;
        }

        .product-compact h5 {
            margin: 0.5rem 0;
            color: var(--accent-light-purple);
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 2rem;
            gap: 0.5rem;
            position: relative;
            top: 22rem; /* Смещение пагинации */
        }

        .pagination button {
            background-color: var(--bg-dark-secondary);
            border: 1px solid var(--accent-purple);
            color: var(--text-light);
            padding: 0.5rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .pagination button:hover, 
        .pagination button.active {
            background-color: var(--accent-purple);
            color: white;
        }

        #products {
            margin-top: 0;  
            position: relative;
            top: 0;
        }
                                             
        /* Формы */

        /* Стили для уведомлений */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            animation: slideIn 0.3s ease-out;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .notification.success {
            background-color: #4CAF50;
        }

        .notification.error {
            background-color: #f44336;
        }

        .notification.loading {
            background-color: #2196F3;
        }

        .notification.fade-out {
            animation: fadeOut 0.3s ease-out forwards;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes fadeOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }


        h3 {
            text-align: center;
            position: static;
            margin-top: 2rem;
            margin-bottom: 2rem;
        }

        .contact-form {
            max-width: 600px;
            margin: 2rem auto;
            animation: fadeIn 2s ease-in-out;
            background-color: var(--bg-dark-secondary);
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
        }

        .contact-form input,
        .contact-form textarea {
            width: 94%;
            padding: 1rem;
            margin: 1rem 0;
            background-color: var(--bg-dark-secondary);
            border: 1px solid #4a5568;
            color: var(--text-primary);
            border-radius: 5px;
            transition: border-color 0.3s;
            resize: vertical;
            max-height: 200px;
            font-family: inherit;
        }

        .contact-form input:focus,
        .contact-form textarea:focus {
            border-color: var(--accent-purple);
            outline: none;
            box-shadow: 0 0 5px var(--accent-light-purple);
        }

        /* Футер */
        footer {
            position: fixed;
            bottom: 0;
            width: 100%;
            background-color: rgba(39, 39, 39, 0.5);
            box-shadow: 0 4px 15px rgba(0, 89, 255, 0.5);
            backdrop-filter: blur(10px);
            text-align: center;
            padding: 1rem;
            color: #fff;
            font-size: 1rem;
            z-index: 9999;
        }

        p2 { 
            font-size: 1rem; 
            color: var(--text-light); 
        }

        /* Переключатель темы и языка */
        .theme-language-switcher {
        display: flex;
        gap: 1rem;
        }

        .theme-language-switcher button {
        background: var(--bg-dark-secondary);
        color: var(--text-light);
        border: 1px solid var(--accent-purple);
        padding: 0.5rem 1rem;
        border-radius: 8px;
        cursor: pointer;
        transition: background 0.3s, color 0.3s;
        }

        .theme-language-switcher button:hover {
        background: var(--accent-purple);
        color: white;
        }

        /* AI-секция */
        .ai-section {
        background: linear-gradient(to bottom right, var(--accent-light-purple), var(--accent-green));
        padding: 3rem;
        text-align: center;
        border-radius: 12px;
        color: white;
        margin: 2rem auto 3rem;
        max-width: 800px;
        animation: fadeInUp 1.5s ease-in-out;
        }

        .ai-section h1 { animation: fadeInZoom 2s ease-in-out; }

        .ai-section p { 
        font-size: 1.2rem; 
        color: #e2e8f0; 
        }

        .ai-section .cta-button {
        background-color: var(--accent-purple);
        color: white;
        border: none;
        padding: 1rem 2rem;
        border-radius: 999px;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 0 10px var(--accent-light-purple);
        animation: fadeInUp 1.5s ease forwards;
        animation-delay: 1s;
        }

        .ai-section .cta-button:hover {
        transform: scale(1.05);
        background-color: var(--accent-green);
        }
    </style>
</head>
<body>
    <nav>
        <div class="nav-container">
            <div class="logo">
            <img src="robot-icon.png" alt="Robot Icon">
                <span>AI Бутик</span>
            </div>
            <div class="nav-links">
                <button id="home-btn" class="active">Главная</button>
                <button id="products-btn">Продукты</button>
                <button id="news-btn">Новости</button>
                <button id="contacts-btn">Контакты</button>
            </div>
            <div class="theme-language-switcher">
                <button id="theme-btn"><i id="theme-icon" class="fas fa-moon"></i></button>
            </div>          
        </div>
    </nav>

    <div id="main" class="main">
        <header>
            <h1>AI Бутик: Интеллект для Вашего Бизнеса</h1>
            <p>Передовые нейросетевые решения, которые преображают ваш бизнес</p>
            <button class="main-button">Получить консультацию</button>
        </header>
        <div id="ai-possibilities" class="ai-section">
            <h1>Возможности искусственного интеллекта</h1>
            <p>Наши интеллектуальные решения помогают автоматизировать процессы, анализировать данные и достигать новых высот в вашем бизнесе.</p>
            <button class="main-button">Узнать больше</button>
        </div>        
    </div>

    <div id="products" class="hidden">
            <div class="products-container">
                <div class="sorting-panel">
                    <h4>Сортировка</h4>
                    <select id="sort-select">
                        <option value="price-asc">Цена: по возрастанию</option>
                        <option value="price-desc">Цена: по убыванию</option>
                        <option value="name-asc">Название: А-Я</option>
                        <option value="name-desc">Название: Я-А</option>
                    </select>
                </div>
                <div class="products-grid" id="products-grid"></div>
            </div>
            <div class="pagination" id="pagination"></div>
        </div>

        <div id="contacts" class="contact hidden">
            <h3 style="text-align: center; margin-top: 14rem;">Свяжитесь с нами</h3>
            <form class="contact-form" action="send-mail.php" method="POST">
                <input type="text" name="name" placeholder="Ваше имя" required>
                <input type="email" name="email" placeholder="Email" required>
                <textarea name="message" placeholder="Ваше сообщение" required></textarea>
                <button type="submit" class="main-button" style="width: 100%;">Отправить</button>
            </form>
        </div>        

        <footer>
                <p2>© 2024 AI Бутик. Все права защищены.</p2>
        </footer>

    <div id="news" class="hidden">
        <div class="main">
            <h2 style="text-align: center; margin-bottom: 2rem;">Новости нейросетей и технологий</h2>
            
            <div class="crypto-widget">
                <span>Bitcoin (BTC)</span>
                <span id="btc-price" class="crypto-price">Загрузка...</span>
            </div>

            <section id="news" class="news-section">
                <h3>Новости</h3>
                <div id="news-container" class="news-list" style="margin: 1rem;">
                    Загрузка новостей...
                </div>
            </section>          
        </div>
    </div>

</body>
<script>

(function() {
    if (!window.fetch) {
        window.fetch = function(url) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                xhr.onload = () => resolve({
                    json: () => Promise.resolve(JSON.parse(xhr.responseText))
                });
                xhr.onerror = () => reject(new Error('Network error'));
                xhr.send();
            });
        };
    }

    if (!Element.prototype.addEventListener) {
        Element.prototype.addEventListener = function(event, callback) {
            this.attachEvent('on' + event, callback);
        };
    }

    function preventDefaultEvent(e) {
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
    }

    window.onerror = function(message, source, lineno, colno, error) {
        console.error('Глобальная ошибка:', {
            message, 
            source, 
            lineno, 
            colno, 
            error: error ? error.toString() : 'Unknown error'
        });
        return false;
    };
})();

console.log("Hello from neverpon4ik1213");

const Base64 = {
    encode: (str) => btoa(unescape(encodeURIComponent(str))),
    decode: (str) => decodeURIComponent(escape(atob(str)))
};

function obfuscateData(data, isEncoding = true) {
    return isEncoding 
        ? data.map(item => ({
            ...item,
            name: Base64.encode(item.name),
            description: Base64.encode(item.description),
            link: Base64.encode(item.link),
            price: item.price ^ 0xA5
        }))
        : data.map(item => ({
            ...item,
            name: Base64.decode(item.name),
            description: Base64.decode(item.description),
            link: Base64.decode(item.link),
            price: item.price ^ 0xA5
        }));
}

async function loadProductsFromFile() {
    try {
        const response = await fetch('products.json');
        let products = await response.json();
        
        products = obfuscateData(products);

        const productsGrid = document.getElementById('products-grid');
        const paginationContainer = document.getElementById('pagination');
        const itemsPerPage = 6;
        let currentPage = 1;

        function displayProducts(page) {
            productsGrid.classList.add('fade-out');
            
            setTimeout(() => {
                productsGrid.innerHTML = '';
                productsGrid.classList.remove('fade-out');
                productsGrid.classList.add('fade-in');

                const startIndex = (page - 1) * itemsPerPage;
                const endIndex = startIndex + itemsPerPage;
                const pageProducts = products.slice(startIndex, endIndex);

                pageProducts.forEach((product, index) => {
                    const productElement = document.createElement('div');
                    productElement.classList.add('product-compact');
                    productElement.style.animationDelay = `${index * 0.1}s`;
                    
                    const decodedProduct = obfuscateData([product], false)[0];

                    productElement.innerHTML = `
                        <div class="product-content">
                            <img src="${product.icon}" alt="${decodedProduct.name}" style="max-width: 100px; max-height: 100px;">
                            <h5>${decodedProduct.name}</h5>
                            <p class="product-description">${decodedProduct.description}</p>
                            <div class="product-footer">
                                <p class="product-price">Цена: ${decodedProduct.price} ₽</p>
                                <a href="#" class="product-button" u뚺w+ʛ^vX琀="${product.link}">Заказать</a>
                            </div>
                        </div>
                    `;
                    
                    const orderButton = productElement.querySelector('.product-button');
                    orderButton.addEventListener('click', async (event) => {
                        event.preventDefault();
                        const encryptedLink = orderButton.getAttribute('u뚺w+ʛ^vX琀');
                        const decodedLink = Base64.decode(encryptedLink);
                        
                        window.open(decodedLink, '_blank');
                    });
                    
                    productsGrid.appendChild(productElement);
                });

                setTimeout(() => {
                    productsGrid.classList.remove('fade-in');
                }, 1000);
            }, 300);

            paginationContainer.innerHTML = '';
            const totalPages = Math.ceil(products.length / itemsPerPage);
            
            for (let i = 1; i <= totalPages; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.classList.toggle('active', i === currentPage);
                pageButton.classList.add('pagination-button');
                pageButton.addEventListener('click', () => {
                    currentPage = i;
                    displayProducts(currentPage);
                });
                paginationContainer.appendChild(pageButton);
            }
        }

        displayProducts(currentPage);

        const sortSelect = document.getElementById('sort-select');
        sortSelect.addEventListener('change', () => {
            const sortValue = sortSelect.value;
            const sortedProducts = [...products];

            switch(sortValue) {
                case 'price-asc':
                    sortedProducts.sort((a, b) => a.price - b.price);
                    break;
                case 'price-desc':
                    sortedProducts.sort((a, b) => b.price - a.price);
                    break;
                case 'name-asc':
                    sortedProducts.sort((a, b) => a.name.localeCompare(b.name));
                    break;
                case 'name-desc':
                    sortedProducts.sort((a, b) => b.name.localeCompare(a.name));
                    break;
            }

            products.length = 0;
            products.push(...sortedProducts);

            currentPage = 1;
            displayProducts(currentPage);
        });

    } catch (error) {
        console.error('Ошибка загрузки продуктов:', error);
    }
}

document.addEventListener("DOMContentLoaded", () => {
    const elements = {
        themeBtn: document.getElementById("theme-btn"),
        themeIcon: document.getElementById("theme-icon"),
        homeBtn: document.getElementById('home-btn'),
        productsBtn: document.getElementById('products-btn'),
        contactsBtn: document.getElementById('contacts-btn'),
        mainSection: document.getElementById('main'),
        productsSection: document.getElementById('products'),
        contactsSection: document.getElementById('contacts'),
        newsBtn: document.getElementById('news-btn'),
        newsSection: document.getElementById('news')
    };

    let darkMode = true;

    const changeTheme = () => {
        const rootStyle = document.documentElement.style;
        rootStyle.transition = "background-color 0.3s, color 0.3s";

        const themeConfigs = darkMode 
            ? {
                bgDark: "#f8f9fa",
                bgDarkSecondary: "#ffffff", 
                textLight: "#212529",
                textDescription: "#495057",
                iconClass: { remove: "fa-moon", add: "fa-sun" }
            }
            : {
                bgDark: "#1a202c",
                bgDarkSecondary: "#2d3748", 
                textLight: "#ffffff",
                textDescription: "#e2e8f0",
                iconClass: { remove: "fa-sun", add: "fa-moon" }
            };

        rootStyle.setProperty("--bg-dark", themeConfigs.bgDark);
        rootStyle.setProperty("--bg-dark-secondary", themeConfigs.bgDarkSecondary);
        rootStyle.setProperty("--text-light", themeConfigs.textLight);
        
        const descriptionElements = [
            ...document.querySelectorAll('.ai-section p'),
            ...document.querySelectorAll('.product p'),
            ...document.querySelectorAll('header p')
        ];

        descriptionElements.forEach(element => {
            element.style.color = themeConfigs.textDescription;
        });

        const titleElements = [
            ...document.querySelectorAll('.ai-section h1'),
            ...document.querySelectorAll('.product h2'),
            ...document.querySelectorAll('header h1')
        ];

        titleElements.forEach(element => {
            element.style.color = themeConfigs.textLight;
        });
        
        elements.themeIcon.classList.replace(
            themeConfigs.iconClass.remove, 
            themeConfigs.iconClass.add
        );

        darkMode = !darkMode;
    };

    const showSection = (sectionToShow) => {
        const sections = [
            elements.mainSection, 
            elements.productsSection, 
            elements.contactsSection,
            elements.newsSection
        ];

        sections.forEach(section => {
            section.classList.remove('visible');
            section.classList.add('hidden');
            section.style.pointerEvents = 'none';
        });

        sectionToShow.classList.remove('hidden');
        sectionToShow.classList.add('visible');
        sectionToShow.style.pointerEvents = 'auto';
    };

    elements.themeBtn.addEventListener("click", changeTheme);
    elements.homeBtn.addEventListener('click', () => showSection(elements.mainSection));
    elements.productsBtn.addEventListener('click', () => showSection(elements.productsSection));
    elements.contactsBtn.addEventListener('click', () => showSection(elements.contactsSection));
    elements.newsBtn.addEventListener('click', () => showSection(elements.newsSection));

    showSection(elements.mainSection);

    const extendPageHeight = () => {
        elements.newsSection.style.paddingBottom = "3rem";
        document.body.style.height = "auto";
    };

    const newsBtn = document.getElementById("news-btn");
    newsBtn.addEventListener("click", () => {
        extendPageHeight();
        elements.newsSection.classList.add("expanded");
    });

    async function fetchCryptoPrices() {
            const btcPriceElement = document.getElementById('btc-price');
            try {
                const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
                const data = await response.json();
                const btcPrice = data.bitcoin.usd;
                btcPriceElement.textContent = `$${btcPrice.toLocaleString()}`;
            } catch (error) {
                btcPriceElement.textContent = 'Ошибка загрузки';
            }
        }

        async function loadRSS() {
        const API_URL = 'https://api.rss2json.com/v1/api.json?rss_url=https://www.technologyreview.com/topic/artificial-intelligence/feed';
        const newsContainer = document.getElementById('news-container');

        async function translateText(text) {
            try {
                const response = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=ru&dt=t&q=${encodeURIComponent(text)}`);
                const data = await response.json();
                return data[0][0][0];
            } catch (error) {
                console.error("Ошибка перевода:", error);
                return text;
            }
        }

        try {
            const response = await fetch(API_URL);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();

            if (data.status !== 'ok') {
                throw new Error('Failed to parse RSS feed');
            }

            newsContainer.innerHTML = '';
            newsContainer.classList.remove('loading');

            const firstFiveItems = data.items.slice(0, 5);

            console.log(firstFiveItems);

            for (const [index, item] of firstFiveItems.entries()) {
                const description = item.description.replace(/<[^>]*>/g, '').slice(0, 200) + '...';

                const translatedTitle = await translateText(item.title);
                const translatedDesc = await translateText(description);

                const imageUrl = item.enclosure?.link || item.thumbnail;

                const newsElement = document.createElement('div');
                newsElement.className = 'news-card';
                newsElement.style.animationDelay = `${index * 0.1}s`;

                newsElement.innerHTML = `
                    <div class="news-header">
                        ${imageUrl ? `<img src="${imageUrl}" alt="${translatedTitle}" class="news-image">` : ''}
                        <small class="date">${new Date(item.pubDate).toLocaleDateString('ru-RU')}</small>
                    </div>
                    <h4>${translatedTitle}</h4>
                    <p>${translatedDesc}</p>
                    <div class="original-text">
                        <details>
                            <summary>Показать оригинал</summary>
                            <h4>${item.title}</h4>
                            <p>${description}</p>
                        </details>
                    </div>
                    <a href="${item.link}" target="_blank" class="read-more">Читать далее</a>
                `;

                newsContainer.appendChild(newsElement);
            }
        } catch (error) {
            console.error("Ошибка загрузки новостей:", error);
            newsContainer.classList.remove('loading');
            newsContainer.innerHTML = '<div class="error">Не удалось загрузить новости. Пожалуйста, попробуйте позже.</div>';
        }
    }

    fetchCryptoPrices();
    loadProductsFromFile();
    loadRSS();
        
    const productsGrid = document.getElementById('products-grid');
    if (products && products.length > 0) {
        products.forEach(product => {
            const productElement = document.createElement('div');
            productElement.classList.add('product-compact');
            productElement.innerHTML = `
                <i class="${product.icon}"></i>
                <h5>${product.name}</h5>
                <p>${product.description}</p>
                <p>Цена: ${product.price} ₽</p>
            `;
            productsGrid.appendChild(productElement);
        });
    }
    
if (window.innerWidth <= 768) {
        navContainer.style.overflowX = 'auto';
        const navContainer = document.querySelector('.nav-container');
        const navLinks = document.querySelector('.nav-links');
        newsSection.style.padding = "1rem";

        const hamburgerMenu = document.createElement('div');
        hamburgerMenu.classList.add('hamburger-menu');
        hamburgerMenu.innerHTML = `
            <span></span>
            <span></span>
            <span></span>
        `;
        navContainer.appendChild(hamburgerMenu);

        hamburgerMenu.addEventListener('click', () => {
            hamburgerMenu.classList.toggle('active');
            navLinks.classList.toggle('active');
        });

        document.addEventListener('click', (event) => {
            const isClickInsideMenu = navContainer.contains(event.target);
            
            if (!isClickInsideMenu) {
                hamburgerMenu.classList.remove('active');
                navLinks.classList.remove('active');
            }
        });

        navLinks.querySelectorAll('button').forEach(button => {
            button.addEventListener('click', () => {
                hamburgerMenu.classList.remove('active');
                navLinks.classList.remove('active');
            });
        });
    }

    const form = document.querySelector('.contact-form');
    
    if (form) {
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            
            const formData = new FormData(this);
            
            // Создаем и показываем временное уведомление о загрузке
            const loadingNotification = createNotification('Отправка сообщения...', 'loading');
            
            fetch('send-mail.php', {
                method: 'POST',
                body: formData
            })

            .then(response => response.text())
            .then(data => {
                loadingNotification.remove();
                
                if (data.trim() === 'success') {
                    createNotification('Сообщение успешно отправлено!', 'success');
                    form.reset();
                } else {
                    createNotification('Ошибка при отправке сообщения', 'error');
                }
            })
            .catch(error => {
                loadingNotification.remove();
                createNotification('Не удалось отправить сообщение', 'error');
                console.error('Ошибка:', error);
            });
        });
    }
    
    function createNotification(message, type) {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        if (type !== 'loading') {
            setTimeout(() => {
                notification.classList.add('fade-out');
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        }
        
        return notification;
    }
});


</script>