<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Агро-простір - Управління земельним банком</title>
    
    <!-- PWA Meta Tags -->
    <meta name="theme-color" content="#198754">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="Агро-простір">
    <meta name="msapplication-TileColor" content="#198754">
    <meta name="msapplication-tap-highlight" content="no">
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="manifest.json">
    
    <!-- Apple Touch Icons -->
    <link rel="apple-touch-icon" href="assets/icons/icon-192x192.png">
    <link rel="apple-touch-icon" sizes="152x152" href="assets/icons/icon-152x152.png">
    <link rel="apple-touch-icon" sizes="192x192" href="assets/icons/icon-192x192.png">
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/icons/icon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="assets/icons/icon-32x32.png">
    
    <!-- Direct fix for line 401 before any other scripts -->
    <script>
        // Create a direct fix for the booleanValid issue
        window.turf = window.turf || {};
        
        // Use Object.defineProperty to make this immutable
        Object.defineProperty(window.turf, 'booleanValid', {
            value: function(geometry) {
                console.log("Using IMMUTABLE booleanValid");
                return true; // Always return true
            },
            writable: false,
            configurable: false,
            enumerable: true
        });
        
        // Also fix the main validation function
        window.validateGeometry = function(geometry) {
            console.log("Using HEAD validateGeometry");
            return true; // Always return true
        };
        
        console.log("IMMUTABLE PATCH APPLIED");
    </script>
    
    <!-- Add our modal helper before any other app scripts -->
    <script src="js/modal-helper.js"></script>
    
    <!-- Continue with other head elements -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    
    <!-- Material Icons for Material Design 3.0 -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    
    <!-- Google Fonts - Roboto (Material Design) -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/field-analysis.css">
    <link rel="stylesheet" href="css/pwa-styles.css">
    <link rel="stylesheet" href="css/user-requests.css">
    <link rel="stylesheet" href="css/toast-notifications.css">
    <link rel="stylesheet" href="css/company-cards.css?v=7.1">
    
    <!-- Flutter-style Modern Cards -->
    <link rel="stylesheet" href="css/argon-flutter-cards.css?v=2.6">

    <!-- Мобільні PWA стилі -->
    <link href="css/mobile-pwa.css" rel="stylesheet">

    <!-- 🚨 СПОЧАТКУ: Mobile Flexbox для базової структури -->
    <link rel="stylesheet" href="css/mobile-flexbox-simple.css?v=3.8">
    
    <!-- Smart Navigation System - ПЕРЕЗАПИСУЄ mobile-flexbox для меню (ПІСЛЯ mobile-flexbox) -->
    <link rel="stylesheet" href="css/smart-navigation.css">
    
    <!-- PREVIOUS STYLES - Commented out for Material Design 3.0 -->
    <!-- <link rel="stylesheet" href="css/dashboard-modern.css"> -->
    
    <!-- <link rel="stylesheet" href="css/dashboard-material-design.css"> -->
    
    <!-- <link rel="stylesheet" href="css/dashboard-enhanced-flutter.css"> -->
    
    <!-- � BUSINESS COMPACT STYLE - Optimized -->
    <!-- <link rel="stylesheet" href="css/dashboard-business-compact.css"> -->
    
    <!-- �🔧 FORCE GRID OVERRIDE - максимальний пріоритет -->
    <!-- <link rel="stylesheet" href="css/dashboard-grid-force.css"> -->

    <!-- 🎨 MATERIAL DESIGN 3.0 - Flutter Business Style (Active) -->
    <link rel="stylesheet" href="css/dashboard-material3.css">

    <!-- Index Page Specific Styles (replaced inline styles) -->
    <link rel="stylesheet" href="css/index-styles.css">
    
    <!-- Add our new accessibility CSS -->
    <link rel="stylesheet" href="css/modal-accessibility.css">
    <link rel="stylesheet" href="css/contracts-analytics.css">
    
    <!-- Early Turf.js fix from previous attempts -->
    <script>
        // Ensure turf exists and has booleanValid function
        window.turf = window.turf || {};
        window.turf.booleanValid = window.turf.booleanValid || function(geom) {
            console.log('Using inline booleanValid polyfill');
            return !!(geom && geom.type && geom.coordinates);
        };
        console.log("Early turf.booleanValid polyfill loaded");
    </script>
    
    <!-- Мобільне меню використовує глобальні стилі з smart-navigation.css -->
