/**
 * Main Script - Profice Website
 * All API calls go through server-side PHP
 * 
 * @version 2.1.0
 */

document.addEventListener("DOMContentLoaded", function() {
    
    // ==========================================
    // SOUND VISUALIZATION ANIMATION
    // ==========================================
    
    function initSoundVisualization() {
        const soundVisualization = document.getElementById('soundVisualization');
        const demoPhoneBtn = document.getElementById('demoPhoneBtn');
        
        if (soundVisualization && demoPhoneBtn) {
            // Start animation on hover
            demoPhoneBtn.addEventListener('mouseenter', () => {
                soundVisualization.classList.add('active');
            });
            
            demoPhoneBtn.addEventListener('mouseleave', () => {
                soundVisualization.classList.remove('active');
            });
            
            // Toggle animation on click/touch
            demoPhoneBtn.addEventListener('click', (e) => {
                e.preventDefault();
                soundVisualization.classList.toggle('active');
                
                // Simulate call action after a brief delay
                setTimeout(() => {
                    window.location.href = demoPhoneBtn.href;
                }, 500);
            });
            
            // Touch support for mobile
            demoPhoneBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                soundVisualization.classList.add('active');
            });
            
            demoPhoneBtn.addEventListener('touchend', () => {
                setTimeout(() => {
                    soundVisualization.classList.remove('active');
                }, 1000);
            });
        }
    }
    
    initSoundVisualization();
    
    // Use absolute path from site root
    const API_ENDPOINT = '/scripts/add/send.php';
    const isLocalFile = window.location.protocol === 'file:';
    
    // ==========================================
    // 1. SMOOTH SCROLLING
    // ==========================================
    
    function initSmoothScrolling() {
        document.querySelectorAll('a[href^="#"]').forEach(link => {
            link.addEventListener('click', function(e) {
                const targetId = this.getAttribute('href');
                if (targetId === '#') return;
                
                const targetElement = document.querySelector(targetId);
                if (targetElement) {
                    e.preventDefault();
                    const header = document.querySelector('.top-banner');
                    const headerHeight = header ? header.offsetHeight : 90;
                    
                    window.scrollTo({
                        top: targetElement.offsetTop - headerHeight - 20,
                        behavior: 'smooth'
                    });
                    
                    history.pushState(null, null, targetId);
                }
            });
        });
    }
    
    initSmoothScrolling();
    
    // ==========================================
    // 1.5. BUTTON NAVIGATION TO DEMO SECTION
    // ==========================================
    
    function initButtonNavigation() {
        const kiPhoneBtn = document.getElementById('kiPhoneBtn');
        const chatBtn = document.getElementById('chatBtn');
        const demoSection = document.getElementById('demo-section');
        
        if (demoSection) {
            const scrollToDemo = () => {
                const header = document.querySelector('.top-banner');
                const headerHeight = header ? header.offsetHeight : 90;
                
                window.scrollTo({
                    top: demoSection.offsetTop - headerHeight - 20,
                    behavior: 'smooth'
                });
            };
            
            if (kiPhoneBtn) {
                kiPhoneBtn.addEventListener('click', scrollToDemo);
            }
            
            if (chatBtn) {
                chatBtn.addEventListener('click', scrollToDemo);
            }
        }
    }
    
    initButtonNavigation();
    
    // ==========================================
    // 1.6. PHONE CALL FUNCTIONALITY
    // ==========================================
    
    function initPhoneCallFunctionality() {
        const demoPhoneBtn = document.getElementById('demoPhoneBtn');
        
        if (demoPhoneBtn) {
            demoPhoneBtn.addEventListener('click', function(e) {
                // Check if mobile device
                const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
                
                if (!isMobile) {
                    e.preventDefault();
                    
                    // Show desktop fallback message
                    const phoneNumber = '+49 123 456789';
                    const message = `Bitte rufen Sie uns direkt an: ${phoneNumber}\n\nOder nutzen Sie das Kontaktformular für eine schriftliche Anfrage.`;
                    
                    // Create a custom modal instead of alert
                    const modal = document.createElement('div');
                    modal.style.cssText = `
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0,0,0,0.5);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 10000;
                        font-family: system-ui, -apple-system, sans-serif;
                    `;
                    
                    modal.innerHTML = `
                        <div style="
                            background: white;
                            padding: 2rem;
                            border-radius: 12px;
                            max-width: 400px;
                            margin: 1rem;
                            text-align: center;
                            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
                        ">
                            <h3 style="margin: 0 0 1rem 0; color: #333;">Telefonnummer</h3>
                            <p style="margin: 0 0 1.5rem 0; color: #666; line-height: 1.6;">${message}</p>
                            <button style="
                                background: #10b981;
                                color: white;
                                border: none;
                                padding: 0.75rem 1.5rem;
                                border-radius: 6px;
                                cursor: pointer;
                                font-size: 1rem;
                            ">OK</button>
                        </div>
                    `;
                    
                    document.body.appendChild(modal);
                    
                    // Close modal on click
                    modal.addEventListener('click', function(e) {
                        if (e.target === modal || e.target.tagName === 'BUTTON') {
                            document.body.removeChild(modal);
                        }
                    });
                    
                    // Auto-close after 5 seconds
                    setTimeout(() => {
                        if (document.body.contains(modal)) {
                            document.body.removeChild(modal);
                        }
                    }, 5000);
                }
            });
        }
    }
    
    initPhoneCallFunctionality();
    
    // ==========================================
    // 2. MENU TOGGLE (REMOVED)
    // ==========================================
    
    // Menu toggle functionality has been removed

    // ==========================================
    // 3. LOGIN BUTTON (REMOVED)
    // ==========================================
    
    // Login button functionality has been removed

    // ==========================================
    // 4. FORM SUBMISSION
    // ==========================================
    
    const contactForm = document.getElementById('contactForm');
    const successMessage = document.getElementById('successMessage');

    if (contactForm) {
        contactForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            const getValue = (id) => {
                const el = document.getElementById(id);
                return el ? el.value : '';
            };

            const serviceSelect = document.getElementById('service');
            const selectedServiceText = serviceSelect ? 
                serviceSelect.options[serviceSelect.selectedIndex].text : 'Dienstleistung';

            const formData = {
                type: 'contact',
                name: getValue('name'),
                organisation: getValue('organisation'),
                contact: getValue('contact'),
                service: getValue('service'),
                budget: getValue('budget'),
                description: getValue('description')
            };
          
            // Always store locally for dashboard
            try {
                const localLead = {
                    id: Date.now(),
                    datum: new Date().toLocaleDateString('de-DE'),
                    dienstleistung: selectedServiceText,
                    status: 'open',
                    statusText: 'Offen',
                    description: formData.description
                };
                const existingLeads = JSON.parse(localStorage.getItem('myLeads') || '[]');
                existingLeads.unshift(localLead);
                localStorage.setItem('myLeads', JSON.stringify(existingLeads.slice(0, 100)));
            } catch (err) {}

            // Send to API if not local file
            if (!isLocalFile) {
                try {
                    const response = await fetch(API_ENDPOINT, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(formData)
                    });
                    const result = await response.json();
                    
                    if (!result.success) {
                        alert('Fehler beim Senden: ' + (result.message || 'Unbekannter Fehler'));
                        return;
                    }
                } catch (error) {
                    alert('Netzwerkfehler beim Senden des Formulars');
                    return;
                }
            }

            // Show success
            contactForm.style.display = 'none';
            if (successMessage) successMessage.classList.add('show');
            contactForm.reset();
        });
    }
});