// assets/js/utama.js
// Script utama untuk website Linkbit.net.id
// dibuat oleh Bintang Bradhiena Surya
// Setiap pencurian adalah tindakan kriminal dan akan ditindak sesuai hukum yang berlaku. dan dosa juga sih
// Jangan asal comot ya, minta izin dulu :)

// ========== INISIALISASI AOS DAN FUNGSI UMUM ==========
        // Inisialisasi AOS
        AOS.init({
            duration: 800,
            once: true,
            offset: 100
        });
        
        // NOTE: Dark mode toggle sudah ditangani di header.php
        // Jangan duplikat logic di sini
        
        // Mobile Menu Toggle (with null check)
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        if (mobileMenuButton) {
            mobileMenuButton.addEventListener('click', function() {
                const menu = document.getElementById('mobile-menu');
                if (menu) {
                    menu.classList.toggle('hidden');
                }
            });
        }
        
        // Speed Bar Animation
        document.addEventListener('DOMContentLoaded', function() {
            const speedBars = document.querySelectorAll('.speed-fill');
            speedBars.forEach(bar => {
                const speed = bar.getAttribute('data-speed');
                bar.style.width = speed + '%';
            });
        });
        
        // Counter Animation
        function animateCounter(elementId, targetValue, duration = 2000) {
            const element = document.getElementById(elementId);
            let startValue = 0;
            const increment = targetValue / (duration / 16); // 60fps
            
            function updateCounter() {
                startValue += increment;
                if (startValue < targetValue) {
                    if (elementId === 'counter3') {
                        element.textContent = startValue.toFixed(1) + '%';
                    } else {
                        element.textContent = Math.floor(startValue);
                    }
                    requestAnimationFrame(updateCounter);
                } else {
                    if (elementId === 'counter3') {
                        element.textContent = targetValue.toFixed(1) + '%';
                    } else {
                        element.textContent = targetValue;
                    }
                }
            }
            
            updateCounter();
        }
        
        // Trigger counter animation when in viewport
        function isElementInViewport(el) {
            const rect = el.getBoundingClientRect();
            return (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                rect.right <= (window.innerWidth || document.documentElement.clientWidth)
            );
        }
        
        let countersAnimated = false;
        
        function checkCounters() {
            const statsSection = document.querySelector('.stats-bg');
            if (isElementInViewport(statsSection) && !countersAnimated) {
                animateCounter('counter1', 2500);
                animateCounter('counter2', 150);
                animateCounter('counter3', 99.9);
                animateCounter('counter4', 98);
                countersAnimated = true;
            }
        }
        
        window.addEventListener('scroll', checkCounters);
        window.addEventListener('load', checkCounters);
        
        // Set current year in footer
        document.getElementById('currentYear').textContent = new Date().getFullYear();
        
        // Close mobile menu when clicking on a link
        document.querySelectorAll('#mobile-menu a').forEach(link => {
            link.addEventListener('click', () => {
                document.getElementById('mobile-menu').classList.add('hidden');
            });
        });
        
        // Smooth scrolling for anchor links
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                if(this.getAttribute('href') === '#') return;
                
                e.preventDefault();
                
                const targetId = this.getAttribute('href');
                if(targetId === '#') return;
                
                const targetElement = document.querySelector(targetId);
                if(targetElement) {
                    window.scrollTo({
                        top: targetElement.offsetTop - 80,
                        behavior: 'smooth'
                    });
                }
            });
        });

        // ========== FORM CEK KETERSEDIAAN JARINGAN ==========
        const btnGunakanLokasi = document.getElementById('btnGunakanlokasi');
        const inputAlamat = document.getElementById('inputAlamat');
        const checkAvailabilityForm = document.getElementById('checkAvailabilityForm');

        if (btnGunakanLokasi) {
            btnGunakanLokasi.addEventListener('click', function(e) {
                e.preventDefault();
                
                if ('geolocation' in navigator) {
                    const originalText = btnGunakanLokasi.innerHTML;
                    btnGunakanLokasi.disabled = true;
                    btnGunakanLokasi.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengambil Lokasi...';
                    
                    navigator.geolocation.getCurrentPosition(
                        function(position) {
                            // Sukses mendapatkan lokasi
                            const latitude = position.coords.latitude;
                            const longitude = position.coords.longitude;
                            const googleMapsLink = `https://maps.google.com/?q=${latitude},${longitude}`;
                            
                            getReverseGeocode(latitude, longitude)
                                .then(function(address) {
                                    const alamatText = `Lokasi saya:\nAlamat: ${address}\n${googleMapsLink}`;
                                    inputAlamat.value = alamatText;
                                    
                                    btnGunakanLokasi.disabled = false;
                                    btnGunakanLokasi.innerHTML = originalText;
                                    
                                    showNotification('Lokasi dan alamat berhasil diambil!', 'success');
                                })
                                .catch(function(error) {
                                    const alamatText = `Lokasi saya:\nKoordinat: ${latitude.toFixed(6)}, ${longitude.toFixed(6)}\n${googleMapsLink}`;
                                    inputAlamat.value = alamatText;
                                    
                                    btnGunakanLokasi.disabled = false;
                                    btnGunakanLokasi.innerHTML = originalText;
                                    
                                    showNotification('Lokasi diambil (alamat tidak tersedia)', 'success');
                                });
                        },
                        function(error) {
                            let errorMessage = 'Gagal mengambil lokasi. ';
                            
                            switch(error.code) {
                                case error.PERMISSION_DENIED:
                                    errorMessage += 'Izin lokasi ditolak oleh browser.';
                                    break;
                                case error.POSITION_UNAVAILABLE:
                                    errorMessage += 'Informasi lokasi tidak tersedia.';
                                    break;
                                case error.TIMEOUT:
                                    errorMessage += 'Waktu tunggu lokasi habis.';
                                    break;
                                default:
                                    errorMessage += 'Terjadi kesalahan yang tidak diketahui.';
                            }
                            
                            // Restore button state
                            btnGunakanLokasi.disabled = false;
                            btnGunakanLokasi.innerHTML = originalText;
                            
                            // Tampilkan error
                            showNotification(errorMessage, 'error');
                        },
                        {
                            enableHighAccuracy: true,
                            timeout: 10000,
                            maximumAge: 0
                        }
                    );
                } else {
                    showNotification('Browser Anda tidak mendukung geolocation.', 'error');
                }
            });
        }

        // Function untuk reverse geocoding menggunakan Nominatim API (OpenStreetMap)
        function getReverseGeocode(latitude, longitude) {
            return fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`, {
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('Gagal mengambil data alamat');
                }
                return response.json();
            })
            .then(function(data) {
                // Prioritas: road/street > house_number > suburb > city
                let address = '';
                
                if (data.address) {
                    const addr = data.address;
                    
                    // Ambil jenis jalan (road, street, path, etc)
                    const road = addr.road || addr.street || addr.path || '';
                    const house = addr.house_number || '';
                    const suburb = addr.suburb || addr.village || addr.town || '';
                    const city = addr.city || addr.county || '';
                    const postcode = addr.postcode || '';
                    
                    // Gabungkan alamat
                    if (road) {
                        address = `${road}${house ? ' No. ' + house : ''}`;
                    } else {
                        address = suburb || city || 'Lokasi tidak dikenal';
                    }
                    
                    if (suburb && suburb !== city && !address.includes(suburb)) {
                        address += `, ${suburb}`;
                    }
                    
                    if (city && !address.includes(city)) {
                        address += `, ${city}`;
                    }
                    
                    if (postcode && !address.includes(postcode)) {
                        address += ` ${postcode}`;
                    }
                }
                
                return address || 'Lokasi tidak dikenal';
            })
            .catch(function(error) {
                console.error('Error reverse geocoding:', error);
                throw error;
            });
        }

        // Handler untuk form submission
        if (checkAvailabilityForm) {
            checkAvailabilityForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Ambil nilai dari form
                const nama = document.getElementById('inputNama').value.trim();
                const noWA = document.getElementById('inputWA').value.trim();
                const alamat = document.getElementById('inputAlamat').value.trim();
                
                // Validasi input
                if (!nama || !noWA || !alamat) {
                    showNotification('Semua field harus diisi!', 'error');
                    return;
                }
                
                // Bersihkan nomor WhatsApp (hanya ambil angka)
                const cleanedWA = noWA.replace(/\D/g, '');
                
                // Validasi nomor WhatsApp (minimal 10 digit)
                if (cleanedWA.length < 10) {
                    showNotification('Nomor WhatsApp tidak valid!', 'error');
                    return;
                }
                
                // Format nomor WA jika belum dimulai dengan 62
                const formattedWA = cleanedWA.startsWith('62') ? cleanedWA : '62' + cleanedWA.slice(cleanedWA.startsWith('0') ? 1 : 0);
                
                // Buat pesan WhatsApp
                const pesan = `Halo Admin,\nSaya ingin cek ketersediaan jaringan.\n\nNama: ${nama}\nNo WA: ${noWA}\nAlamat / Lokasi:\n${alamat}\n\nChat ini dikirim dari website.`;
                
                // Encode pesan untuk URL
                const encodedMessage = encodeURIComponent(pesan);
                
                // Redirect ke WhatsApp
                const waLink = `https://wa.me/6281392120473?text=${encodedMessage}`;
                window.open(waLink, '_blank');
            });
        }

        // Function untuk menampilkan notifikasi
        function showNotification(message, type = 'info') {
            // Buat elemen notifikasi
            const notification = document.createElement('div');
            const bgColor = type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : 'bg-blue-500';
            const icon = type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle';
            
            notification.className = `${bgColor} text-white px-6 py-4 rounded-lg shadow-lg flex items-center gap-3 fixed bottom-5 right-5 z-50 max-w-sm animate-fadeInRight`;
            notification.innerHTML = `
                <i class="fas ${icon}"></i>
                <span>${message}</span>
            `;
            
            document.body.appendChild(notification);
            
            // Hapus notifikasi setelah 3 detik
            setTimeout(function() {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(400px)';
                notification.style.transition = 'all 0.3s ease-out';
                
                setTimeout(function() {
                    notification.remove();
                }, 300);
            }, 3000);
        }

        // Tambahkan CSS untuk animasi notifikasi jika belum ada
        if (!document.querySelector('style[data-notification]')) {
            const style = document.createElement('style');
            style.setAttribute('data-notification', 'true');
            style.textContent = `
                @keyframes fadeInRight {
                    from {
                        opacity: 0;
                        transform: translateX(400px);
                    }
                    to {
                        opacity: 1;
                        transform: translateX(0);
                    }
                }
                .animate-fadeInRight {
                    animation: fadeInRight 0.3s ease-out;
                }
            `;
            document.head.appendChild(style);
        }
