// Age verification modal functions function confirmAge() { console.log('✅ Age confirmed - setting cookie and closing modal'); // Set age verification cookie for 30 days const expirationDate = new Date(); expirationDate.setTime(expirationDate.getTime() + (30 * 24 * 60 * 60 * 1000)); document.cookie = `ageVerified=true; expires=${expirationDate.toUTCString()}; path=/; SameSite=Lax`; // Also store in localStorage as backup localStorage.setItem('ageVerified', 'true'); localStorage.setItem('ageVerifiedDate', new Date().toISOString()); // Close modal const modal = document.getElementById('ageModal'); if (modal) { modal.style.display = 'none'; } } // Check if age verification is needed function checkAgeVerification() { // Check cookie first const cookies = document.cookie.split(';'); const ageVerifiedCookie = cookies.find(cookie => cookie.trim().startsWith('ageVerified=')); if (ageVerifiedCookie && ageVerifiedCookie.includes('true')) { console.log('✅ Age verified via cookie'); return true; } // Check localStorage as backup const ageVerified = localStorage.getItem('ageVerified'); const ageVerifiedDate = localStorage.getItem('ageVerifiedDate'); if (ageVerified === 'true' && ageVerifiedDate) { const verifiedDate = new Date(ageVerifiedDate); const now = new Date(); const daysDiff = (now - verifiedDate) / (1000 * 60 * 60 * 24); if (daysDiff < 30) { console.log('✅ Age verified via localStorage'); // Restore cookie const expirationDate = new Date(); expirationDate.setTime(expirationDate.getTime() + (30 * 24 * 60 * 60 * 1000)); document.cookie = `ageVerified=true; expires=${expirationDate.toUTCString()}; path=/; SameSite=Lax`; return true; } } console.log('❌ Age verification required'); return false; } function toggleModalLanguageDropdown() { console.log('🌍 Modal language dropdown toggled'); const dropdown = document.getElementById('modalLanguageDropdown'); if (dropdown) { const isVisible = dropdown.style.display === 'block'; dropdown.style.display = isVisible ? 'none' : 'block'; } } function selectModalLanguage(lang) { console.log('🌍 Modal language selected:', lang); const languageData = { 'en': { flag: 'https://flagcdn.com/w20/us.png', alt: 'US', name: 'English' }, 'tr': { flag: 'https://flagcdn.com/w20/tr.png', alt: 'TR', name: 'English' }, 'fr': { flag: 'https://flagcdn.com/w20/fr.png', alt: 'FR', name: 'Français' }, 'de': { flag: 'https://flagcdn.com/w20/de.png', alt: 'DE', name: 'Deutsch' }, 'it': { flag: 'https://flagcdn.com/w20/it.png', alt: 'IT', name: 'Italiano' }, 'nl': { flag: 'https://flagcdn.com/w20/nl.png', alt: 'NL', name: 'Nederlands' } }; // Update current language display const currentFlag = document.getElementById('modalCurrentFlag'); const currentText = document.getElementById('modalLanguageText'); if (currentFlag && currentText && languageData[lang]) { currentFlag.src = languageData[lang].flag; currentFlag.alt = languageData[lang].alt; currentText.textContent = languageData[lang].name; } // Update global language window.DETECTED_LANGUAGE = lang; // Update modal content with new language updateAgeModalContent(lang); // Close dropdown const dropdown = document.getElementById('modalLanguageDropdown'); if (dropdown) { dropdown.style.display = 'none'; } // Update active state document.querySelectorAll('#modalLanguageDropdown .language-option').forEach(opt => { opt.classList.remove('active'); }); const activeOption = document.querySelector(`#modalLanguageDropdown [data-lang="${lang}"]`); if (activeOption) { activeOption.classList.add('active'); } } function loginFromModal() { console.log('🔐 Login button clicked from modal - redirecting to /login'); // Don't close the modal, just redirect to login // The age verification will be checked again when they return window.location.href = '/login'; } function updateAgeModalContent(lang) { const translations = { 'en': { title: 'This site is for adults only!', description: 'By entering this website, I confirm that I am 18 years of age or older and I agree to the Terms of Service.', language: 'English', login: 'Login', confirm: 'I am 18 or older' }, 'tr': { title: 'This site is for adults only!', description: 'Bu web sitesine girerek 18 yaşında veya daha büyük olduğumu kabul ediyor ve Hizmet Şartlarını kabul ediyorum.', language: 'English', login: 'Login', confirm: 'I am 18 or older' }, 'fr': { title: 'Ce site est réservé aux adultes!', description: 'En entrant sur ce site, je confirme que j\'ai 18 ans ou plus et que j\'accepte les Conditions d\'utilisation.', language: 'Français', login: 'Connexion', confirm: 'J\'ai 18 ans ou plus' }, 'de': { title: 'Diese Seite ist nur für Erwachsene!', description: 'Mit dem Betreten dieser Website bestätige ich, dass ich 18 Jahre oder älter bin und die Nutzungsbedingungen akzeptiere.', language: 'Deutsch', login: 'Anmelden', confirm: 'Ich bin 18 oder älter' }, 'it': { title: 'Questo sito è solo per adulti!', description: 'Entrando in questo sito, confermo di avere 18 anni o più e di accettare i Termini di servizio.', language: 'Italiano', login: 'Accesso', confirm: 'Ho 18 anni o più' }, 'nl': { title: 'Deze site is alleen voor volwassenen!', description: 'Door deze website te betreden, bevestig ik dat ik 18 jaar of ouder ben en akkoord ga met de Servicevoorwaarden.', language: 'Nederlands', login: 'Inloggen', confirm: 'Ik ben 18 of ouder' } }; const t = translations[lang] || translations['en']; // Update modal content const modal = document.querySelector('#ageModal .modal-content'); if (modal) { modal.innerHTML = `
${t.description}
`; } } // Close dropdown when clicking outside document.addEventListener('click', function(event) { const selector = document.getElementById('modalLanguageSelector'); const dropdown = document.getElementById('modalLanguageDropdown'); if (selector && dropdown && !selector.contains(event.target)) { dropdown.style.display = 'none'; } }); // Authentication functions - redirect to login page instead of showing modal function showLoginModal() { console.log('🔐 Redirecting to login page instead of showing modal'); window.location.href = '/login'; } function closeLoginModal() { console.log('🔐 Closing login modal'); document.getElementById('loginModal').style.display = 'none'; // Clear form document.getElementById('quickLoginForm').reset(); document.getElementById('quickLoginError').style.display = 'none'; } // Quick login form handler document.addEventListener('DOMContentLoaded', () => { const quickLoginForm = document.getElementById('quickLoginForm'); if (quickLoginForm) { quickLoginForm.addEventListener('submit', async (e) => { e.preventDefault(); const btn = document.getElementById('quickLoginBtn'); const spinner = document.getElementById('quickLoginSpinner'); const text = document.getElementById('quickLoginText'); const errorDiv = document.getElementById('quickLoginError'); const identifier = document.getElementById('quickIdentifier').value.trim(); const password = document.getElementById('quickPassword').value; // Clear previous errors errorDiv.style.display = 'none'; if (!identifier || !password) { errorDiv.textContent = 'Please fill in all fields'; errorDiv.style.display = 'block'; return; } // Show loading btn.disabled = true; spinner.style.display = 'inline-block'; text.textContent = 'Signing in...'; try { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ identifier, password }) }); const data = await response.json(); if (data.success) { // Store token and user data localStorage.setItem('authToken', data.data.token); localStorage.setItem('user', JSON.stringify(data.data.user)); console.log('✅ Login successful'); // Close modal closeLoginModal(); // Update UI updateAuthUI(); // Show success message showNotification('Login successful!', 'success'); } else { errorDiv.textContent = data.message || 'Login failed'; errorDiv.style.display = 'block'; } } catch (error) { console.error('Login error:', error); errorDiv.textContent = 'Network error. Please try again.'; errorDiv.style.display = 'block'; } finally { btn.disabled = false; spinner.style.display = 'none'; text.textContent = 'Sign In'; } }); } }); // USER PROFILE FUNCTIONS function showProfile() { console.log('📱 Profile clicked'); toggleUserDropdown(); // Close dropdown document.getElementById('profileModal').style.display = 'block'; loadUserProfile(); } function showSettings() { console.log('⚙️ Settings clicked'); toggleUserDropdown(); // Close dropdown alert('Settings page coming soon!'); } function showPremium() { console.log('👑 Premium clicked'); toggleUserDropdown(); // Close dropdown window.location.href = '/pricing'; } function logoutUser() { console.log('🚪 Logout clicked'); toggleUserDropdown(); // Close dropdown if (confirm('Are you sure you want to logout?')) { logout(); } } // Notification function function showNotification(message, type = 'info') { const notification = document.createElement('div'); notification.style.cssText = ` position: fixed; top: 20px; right: 20px; padding: 15px 20px; border-radius: 8px; color: white; font-weight: 500; z-index: 10000; animation: slideIn 0.3s ease; ${type === 'success' ? 'background: linear-gradient(135deg, #4CAF50, #45a049);' : 'background: linear-gradient(135deg, #4a90e2, #357abd);'} `; notification.innerHTML = ` ${message}`; document.body.appendChild(notification); setTimeout(() => { if (notification.parentNode) { notification.parentNode.removeChild(notification); } }, 3000); } function goToPricing() { window.location.href = '/pricing'; } async function logout() { try { const token = localStorage.getItem('authToken'); if (token) { await fetch('/api/auth/logout', { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } }); } } catch (error) { console.error('Logout error:', error); } finally { // Clear local storage localStorage.removeItem('authToken'); localStorage.removeItem('user'); // Update UI updateAuthUI(); // Redirect to home window.location.reload(); } } function updateAuthUI() { console.log('🔄 updateAuthUI called'); const loginIcon = document.getElementById('loginIcon'); const userProfile = document.getElementById('userProfile'); const token = localStorage.getItem('authToken'); console.log('🔍 Auth UI check:', { hasToken: !!token, loginIcon: !!loginIcon, userProfile: !!userProfile }); // Clear any invalid tokens first if (token && !isValidJWTFormat(token)) { console.log('❌ Invalid token format, clearing auth data'); clearInvalidAuthData(); if (loginIcon) loginIcon.style.display = 'block'; if (userProfile) userProfile.style.display = 'none'; return; } const user = JSON.parse(localStorage.getItem('user') || '{}'); console.log('👤 User data:', user); if (token && isValidJWTFormat(token) && user.id) { console.log('✅ User is authenticated, showing profile'); // User is logged in - show profile, hide login icon if (loginIcon) { loginIcon.style.display = 'none'; console.log('🔒 Login icon hidden'); } if (userProfile) { userProfile.style.display = 'block'; console.log('👤 User profile shown'); } // Update username in profile const usernameDisplay = document.getElementById('usernameDisplay'); if (usernameDisplay) { usernameDisplay.textContent = user.username || 'User'; console.log('📝 Username updated:', user.username); } // Update dropdown details const dropdownUsername = document.getElementById('dropdownUsername'); if (dropdownUsername) { dropdownUsername.textContent = user.username || 'User'; } const dropdownEmail = document.getElementById('dropdownEmail'); if (dropdownEmail) { dropdownEmail.textContent = user.email || 'user@example.com'; } console.log('✅ User profile UI updated successfully'); } else { console.log('❌ User not authenticated, showing login icon'); // User is not logged in - show login icon, hide profile if (loginIcon) loginIcon.style.display = 'block'; if (userProfile) userProfile.style.display = 'none'; } } function isValidJWTFormat(token) { if (!token || typeof token !== 'string') { return false; } const parts = token.split('.'); if (parts.length !== 3) { return false; } // Check if each part is base64-like (basic validation) for (let part of parts) { if (!part || part.length === 0) { return false; } } return true; } function clearInvalidAuthData() { console.log('Clearing invalid authentication data from localStorage'); localStorage.removeItem('authToken'); localStorage.removeItem('user'); localStorage.removeItem('refreshToken'); } async function loadUserProfile() { const token = localStorage.getItem('authToken'); if (!token) return; // Validate token format before making request if (!isValidJWTFormat(token)) { console.log('Invalid token format detected, clearing auth data'); clearInvalidAuthData(); updateAuthUI(); return; } try { const response = await fetch('/api/auth/profile', { headers: { 'Authorization': `Bearer ${token}` } }); if (response.ok) { const data = await response.json(); if (data.success) { // Update stored user data localStorage.setItem('user', JSON.stringify(data.data)); updateAuthUI(); // Update profile modal content updateProfileModal(data.data); } } else if (response.status === 401) { // Token is invalid, logout console.log('Token validation failed on server, clearing auth data'); clearInvalidAuthData(); updateAuthUI(); } } catch (error) { console.error('Failed to load user profile:', error); // If there's a network error and token is invalid format, clear it if (!isValidJWTFormat(token)) { clearInvalidAuthData(); updateAuthUI(); } } } function updateProfileModal(userData) { const profileBody = document.querySelector('.profile-body'); profileBody.innerHTML = `