</head>
<body class="page-home">
    <!-- Floating Particles Background -->
    <div class="particles">
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
    </div>

    <!-- Argon навбар -->
    <nav class="navbar navbar-expand-lg argon-navbar">
        <div class="container-fluid">
            <a class="navbar-brand argon-navbar-brand" href="index.html">
                <i class="bi bi-flower1 me-2"></i>Агро-простір
            </a>
            
            <button class="navbar-toggler argon-navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link argon-nav-link active" href="index.html">
                            <i class="bi bi-house me-1"></i>Головна
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link argon-nav-link" href="pages/resources.html">
                            <i class="bi bi-geo-alt me-1"></i>Ресурси
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link argon-nav-link" href="pages/my-registry.html">
                            <i class="bi bi-journal-text me-1"></i>Мій реєстр
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link argon-nav-link" href="pages/notes.html">
                            <i class="bi bi-sticky me-1"></i>Замітки
                        </a>
                    </li>
                    <!-- PWA-specific menu item, hidden in browser mode -->
                    <li class="nav-item pwa-only" style="display: none;">
                        <a class="nav-link argon-nav-link" href="pwa-diagnostics.html">
                            <i class="bi bi-gear me-1"></i>Діагностика
                        </a>
                    </li>
                    <!-- Мобільне меню з трьома крапками -->
                    <li class="nav-item dropdown d-lg-none">
                        <a class="nav-link argon-nav-link dropdown-toggle" href="#" id="mobileMenuDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-three-dots-vertical me-1"></i>Меню
                        </a>
                        <ul class="dropdown-menu argon-dropdown-menu" aria-labelledby="mobileMenuDropdown">
                            <li><a class="dropdown-item argon-dropdown-item" href="pages/settings-simple.html">
                                <i class="bi bi-gear me-2"></i>Параметри
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item argon-dropdown-item" href="#" onclick="logout()">
                                <i class="bi bi-box-arrow-right me-2"></i>Вийти
                            </a></li>
                        </ul>
                    </li>
                </ul>
                
                <!-- Argon соціальні мережі в навбарі -->
                <div class="argon-navbar-social d-flex align-items-center me-3">
                    <a href="register.html" class="btn argon-btn-outline btn-sm me-2" title="Зв'язатись з нами">
                        <i class="bi bi-chat-dots"></i>
                    </a>
                    <button id="installPWA-navbar" class="btn argon-btn-outline btn-sm me-2" title="Встановити додаток">
                        <i class="bi bi-download"></i>
                    </button>
                    <a href="https://t.me/agro_workspace" target="_blank" class="btn argon-btn-outline btn-sm me-2" title="Telegram канал">
                        <i class="bi bi-telegram"></i>
                    </a>
                    <a href="https://invite.viber.com/?g2=AQBuIMLOVsXoilGIsOfkdrpF3js8He7%2FBCfBZcO17ahyDSdyOhnIcqH7437QFc6K" target="_blank" class="btn argon-btn-outline btn-sm me-2" title="Viber спільнота">
                        <i class="bi bi-chat"></i>
                    </a>
                </div>
                
                <!-- Argon користувацьке меню (показується після входу) -->
                <div class="navbar-nav" id="userMenu" style="display: none;">
                    <div class="nav-item dropdown">
                        <a class="nav-link argon-nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-1"></i>
                            <span id="userName">Користувач</span>
                        </a>
                        <ul class="dropdown-menu argon-dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item argon-dropdown-item" href="cabinet.html">
                                <i class="bi bi-house me-1"></i>Кабінет
                            </a></li>
                            <li><a class="dropdown-item argon-dropdown-item" href="pages/user-settings.html">
                                <i class="bi bi-gear me-1"></i>Налаштування
                            </a></li>
                            <li><a class="dropdown-item argon-dropdown-item" href="pages/settings-simple.html">
                                <i class="bi bi-sliders me-1"></i>Параметри системи
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item argon-dropdown-item" href="#" onclick="logout()">
                                <i class="bi bi-box-arrow-right me-1"></i>Вихід
                            </a></li>
                        </ul>
                    </div>
                </div>
                
                <!-- Argon кнопки авторизації (показуються до входу) -->
                <div class="d-flex" id="authButtons">
                    <a href="login.html" class="btn argon-btn-outline me-2">Увійти</a>
                    <a href="register.html" class="btn argon-btn-primary">Реєстрація</a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid px-0" id="main-content">
        <!-- Hero section -->
        <div class="bg-light py-5 py-md-5 py-3" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
            <div class="container-fluid px-4 px-md-4 px-xl-5">
                <div class="row align-items-center">
                    <div class="col-md-10 col-xl-11 mx-auto text-center">
                        <!-- Контент для незалогінених користувачів -->
                        <div id="hero-guest-content">
                            <h1 class="display-4 fw-bold text-success">Агро-простір</h1>
                            <p class="lead mb-4">Автоматизуйте процеси управління вашими земельними ділянками та підвищіть ефективність агробізнесу</p>
                            <div class="mt-4">
                                <!-- Головні кнопки дії -->
                                <div class="d-flex justify-content-center align-items-center mb-3" style="gap: 1rem; flex-wrap: wrap;">
                                    <a href="register.html" class="btn btn-success btn-lg" style="width: 180px; height: 48px; display: flex; align-items: center; justify-content: center;">
                                        <i class="bi bi-chat-dots me-1"></i> Зв'язатись
                                    </a>
                                    
                                    <!-- PWA Install Button -->
                                    <button id="installPWA" class="btn btn-outline-success btn-lg" style="width: 180px; height: 48px; display: flex; align-items: center; justify-content: center;">
                                        <i class="bi bi-download me-1"></i> Встановити
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Dashboard для залогінених користувачів -->
                        <div id="hero-user-content" style="display: none;">
                            <!-- Прибираємо заголовок -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 📊 СУЧАСНИЙ ДАШБОРД - Нова структура в стилі Material Design -->
        <div id="user-dashboard-grid" class="dashboard-hidden">
            <!-- Дашборд буде створений динамічно через DashboardController -->
        </div>

        <!-- 🔄 ПРОСТИЙ ІНДИКАТОР ЗАВАНТАЖЕННЯ (НЕ БЛОКУЮЧИЙ) -->
        <div id="simple-loading" class="alert alert-info text-center mb-3" style="display: none;">
            <div class="d-inline-flex align-items-center">
                <div class="spinner-border spinner-border-sm text-info me-2" role="status">
                    <span class="visually-hidden">Завантаження...</span>
                </div>
                <span>Завантаження даних...</span>
            </div>
        </div>
        </div>
    </div>

    <!-- Load scripts in optimal order -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
    
    <!-- PDF and Canvas libraries for Ukrainian text support -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    
    <!-- FIX: Load turf with specific modules needed -->
    <script src="https://unpkg.com/@turf/turf@6.5.0/turf.min.js"></script>
    <script src="js/field-analysis.js"></script>
    
    <!-- PDF Reporter for contractor analysis -->
    <script src="js/pdf-reporter.js"></script>
    
    <!-- Contracts Analytics Dashboard -->
    <script src="js/contracts-analytics.js"></script>
    
    <!-- Add one more failsafe before application scripts -->
    <script>
        // Final check to ensure turf.booleanValid exists
        if (typeof turf.booleanValid !== 'function') {
            console.log("FINAL CHECK: Adding turf.booleanValid");
            
            // Use Object.defineProperty to force it to exist
            Object.defineProperty(window.turf, 'booleanValid', {
                value: function(geometry) {
                    return true;
                },
                writable: false,
                configurable: false
            });
        }
        
        // Add a global error handler for this specific error
        window.addEventListener('error', function(event) {
            if (event.error && event.error.toString().includes('turf.booleanValid is not a function')) {
                console.log("CAUGHT turf.booleanValid error in real-time");
                
                // Re-add the function
                try {
                    Object.defineProperty(window.turf, 'booleanValid', {
                        value: function() { return true; },
                        writable: true,
                        configurable: true
                    });
                } catch (e) {
                    // If we can't redefine it, set it directly
                    window.turf.booleanValid = function() { return true; };
                }
                
                // Stop error propagation
                event.preventDefault();
                return true;
            }
        }, true);
    </script>
    
    <!-- PWA Service Worker -->
    <script>
        // Реєстрація Service Worker для PWA
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', async () => {
                try {
                    const registration = await navigator.serviceWorker.register('sw.js');
                    
                    // Перевіряємо поточну версію
                    if (registration.active) {
                        checkSWVersion(registration.active);
                    }
                    
                    // Слухаємо оновлення
                    registration.addEventListener('updatefound', () => {
                        const newWorker = registration.installing;
                        
                        newWorker.addEventListener('statechange', () => {
                            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                // Примусово активуємо новий SW
                                newWorker.postMessage({ type: 'SKIP_WAITING' });
                            }
                        });
                    });
                    
                    // Слухаємо повідомлення про контроль
                    navigator.serviceWorker.addEventListener('controllerchange', () => {
                        window.location.reload(); // Перезавантажуємо сторінку
                    });
                    
                } catch (error) {
                    // Service Worker не підтримується або помилка реєстрації
                }
            });
        }
        
        // Функція для перевірки версії SW
        function checkSWVersion(worker) {
            const channel = new MessageChannel();
            channel.port1.onmessage = (event) => {
                if (event.data.type === 'VERSION_RESPONSE') {
                    // Версія SW отримана
                }
            };
            worker.postMessage({ type: 'GET_VERSION' }, [channel.port2]);
        }
        
        // Функція для примусового оновлення SW
        function updateServiceWorker() {
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.getRegistration().then(registration => {
                    if (registration) {
                        registration.update();
                    }
                });
            }
        }
        
        // Функція для очищення кешу
        function clearAllCaches() {
            if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
                navigator.serviceWorker.controller.postMessage({ type: 'CLEAR_CACHE' });
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            }
        }
    </script>
    
    <!-- PWA Install Script -->
    <script>
        let deferredPrompt;
        const installButton = document.getElementById('installPWA');

        // Функція для відображення інструкцій встановлення
        function showInstallInstructions() {
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header bg-success text-white">
                            <h5 class="modal-title">📱 Встановлення PWA додатку</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>🖥️ На Windows (Chrome/Edge):</h6>
                                    <ol>
                                        <li>Натисніть іконку <strong>⬇️</strong> в адресному рядку</li>
                                        <li>Або Меню → "Встановити Агро-простір"</li>
                                        <li>Підтвердіть встановлення</li>
                                        <li>Додаток з'явиться в меню Пуск</li>
                                    </ol>
                                </div>
                                <div class="col-md-6">
                                    <h6>📱 На Android (Chrome):</h6>
                                    <ol>
                                        <li>Меню браузера (⋮)</li>
                                        <li>"Додати на головний екран"</li>
                                        <li>Або кнопка "Встановити"</li>
                                        <li>Додаток з'явиться на екрані</li>
                                    </ol>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-md-6">
                                    <h6>🍎 На iOS (Safari):</h6>
                                    <ol>
                                        <li>Кнопка "Поділитися" (⬆️)</li>
                                        <li>"На екран 'Домівка'"</li>
                                        <li>Введіть назву</li>
                                        <li>Натисніть "Додати"</li>
                                    </ol>
                                </div>
                                <div class="col-md-6">
                                    <h6>✨ Переваги PWA:</h6>
                                    <ul>
                                        <li>🚀 Швидший запуск</li>
                                        <li>📱 Повноекранний режим</li>
                                        <li>⚡ Офлайн робота</li>
                                        <li>🔄 Автооновлення</li>
                                        <li>🔒 Безпечність</li>
                                    </ul>
                                </div>
                            </div>
                            <div class="alert alert-info mt-3">
                                <strong>💡 Підказка:</strong> Якщо кнопка встановлення не з'являється в браузері, 
                                спробуйте відкрити сайт через HTTPS або локальний сервер.
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрити</button>
                            <a href="PWA-INSTALL-GUIDE.md" class="btn btn-success" target="_blank">Детальна інструкція</a>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            const bootstrapModal = new bootstrap.Modal(modal);
            bootstrapModal.show();
            
            // Видаляємо модал після закриття
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }

        // Перевірка на наявність нативного install промпта
        window.addEventListener('beforeinstallprompt', (e) => {
            console.log('🎯 PWA готовий до встановлення');
            e.preventDefault();
            deferredPrompt = e;
            
            const installButton = document.getElementById('installPWA');
            const navbarInstallButton = document.getElementById('installPWA-navbar');
            
            // Показуємо кнопки з нативним промптом
            if (installButton && !isPWA()) {
                installButton.innerHTML = '<i class="bi bi-download"></i> Встановити зараз';
                installButton.classList.remove('btn-outline-success');
                installButton.classList.add('btn-success');
                installButton.classList.add('show');
                installButton.title = 'Встановити додаток';
                installButton.disabled = false;
            }
            
            if (navbarInstallButton && !isPWA()) {
                navbarInstallButton.style.display = 'flex';
                navbarInstallButton.classList.remove('btn-outline-light');
                navbarInstallButton.classList.add('btn-light');
            }
        });

        // Додаємо PWA статус та логіку показу кнопки
        document.addEventListener('DOMContentLoaded', () => {
            const installButton = document.getElementById('installPWA');
            const navbarInstallButton = document.getElementById('installPWA-navbar');
            
            if (isPWA()) {
                console.log('✅ Запущено як PWA');
                document.body.classList.add('pwa-mode');
                
                // Показуємо PWA-only навігаційні елементи
                const pwaOnlyItems = document.querySelectorAll('.pwa-only');
                pwaOnlyItems.forEach(item => {
                    item.style.display = 'block';
                });
                
                // Якщо запущено як PWA, приховуємо кнопки установки
                if (installButton) {
                    installButton.classList.remove('show');
                }
                if (navbarInstallButton) {
                    navbarInstallButton.style.display = 'none';
                }
            } else {
                console.log('🌐 Запущено в браузері');
                
                // Показуємо кнопки одразу, незалежно від наявності промпта
                if (installButton) {
                    installButton.innerHTML = '<i class="bi bi-download"></i> Встановити зараз';
                    installButton.classList.add('show');
                    installButton.title = 'Встановити додаток';
                }
                
                if (navbarInstallButton) {
                    navbarInstallButton.style.display = 'flex';
                }
                
                // Через 1 секунду перевіряємо, чи є нативний промпт для оновлення стилю
                setTimeout(() => {
                    if (installButton && deferredPrompt) {
                        installButton.classList.remove('btn-outline-success');
                        installButton.classList.add('btn-success');
                    }
                    if (navbarInstallButton && deferredPrompt) {
                        navbarInstallButton.classList.remove('btn-outline-light');
                        navbarInstallButton.classList.add('btn-light');
                    }
                }, 1000);
            }
        });
        
        // Функція для налаштування обробників PWA кнопок
        function setupPWAButtons() {
            const installButton = document.getElementById('installPWA');
            const navbarInstallButton = document.getElementById('installPWA-navbar');
            
            // Функція обробки кліку
            const handleInstallClick = async () => {
                if (deferredPrompt) {
                    console.log('📱 Встановлення PWA...');
                    // Нативне встановлення PWA
                    deferredPrompt.prompt();
                    const { outcome } = await deferredPrompt.userChoice;
                    
                    if (outcome === 'accepted') {
                        console.log('✅ PWA встановлено успішно');
                        if (installButton) installButton.classList.remove('show');
                        if (navbarInstallButton) navbarInstallButton.style.display = 'none';
                    } else {
                        console.log('❌ Користувач відхилив встановлення');
                    }
                    
                    deferredPrompt = null;
                } else {
                    // Показуємо інструкції встановлення
                    showInstallInstructions();
                }
            };
            
            // Додаємо обробники для обох кнопок
            if (installButton) {
                installButton.addEventListener('click', handleInstallClick);
            }
            
            if (navbarInstallButton) {
                navbarInstallButton.addEventListener('click', handleInstallClick);
            }
        }
        
        // Викликаємо функцію налаштування кнопок
        setupPWAButtons();

        // Приховуємо кнопки після успішного встановлення
        window.addEventListener('appinstalled', () => {
            console.log('PWA was installed successfully');
            const installButton = document.getElementById('installPWA');
            const navbarInstallButton = document.getElementById('installPWA-navbar');
            
            if (installButton) {
                installButton.classList.remove('show');
            }
            if (navbarInstallButton) {
                navbarInstallButton.style.display = 'none';
            }
        });

        // Обробник успішного встановлення PWA (видаляємо дублювання)
        window.addEventListener('appinstalled', () => {
            console.log('PWA успішно встановлено');
            deferredPrompt = null;
        });

        // Перевірка, чи запущено як PWA
        function isPWA() {
            return window.matchMedia('(display-mode: standalone)').matches || 
                   window.navigator.standalone === true;
        }
    </script>
    
    <!-- Now load application scripts -->
    <script src="js/config.js"></script>
    <script src="js/auth.js"></script>
    
    <!-- Dashboard Scripts -->
    <script src="js/dashboard-stats-api.js?v=8.5"></script>
    <script src="js/dashboard-stats-integration.js"></script>
    <script src="js/cached-companies-renderer.js?v=9.3"></script>
    <script src="js/consolidated-companies.js"></script>
    <script src="js/dashboard-dev-tools.js"></script>
    
    <!-- Modern Dashboard Controller -->
    <script src="js/dashboard-controller.js"></script>
    
    <script src="js/user-settings.js"></script>
    <script src="js/smart-navigation.js"></script>
    <script src="js/smart-navigation-scroll.js"></script>
    <script src="js/pwa-navigation-stabilizer.js"></script>
    
    <!-- Material Design Auto-Apply для панелі аналізу -->
    <script src="js/material-design-auto-apply.js"></script>
    
    <!-- Material Design 3.0 Dashboard Animations -->
    <script src="js/material-dashboard-animations.js"></script>

    <!-- Функція рефрешу головної сторінки -->
    <script>
        // Функція рефрешу головної сторінки (локальна версія для index.html)
        function refreshHomePage() {
            console.log('🔄 Refreshing homepage (already on home page)...');
            
            // Для PWA додаємо очищення кешу та форсований рефреш
            if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
                console.log('📱 PWA detected, forcing cache refresh...');
                
                // Очищаємо кеш сторінки
                if ('caches' in window) {
                    caches.delete('agro-space-dynamic-v1.3.6-spatial-filter-enhanced');
                }
                
                // Форсований рефреш з обходом кешу
                window.location.href = 'index.html?refresh=' + Date.now() + '&t=' + Math.random();
            } else {
                // Звичайний рефреш для браузера
                window.location.href = 'index.html?refresh=' + Date.now();
            }
        }

        // Робимо функцію глобальною
        window.refreshHomePage = refreshHomePage;
        
        // Функція виходу з системи
        function logout() {
            if (confirm('Ви дійсно хочете вийти з системи?')) {
                console.log('🚪 Logging out user...');
                
                // Очищаємо локальне сховище
                localStorage.clear();
                sessionStorage.clear();
                
                // Якщо доступний Supabase - робимо signOut
                if (window.supabase && window.supabase.auth) {
                    window.supabase.auth.signOut().then(() => {
                        console.log('✅ Supabase logout successful');
                        window.location.href = 'login.html';
                    }).catch((error) => {
                        console.error('❌ Logout error:', error);
                        // Все одно перенаправляємо на логін
                        window.location.href = 'login.html';
                    });
                } else {
                    // Якщо Supabase недоступний, просто перенаправляємо
                    window.location.href = 'login.html';
                }
            }
        }
        
        // Робимо функцію глобальною
        window.logout = logout;
        
        // Проста заглушка для сумісності (тепер все керується DashboardController)
        window.loadCompaniesCardsInline = async function() {
            console.log('🏢 loadCompaniesCardsInline викликано (керується DashboardController)');
            // Функція залишена для сумісності, але логіка перенесена в DashboardController
        };
    </script>

    <!-- Скрипт для обробки переходу на карту -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('🔄 index.html DOMContentLoaded: Starting...');
            
            // Форсоване оновлення Service Worker для нової версії
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.getRegistrations().then(function(registrations) {
                    for(let registration of registrations) {
                        console.log('🔄 Force updating Service Worker...');
                        registration.update();
                    }
                });
                
                // Очищуємо старі кеші
                if ('caches' in window) {
                    caches.keys().then(function(cacheNames) {
                        return Promise.all(
                            cacheNames.filter(function(cacheName) {
                                return cacheName.includes('agro-space') && !cacheName.includes('v1.3.8');
                            }).map(function(cacheName) {
                                console.log('🗑️ Deleting old cache:', cacheName);
                                return caches.delete(cacheName);
                            })
                        );
                    });
                }
            }
            
            // Ініціалізуємо userSettings для карток підприємств
            if (typeof UserSettings !== 'undefined') {
                window.userSettings = new UserSettings();
                console.log('✅ UserSettings ініціалізовано на головній сторінці');
            } else {
                console.warn('⚠️ UserSettings клас не знайдено');
            }
            
            // Перевіряємо, чи був запит на рефреш
            const urlParams = new URLSearchParams(window.location.search);
            const refreshParam = urlParams.get('refresh');
            const tParam = urlParams.get('t'); // додатковий параметр для PWA
            
            // ВІДКЛЮЧЕНО: Старі системи статистики заблоковані для нового дизайну
            console.log('🚫 index.html: Старі системи статистики відключені');
            console.log('🎛️ index.html: Дашборд керується тільки через DashboardController');
            
            // Додаємо гарантований виклик тільки DashboardController через 1 секунду
            setTimeout(async () => {
                console.log('🎯 index.html: Checking DashboardController status...');
                
                // Перевіряємо чи користувач залогінений
                if (window.supabase && window.supabase.auth) {
                    try {
                        const { data: { user } } = await window.supabase.auth.getUser();
                        const dashboardGrid = document.getElementById('user-dashboard-grid');
                        
                        if (user && dashboardGrid && !dashboardGrid.classList.contains('dashboard-hidden')) {
                            console.log('✅ index.html: User authenticated and dashboard visible');
                            console.log('🎛️ index.html: Dashboard керується через DashboardController');
                            
                            // Перезапускаємо Material Design анімації після рендерингу дашборду
                            setTimeout(() => {
                                if (window.materialDashboardAnimations) {
                                    console.log('🎨 Перезапуск Material Design анімацій...');
                                    window.materialDashboardAnimations.restartCounters();
                                    window.materialDashboardAnimations.animateCardAppearance();
                                }
                            }, 1000);
                        } else {
                            console.log('❌ index.html: User not authenticated or dashboard hidden');
                        }
                        
                    } catch (error) {
                        console.error('❌ index.html: Error checking user:', error);
                    }
                } else {
                    console.log('❌ index.html: Supabase not available');
                }
            }, 1000);
            
            // ВІДКЛЮЧЕНО: Всі старі системи статистики та рендерінгу заблоковані
            console.log('🚫 index.html: Старі рендерери повністю відключені для нового дизайну');
            
        }); // end DOMContentLoaded
        
        // Простий індикатор завантаження (не блокуючий)
        const simpleLoading = document.getElementById('simple-loading');
        if (simpleLoading) {
            simpleLoading.style.display = 'block';
            
            // Приховуємо через 2 секунди
            setTimeout(() => {
                simpleLoading.style.display = 'none';
                console.log('✅ Індикатор завантаження прихований');
            }, 2000);
        }
        
        console.log('ℹ️ Сторінка готова до використання (з простим індикатором)');

        // Ініціалізація завершена - дашборд працює через DashboardController
        console.log('✅ index.html: Ініціалізація завершена');
        
    </script>

    <!-- Функція рефрешу головної сторінки -->
    <script>
        // Функція рефрешу головної сторінки (локальна версія для index.html)
        function refreshHomePage() {
            console.log('🔄 Refreshing homepage (already on home page)...');
            
            // Для PWA додаємо очищення кешу та форсований рефреш
            if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
                console.log('📱 PWA detected, forcing cache refresh...');
                
                // Очищаємо кеш сторінки
                if ('caches' in window) {
                    caches.delete('agro-space-dynamic-v1.3.6-spatial-filter-enhanced');
                }
                
                // Форсований рефреш з обходом кешу
                window.location.href = 'index.html?refresh=' + Date.now() + '&t=' + Math.random();
            } else {
                // Звичайний рефреш для браузера
                window.location.href = 'index.html?refresh=' + Date.now();
            }
        }
        
        // Обробник кліків для карти з територією
        document.addEventListener('DOMContentLoaded', () => {
            // Знаходимо посилання на карту
            const mapLink = document.querySelector('a[data-page="map"]');
            
            if (mapLink) {
                mapLink.addEventListener('click', function(e) {
                    e.preventDefault(); // Запобігаємо стандартному переходу
                    
                    // Перевіряємо чи є збережена територія
                    const savedTerritory = localStorage.getItem('agro-current-territory');
                    
                    if (savedTerritory) {
                        // Якщо є збережена територія - переходимо з параметром
                        try {
                            const territory = JSON.parse(savedTerritory);
                            window.location.href = `pages/map.html?coatuu=${territory.coatuu}`;
                        } catch (error) {
                            // Якщо помилка парсингу - очищаємо і переходимо без параметра
                            localStorage.removeItem('agro-current-territory');
                            window.location.href = 'pages/map.html';
                        }
                    } else {
                        // Якщо немає збереженої території - переходимо без параметра
                        window.location.href = 'pages/map.html';
                    }
                });
            }
        });
    </script>

    <!-- 📱 СТАНДАРТНЕ МОБІЛЬНЕ МЕНЮ -->
    <nav class="mobile-bottom-nav">
        <!-- Ліва сторона: 2 кнопки -->
        <a href="pages/map.html" class="mobile-nav-item" data-page="map">
            <i class="bi bi-map"></i>
            <span>Карта</span>
        </a>
        <a href="pages/my-registry.html" class="mobile-nav-item" data-page="my-registry">
            <i class="bi bi-journal-text"></i>
            <span>Реєстр</span>
        </a>
        
        <!-- Центр: Головна кнопка -->
        <a href="index.html" class="mobile-nav-item mobile-nav-home active" data-page="home">
            <i class="bi bi-house-fill"></i>
            <span>Головна</span>
        </a>
        
        <!-- Права сторона: 2 кнопки -->
        <a href="pages/notes.html" class="mobile-nav-item" data-page="notes">
            <i class="bi bi-sticky"></i>
            <span>Замітки</span>
        </a>
        
        <!-- Smart Menu Dropdown - ФІКСОВАНИЙ РОЗМІР -->
        <div class="mobile-nav-item dropdown" data-page="menu">
            <button class="btn p-0 text-center w-100 h-100 d-flex flex-column align-items-center justify-content-center" 
                    type="button" 
                    id="mobileBottomMenuDropdown" 
                    data-bs-toggle="dropdown" 
                    aria-expanded="false"
                    style="border: none !important; outline: none !important; box-shadow: none !important; background: transparent !important;">
                <i class="bi bi-three-dots"></i>
                <span>Меню</span>
            </button>
            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="mobileBottomMenuDropdown">
                <!-- Основні функції -->
                <li><a class="dropdown-item" href="pages/requests.html">
                    <i class="bi bi-chat-dots text-warning"></i>Запити
                </a></li>
                <li><a class="dropdown-item" href="pages/resources.html">
                    <i class="bi bi-geo-alt text-info"></i>Ресурси
                </a></li>
                <li><hr class="dropdown-divider"></li>
                <!-- Система -->
                <li><a class="dropdown-item" href="#" onclick="logout()">
                    <i class="bi bi-box-arrow-right text-danger"></i>Вийти
                </a></li>
            </ul>
        </div>
    </nav>

    <!-- JavaScript для мобільного меню -->
    <script>
        // Функція для переходу на карту з урахуванням збереженої території
        function goToMapWithTerritory() {
            const savedTerritory = localStorage.getItem('agro-current-territory');
            if (savedTerritory) {
                try {
                    const territory = JSON.parse(savedTerritory);
                    window.location.href = `pages/map.html?coatuu=${territory.coatuu}`;
                } catch (error) {
                    localStorage.removeItem('agro-current-territory');
                    window.location.href = 'pages/map.html';
                }
            } else {
                window.location.href = 'pages/map.html';
            }
        }

        // Функція logout (якщо не існує)
        if (typeof logout === 'undefined') {
            function logout() {
                if (window.supabase && window.supabase.auth) {
                    window.supabase.auth.signOut().then(() => {
                        window.location.href = 'login.html';
                    }).catch(() => {
                        window.location.href = 'login.html';
                    });
                } else {
                    window.location.href = 'login.html';
                }
            }
        }

        // Робимо функції доступними глобально
        window.goToMapWithTerritory = goToMapWithTerritory;
        if (typeof window.logout === 'undefined') {
            window.logout = logout;
        }
    </script>

    <!-- Модальне вікно аналітики договорів -->
    <div class="modal fade" id="contractsAnalyticsModal" tabindex="-1" aria-labelledby="contractsAnalyticsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title" id="contractsAnalyticsModalLabel">
                        <i class="bi bi-graph-up me-2"></i>
                        Аналітика договорів оренди
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Закрити"></button>
                </div>
                
                <!-- Стан завантаження -->
                <div id="analyticsLoading" class="text-center py-5" style="display: none;">
                    <div class="spinner-border text-info" role="status">
                        <span class="visually-hidden">Завантаження...</span>
                    </div>
                    <p class="mt-3 text-muted">Обробка даних договорів...</p>
                </div>
                
                <!-- Стан помилки -->
                <div id="analyticsError" class="text-center py-5" style="display: none;">
                    <i class="bi bi-exclamation-triangle display-1 text-warning"></i>
                    <h5 class="mt-3">Помилка завантаження</h5>
                    <p class="text-muted" id="analyticsErrorText">Не вдалося завантажити дані для аналітики</p>
                    <button class="btn btn-outline-info" onclick="window.contractsAnalytics.showAnalytics()">
                        <i class="bi bi-arrow-clockwise me-2"></i>Спробувати знову
                    </button>
                </div>
                
                <!-- Основний контент -->
                <div id="analyticsContent" class="modal-body" style="display: none;">
                    <!-- Фільтри та експорт -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <label for="yearFilter" class="form-label">Фільтр по роках:</label>
                            <select class="form-select" id="yearFilter">
                                <option value="all">Всі роки</option>
                                <option value="critical">Критичні (≤3 роки)</option>
                                <option value="expired">Прострочені</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="tenantSearch" class="form-label">Пошук орендаря:</label>
                            <input type="text" class="form-control" id="tenantSearch" placeholder="Введіть назву орендаря...">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <button class="btn btn-success w-100" id="exportAnalytics">
                                <i class="bi bi-download me-2"></i>Експорт в Excel
                            </button>
                        </div>
                    </div>
                    
                    <!-- Загальна статистика -->
                    <div class="row mb-4" id="generalStats">
                        <!-- Статистика буде додана динамічно -->
                    </div>
                    
                    <!-- Критичні роки -->
                    <div class="mb-4">
                        <h6 class="mb-3">
                            <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>
                            Критичні роки (закінчення ≤3 роки)
                        </h6>
                        <div class="row" id="criticalYearsCards">
                            <!-- Картки критичних років будуть додані динамічно -->
                        </div>
                    </div>
                    
                    <!-- Хітмап таблиця -->
                    <div class="mb-4">
                        <h6 class="mb-3">
                            <i class="bi bi-table text-info me-2"></i>
                            Розподіл договорів по орендарям та рокам
                        </h6>
                        <div class="table-responsive" id="heatmapTableContainer">
                            <!-- Таблиця буде додана динамічно -->
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрити</button>
                </div>
            </div>
        </div>
    </div>

    <!-- � ДЕБАГ: Активація Simple Flexbox Layout -->
    <script>
        // Активуємо простий flexbox для ВСІХ пристроїв
        function activateMobileFlexboxLayout() {
            const isMobile = window.innerWidth <= 991.98;
            const html = document.documentElement;
            const body = document.body;
            
            // ЗАВЖДИ активуємо flexbox layout
            html.classList.add('mobile-flexbox-layout');
            
            // Додаємо фіксацію статистики на мобільних
            if (isMobile) {
                body.classList.add('mobile-flexbox-active');
                fixMobileStatistics();
            } else {
                body.classList.remove('mobile-flexbox-active');
            }
            
            if (isMobile) {
                console.log('📱 ✅ АКТИВОВАНО Simple Flexbox Layout (МОБІЛЬНИЙ)');
                console.log('🔍 Ширина екрану:', window.innerWidth);
                console.log('🔍 HTML клас додано:', html.className);
                
                // Перевіряємо чи є потрібні елементи
                setTimeout(() => {
                    const userDashboard = document.querySelector('#user-dashboard-grid');
                    const userCompanies = document.querySelector('#user-companies-container');
                    console.log('🔍 #user-dashboard-grid знайдено:', !!userDashboard);
                    console.log('🔍 #user-companies-container знайдено:', !!userCompanies);
                    
                    if (userDashboard) {
                        console.log('🔍 Dashboard display:', getComputedStyle(userDashboard).display);
                    }
                    if (userCompanies) {
                        console.log('🔍 Companies display:', getComputedStyle(userCompanies).display);
                    }
                }, 500);
                
                // Перевіряємо flexbox властивості
                setTimeout(() => {
                    const navbar = document.querySelector('.navbar');
                    const mainContent = document.querySelector('#main-content');
                    const mobileMenu = document.querySelector('.mobile-bottom-nav');
                    
                    console.log('🔍 FLEXBOX ДЕБАГ:');
                    console.log('Body display:', getComputedStyle(body).display);
                    console.log('Body flex-direction:', getComputedStyle(body).flexDirection);
                    console.log('Body height:', getComputedStyle(body).height);
                    
                    if (mainContent) {
                        console.log('Main flex:', getComputedStyle(mainContent).flex);
                        console.log('Main height:', getComputedStyle(mainContent).height);
                    }
                    
                    if (mobileMenu) {
                        console.log('Menu flex-shrink:', getComputedStyle(mobileMenu).flexShrink);
                        console.log('Menu height:', getComputedStyle(mobileMenu).height);
                    }
                }, 100);
            } else {
                console.log('💻 ✅ АКТИВОВАНО Simple Flexbox Layout (ДЕСКТОП)');
                console.log('� Ширина екрану:', window.innerWidth);
                console.log('🔍 HTML клас активний:', html.className);
            }
        }
        
        // Фіксація статистики ТІЛЬКИ в картках компаній з блочною структурою
        function fixMobileStatistics() {
            setTimeout(() => {
                // Знаходимо ТІЛЬКИ картки компаній з новим дизайном
                const companyCards = document.querySelectorAll('.progress-comparison-card');
                let fixedElements = 0;
                
                companyCards.forEach(card => {
                    // Налаштовуємо контейнер статистики - КОМПАКТНО
                    const statContainer = card.querySelector('.argon-stat-container');
                    if (statContainer) {
                        statContainer.style.setProperty('display', 'flex', 'important');
                        statContainer.style.setProperty('flex-direction', 'column', 'important');
                        statContainer.style.setProperty('gap', '10px', 'important');
                        statContainer.style.setProperty('padding', '12px', 'important');
                    }
                    
                    // Налаштовуємо всі блоки статистики - КОМПАКТНО
                    const statBlocks = card.querySelectorAll('.stat-block');
                    statBlocks.forEach(block => {
                        block.style.setProperty('padding', '10px', 'important');
                        block.style.setProperty('margin-bottom', '8px', 'important');
                        block.style.setProperty('border-radius', '8px', 'important');
                        block.style.setProperty('min-height', 'auto', 'important');
                        fixedElements++;
                    });
                    
                    // Фіксуємо числові значення в блоках - ШИРШІ І БІЛЬШІ
                    const statNumbers = card.querySelectorAll('.argon-stat-number, .text-info, .fw-bold, [class*="text-"]');
                    statNumbers.forEach(element => {
                        if (element.textContent && element.textContent.match(/\d/)) {
                            element.style.setProperty('font-size', '1.4rem', 'important');
                            element.style.setProperty('font-weight', '700', 'important');
                            element.style.setProperty('letter-spacing', '1px', 'important');
                            element.style.setProperty('padding', '8px 12px', 'important');
                            element.style.setProperty('margin', '4px 0', 'important');
                            element.style.setProperty('white-space', 'nowrap', 'important');
                            element.style.setProperty('word-break', 'keep-all', 'important');
                            element.style.setProperty('text-align', 'center', 'important');
                            element.style.setProperty('display', 'inline-block', 'important');
                            element.style.setProperty('background', 'rgba(255, 255, 255, 0.2)', 'important');
                            element.style.setProperty('border-radius', '6px', 'important');
                            element.style.setProperty('box-shadow', '0 1px 3px rgba(0,0,0,0.1)', 'important');
                            fixedElements++;
                        }
                    });
                    
                    // Фіксуємо підписи
                    const statSubtitles = card.querySelectorAll('.argon-card-subtitle');
                    statSubtitles.forEach(element => {
                        element.style.setProperty('white-space', 'nowrap', 'important');
                        element.style.setProperty('word-break', 'keep-all', 'important');
                        element.style.setProperty('font-size', '1rem', 'important');
                        element.style.setProperty('font-weight', '600', 'important');
                        fixedElements++;
                    });
                    
                    // Фіксуємо індикатор різниці
                    const freshnessIndicators = card.querySelectorAll('.data-freshness-indicator');
                    freshnessIndicators.forEach(element => {
                        element.style.setProperty('white-space', 'nowrap', 'important');
                        element.style.setProperty('word-break', 'keep-all', 'important');
                        element.style.setProperty('text-align', 'center', 'important');
                        fixedElements++;
                    });
                });
                
                console.log('🔧 Застосовано блочну структуру для статистики в', companyCards.length, 'картках компаній (' + fixedElements + ' елементів)');
            }, 100);
        }
        
        // Активуємо при завантаженні
        document.addEventListener('DOMContentLoaded', activateMobileFlexboxLayout);
        
        // Активуємо при зміні розміру екрану
        window.addEventListener('resize', activateMobileFlexboxLayout);
        
        // Активуємо зразу
        activateMobileFlexboxLayout();
        
        // Debug функції для дашборду
        setTimeout(() => {
            console.log('🔍 Debug: Доступні функції для тестування дашборду:');
            console.log('testShowDashboard() - форсовано показати дашборд');
            console.log('window.dashboardController - перевірити чи створений DashboardController');
            console.log('DashboardController - клас для ручного створення');
            
            // Material Design Debug функції
            console.log('🎨 Material Design Debug функції:');
            console.log('restartDashboardCounters() - перезапуск анімованих лічильників');
            console.log('shimmerDashboard() - shimmer ефект на картках');
            console.log('addDashboardParticles() - додати нові частинки');
            console.log('simulateDashboardHover() - симуляція hover ефекту');
            
            // Глобальна функція для швидкої діагностики
            window.diagnosteDashboard = function() {
                const info = {
                    dashboardController: !!window.dashboardController,
                    DashboardController: typeof DashboardController,
                    userDashboardGrid: !!document.getElementById('user-dashboard-grid'),
                    dashboardGridClasses: document.getElementById('user-dashboard-grid')?.className,
                    bodyClasses: document.body.className,
                    supabase: !!window.supabase,
                    materialAnimations: !!window.materialDashboardAnimations,
                    dashboardCards: document.querySelectorAll('.dashboard-card').length,
                    particles: document.querySelectorAll('.particle').length
                };
                console.table(info);
                return info;
            };
            
            // Функція для демонстрації всіх анімацій
            window.demoDashboardAnimations = function() {
                console.log('🎪 Демонстрація всіх Material Design анімацій...');
                
                setTimeout(() => restartDashboardCounters(), 0);
                setTimeout(() => shimmerDashboard(), 2500);
                setTimeout(() => addDashboardParticles(), 5000);
                setTimeout(() => simulateDashboardHover(), 7500);
                
                console.log('✨ Демо запущено! Подивіться на дашборд протягом наступних 10 секунд.');
            };
        }, 2000);
    </script>

</body>
</html>