// ========== ip publik kamu ==========
fetch('https://api.ipify.org?format=json')
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('public-ip').textContent = data.ip;
                        })
                        .catch(error => {
                            console.error('Error fetching IP address:', error);
                            document.getElementById('public-ip').textContent = 'Unable to fetch IP';
                        }); 

// ========== QONTAK ==========
        const qchatInit = document.createElement('script');
        qchatInit.src = "https://webchat.qontak.com/qchatInitialize.js";
        const qchatWidget = document.createElement('script');
        qchatWidget.src = "https://webchat.qontak.com/js/app.js";
        document.head.prepend(qchatInit);
        document.head.prepend(qchatWidget);
        qchatInit.onload = function() {
            qchatInitialize({
                id: "65800ad1-f63e-4b51-9127-75f2e8cb5ceb",
                code: "4Pfc1yhDoYx1KD0QNEDQVg"
            })
        };
// ========== COOKIE CONSENT POPUP ==========
document.addEventListener('DOMContentLoaded', function() {
    // Cek apakah user sudah accept cookie
    const cookieAccepted = localStorage.getItem('linkbit_cookie_accepted');
    
    if (!cookieAccepted) {
        // Tampilkan cookie consent popup
        setTimeout(showCookieConsent, 1000);
    }
});

function showCookieConsent() {
    // Cek apakah popup sudah ada
    if (document.getElementById('cookie-consent')) {
        return;
    }
    
    // Buat popup container
    const cookiePopup = document.createElement('div');
    cookiePopup.id = 'cookie-consent';
    cookiePopup.className = 'fixed bottom-0 left-0 right-0 z-50 p-4 md:p-6 animate-slideUp';
    cookiePopup.innerHTML = `
        <div class="max-w-4xl mx-auto bg-white rounded-xl shadow-2xl border-l-4 border-primary overflow-hidden">
            <div class="flex flex-col md:flex-row items-center justify-between gap-6 p-6 md:p-8">
                <!-- Content -->
                <div class="flex-1">
                    <div class="flex items-start gap-4">
                        <div class="flex-shrink-0 text-2xl">
                            🍪
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-slate-800 mb-2">
                                Kami Menggunakan Cookie
                            </h3>
                            <p class="text-sm text-slate-600 leading-relaxed">
                                Kami menggunakan cookie untuk meningkatkan pengalaman Anda, menganalisis traffic, dan menampilkan iklan yang relevan. Dengan mengklik "Terima Semua", Anda setuju dengan penggunaan cookie kami.
                                <a href="#" class="text-primary hover:underline font-semibold ml-1">Pelajari lebih lanjut</a>
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Buttons -->
                <div class="flex flex-col sm:flex-row gap-3 w-full md:w-auto flex-shrink-0">
                    <button 
                        id="cookieReject" 
                        class="px-6 py-3 rounded-lg border-2 border-slate-300 text-slate-700 font-semibold hover:bg-slate-100 transition transform hover:scale-105 active:scale-95 whitespace-nowrap"
                    >
                        Tolak
                    </button>
                    <button 
                        id="cookieAccept" 
                        class="px-8 py-3 rounded-lg bg-gradient-to-r from-primary to-primary-light text-white font-semibold hover:shadow-lg transition transform hover:scale-105 active:scale-95 whitespace-nowrap"
                    >
                        <i class="fas fa-check mr-2"></i>Terima Semua
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(cookiePopup);
    
    // Handler untuk Accept button
    document.getElementById('cookieAccept').addEventListener('click', function() {
        // Simpan preferensi cookie
        localStorage.setItem('linkbit_cookie_accepted', 'true');
        localStorage.setItem('linkbit_cookie_analytics', 'true');
        localStorage.setItem('linkbit_cookie_marketing', 'true');
        localStorage.setItem('linkbit_cookie_timestamp', new Date().getTime());
        
        // Tampilkan notifikasi
        showNotification('✓ Terima kasih! Cookie telah diterima.', 'success');
        
        // Tutup popup
        closeCookieConsent();
        
        // Load analytics scripts (Google Analytics, etc)
        loadAnalyticsScripts();
    });
    
    // Handler untuk Reject button
    document.getElementById('cookieReject').addEventListener('click', function() {
        // Simpan preferensi cookie (hanya essential)
        localStorage.setItem('linkbit_cookie_accepted', 'false');
        localStorage.setItem('linkbit_cookie_analytics', 'false');
        localStorage.setItem('linkbit_cookie_marketing', 'false');
        localStorage.setItem('linkbit_cookie_timestamp', new Date().getTime());
        
        // Tampilkan notifikasi
        showNotification('Cookie non-essential ditolak.', 'info');
        
        // Tutup popup
        closeCookieConsent();
    });
}

function closeCookieConsent() {
    const cookiePopup = document.getElementById('cookie-consent');
    
    if (cookiePopup) {
        cookiePopup.style.opacity = '0';
        cookiePopup.style.transform = 'translateY(400px)';
        cookiePopup.style.transition = 'all 0.3s ease-out';
        
        // Hapus elemen setelah animasi selesai
        setTimeout(function() {
            cookiePopup.remove();
        }, 300);
    }
}

function loadAnalyticsScripts() {
    // Load Google Analytics
    const gaScript = document.createElement('script');
    gaScript.async = true;
    gaScript.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID';
    document.head.appendChild(gaScript);
    
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'GA_MEASUREMENT_ID', {
        'anonymize_ip': true
    });
}

// ========== NEWSLETTER POPUP ==========
document.addEventListener('DOMContentLoaded', function() {
    // Cek apakah user sudah menutup popup
    const popupDismissed = localStorage.getItem('linkbit_newsletter_dismissed');
    
    if (!popupDismissed) {
        // Tampilkan popup setelah 3 detik
        setTimeout(showNewsletterPopup, 3000);
    }
});

function showNewsletterPopup() {
    // Buat overlay
    const overlay = document.createElement('div');
    overlay.className = 'fixed inset-0 bg-black bg-opacity-50 z-40 animate-fadeIn';
    overlay.id = 'newsletter-overlay';
    
    // Buat popup container
    const popup = document.createElement('div');
    popup.className = 'fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50 w-full max-w-md animate-slideUp';
    popup.id = 'newsletter-popup';
    popup.innerHTML = `
        <div class="bg-white rounded-2xl shadow-2xl overflow-hidden">
            <!-- Header dengan gradient -->
            <div class="bg-gradient-to-r from-primary to-primary-light p-8 text-white relative overflow-hidden">
                <div class="absolute top-0 right-0 w-40 h-40 bg-white opacity-10 rounded-full -mr-20 -mt-20"></div>
                <div class="relative">
                    <h2 class="text-2xl font-bold mb-2">Dapatkan Penawaran Spesial!</h2>
                    <p class="text-primary-light text-sm">Berlangganan dan dapatkan diskon hingga 25%</p>
                </div>
            </div>
            
            <!-- Content -->
            <div class="p-8">
                <p class="text-slate-600 mb-6 text-center">
                    Jadilah bagian dari komunitas Linkbit dan nikmati berbagai keuntungan eksklusif
                </p>
                
                <!-- Benefits -->
                <div class="space-y-3 mb-8">
                    <div class="flex items-center gap-3">
                        <div class="w-5 h-5 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0">
                            <i class="fas fa-check text-green-600 text-xs"></i>
                        </div>
                        <span class="text-sm text-slate-700">Penawaran eksklusif setiap minggu</span>
                    </div>
                    <div class="flex items-center gap-3">
                        <div class="w-5 h-5 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0">
                            <i class="fas fa-check text-green-600 text-xs"></i>
                        </div>
                        <span class="text-sm text-slate-700">Tips optimasi jaringan gratis</span>
                    </div>
                    <div class="flex items-center gap-3">
                        <div class="w-5 h-5 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0">
                            <i class="fas fa-check text-green-600 text-xs"></i>
                        </div>
                        <span class="text-sm text-slate-700">Akses prioritas fitur baru</span>
                    </div>
                </div>
                
                <!-- Input form -->
                <form id="newsletterForm" class="space-y-4">
                    <div>
                        <input 
                            type="email" 
                            id="newsletterEmail" 
                            placeholder="Masukkan email Anda" 
                            class="w-full px-4 py-3 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition"
                            required
                        >
                    </div>
                    <button 
                        type="submit" 
                        class="w-full bg-gradient-to-r from-primary to-primary-light hover:shadow-lg text-white font-semibold py-3 rounded-lg transition transform hover:scale-105 active:scale-95"
                    >
                        <i class="fas fa-paper-plane mr-2"></i>Berlangganan Sekarang
                    </button>
                </form>
                
                <!-- Close button -->
                <button 
                    id="closeNewsletterPopup" 
                    class="w-full mt-4 text-slate-600 hover:text-slate-800 font-medium py-2 transition"
                >
                    Tutup
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(overlay);
    document.body.appendChild(popup);
    
    // Handler untuk close button
    document.getElementById('closeNewsletterPopup').addEventListener('click', closeNewsletterPopup);
    
    // Handler untuk overlay click
    overlay.addEventListener('click', closeNewsletterPopup);
    
    // Handler untuk form submission
    document.getElementById('newsletterForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const email = document.getElementById('newsletterEmail').value.trim();
        
        if (!email) {
            showNotification('Email tidak boleh kosong!', 'error');
            return;
        }
        
        // Validasi email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            showNotification('Format email tidak valid!', 'error');
            return;
        }
        
        // Simpan email ke localStorage (atau kirim ke backend)
        const subscribers = JSON.parse(localStorage.getItem('linkbit_subscribers') || '[]');
        
        if (!subscribers.includes(email)) {
            subscribers.push(email);
            localStorage.setItem('linkbit_subscribers', JSON.stringify(subscribers));
        }
        
        // Tampilkan success notification
        showNotification('✨ Terima kasih! Cek email Anda untuk konfirmasi.', 'success');
        
        // Close popup
        closeNewsletterPopup();
    });
}

