/**
 * Main Script - Profice Website
 * All API calls go through server-side PHP
 * Includes fallback for local file access (no server)
 * 
 * @version 2.1.0
 */

document.addEventListener("DOMContentLoaded", function() {
    
    // 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();
    
    // ==========================================
    // 2. MENU TOGGLE
    // ==========================================
    
    const menuToggle = document.getElementById('menuToggle');
    const slideMenu = document.getElementById('slideMenu');
    const overlay = document.getElementById('overlay');

    if (menuToggle && slideMenu && overlay) {
        const toggleMenu = () => {
            menuToggle.classList.toggle('active');
            slideMenu.classList.toggle('active');
            overlay.classList.toggle('active');
        };
        menuToggle.addEventListener('click', toggleMenu);
        overlay.addEventListener('click', toggleMenu);
    }

    // ==========================================
    // 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();
        });
    }
});