// Lead Submission Logic

let currentStep = 1;
let selectedService = '';

// Check if freelancer stats exist in localStorage, if not initialize
if (!localStorage.getItem('freelancerLeads')) {
    localStorage.setItem('freelancerLeads', JSON.stringify([]));
}

function nextStep(step) {
    if (step === 2) {
        // Validate Step 1
        const name = document.getElementById('freelancerName').value;
        const mobile = document.getElementById('freelancerMobile').value;

        if (!name || !mobile) {
            alert('Please fill in required fields');
            return;
        }

        // Save freelancer info for next time
        localStorage.setItem('freelancerInfo', JSON.stringify({
            name: name,
            mobile: mobile,
            whatsapp: document.getElementById('freelancerWhatsapp').value
        }));
    }

    if (step === 3) {
        // Validate Step 2
        const customService = document.getElementById('customService').value;
        if (!selectedService && !customService) {
            alert('Please select a service or enter one');
            return;
        }
    }

    showStep(step);
}

function prevStep(step) {
    showStep(step);
}

function showStep(step) {
    // Hide all steps
    document.querySelectorAll('.step-container').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.progress-step').forEach(el => el.classList.remove('active', 'completed'));

    // Show current step
    document.getElementById(`step-${step}`).classList.add('active');

    // Update progress
    for (let i = 1; i <= step; i++) {
        const pStep = document.getElementById(`progress-1`).parentElement.children[i - 1]; // specific selection logic
        if (i === step) pStep.classList.add('active');
        if (i < step) pStep.classList.add('completed');
    }

    // Re-select step indicators strictly
    for (let i = 1; i <= 3; i++) {
        const el = document.getElementById(`progress-${i}`);
        if (i < step) {
            el.classList.add('completed');
            el.classList.remove('active');
        } else if (i === step) {
            el.classList.add('active');
            el.classList.remove('completed');
        } else {
            el.classList.remove('active', 'completed');
        }
    }

    currentStep = step;
}

function selectService(element, serviceName) {
    // Remove selected class from all
    document.querySelectorAll('.service-option').forEach(el => el.classList.remove('selected'));
    // Add to clicked
    element.classList.add('selected');
    selectedService = serviceName;
    document.getElementById('customService').value = ''; // Clear custom if selected
}

// Prefill Freelancer Info if available
window.addEventListener('DOMContentLoaded', () => {
    const savedInfo = localStorage.getItem('freelancerInfo');
    if (savedInfo) {
        const info = JSON.parse(savedInfo);
        document.getElementById('freelancerName').value = info.name || '';
        document.getElementById('freelancerMobile').value = info.mobile || '';
        document.getElementById('freelancerWhatsapp').value = info.whatsapp || '';
    }
});

// Pincode API
async function fetchPincodeDetails() {
    const pincode = document.getElementById('pincode').value;
    if (pincode.length === 6) {
        document.getElementById('pincodeLoader').style.display = 'flex';
        try {
            const response = await fetch(`https://api.postalpincode.in/pincode/${pincode}`);
            const data = await response.json();

            if (data[0].Status === 'Success') {
                const details = data[0].PostOffice[0];
                document.getElementById('city').value = details.Block || details.Name;
                document.getElementById('district').value = details.District;
                document.getElementById('state').value = details.State;
                document.getElementById('pincodeError').classList.add('hidden');
            } else {
                document.getElementById('pincodeError').classList.remove('hidden');
                document.getElementById('city').value = '';
                document.getElementById('district').value = '';
                document.getElementById('state').value = '';
            }
        } catch (e) {
            console.error(e);
        }
        document.getElementById('pincodeLoader').style.display = 'none';
    }
}

// Form Submission
document.getElementById('leadForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const leadData = {
        id: Date.now().toString(),
        freelancer: {
            name: document.getElementById('freelancerName').value,
            mobile: document.getElementById('freelancerMobile').value,
            whatsapp: document.getElementById('freelancerWhatsapp').value
        },
        service: selectedService || document.getElementById('customService').value,
        customer: {
            name: document.getElementById('customerName').value,
            mobile: document.getElementById('customerMobile').value,
            whatsapp: document.getElementById('customerWhatsapp').value,
            address: {
                pincode: document.getElementById('pincode').value,
                city: document.getElementById('city').value,
                district: document.getElementById('district').value,
                state: document.getElementById('state').value
            }
        },
        status: 'Pending',
        timestamp: new Date().toISOString()
    };

    // Save to LocalStorage
    const leads = JSON.parse(localStorage.getItem('freelancerLeads') || '[]');
    leads.push(leadData);
    localStorage.setItem('freelancerLeads', JSON.stringify(leads));

    alert('Lead Submitted Successfully!');
    window.location.href = 'dashboard.html';
});