function closeNewsletterPopup() {
    const overlay = document.getElementById('newsletter-overlay');
    const popup = document.getElementById('newsletter-popup');
    
    if (overlay) {
        overlay.style.opacity = '0';
        overlay.style.transition = 'opacity 0.3s ease-out';
    }
    
    if (popup) {
        popup.style.opacity = '0';
        popup.style.transform = 'translate(-50%, -50%) scale(0.95)';
        popup.style.transition = 'all 0.3s ease-out';
    }
    
    // Hapus elemen setelah animasi selesai
    setTimeout(function() {
        if (overlay) overlay.remove();
        if (popup) popup.remove();
    }, 300);
    
    // Tandai bahwa user sudah menutup popup (valid selama 1 hari)
    localStorage.setItem('linkbit_newsletter_dismissed', 'true');
    
    // Reset setelah 24 jam
    setTimeout(function() {
        localStorage.removeItem('linkbit_newsletter_dismissed');
    }, 24 * 60 * 60 * 1000);
}

// Tambahkan CSS animasi jika belum ada
if (!document.querySelector('style[data-popup-animation]')) {
    const style = document.createElement('style');
    style.setAttribute('data-popup-animation', 'true');
    style.textContent = `
        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }
        
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translate(-50%, -40%);
            }
            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }
        
        .animate-fadeIn {
            animation: fadeIn 0.3s ease-out;
        }
        
        .animate-slideUp {
            animation: slideUp 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        }
    `;
    document.head.appendChild(style);
}
