﻿// public_html/js/home.js

// Check Auth & Personalization
let token = localStorage.getItem('token');
const userName = localStorage.getItem('userName');
const userId = localStorage.getItem('userId');

if (userName) document.getElementById('greeting').innerText = `┘à╪▒╪¡╪¿╪º┘ï╪î ${userName.split(' ')[0]} ≡ƒæï`;

// ≡ƒƒó Fetch Pricing Settings
let pricingConfig = null;
async function fetchPricingConfig() {
    try {
        const res = await fetch(`${API_URL}/api/orders/price-config`, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        if (res.ok) {
            pricingConfig = await res.json();
            console.log('≡ƒÆ░ Pricing Loaded:', pricingConfig);
        }
    } catch (e) { console.error('Error loading pricing', e); }
}
if (token) fetchPricingConfig();

// ≡ƒù║∩╕Å Map Initialization & Modal Logic
let map, currentSelectionMode, mapInitialized = false;

function openMapModal(mode) {
    currentSelectionMode = mode;
    const title = mode === 'pickup' ? '╪¬╪¡╪»┘è╪» ┘à┘ê┘é╪╣ ╪º┘ä╪º╪│╪¬┘ä╪º┘à' : '╪¬╪¡╪»┘è╪» ┘ê╪¼┘ç╪⌐ ╪º┘ä╪¬╪│┘ä┘è┘à';
    document.getElementById('modalTitle').innerText = title;

    const modalEl = document.getElementById('locationPickerModal');
    const modal = new bootstrap.Modal(modalEl);
    modal.show();

    // Refresh map on modal show
    if (!mapInitialized) {
        setTimeout(initMap, 400);
    } else {
        setTimeout(() => map.invalidateSize(), 400);
    }
}

function initMap() {
    if (mapInitialized) return;
    try {
        // ≡ƒƒó Use 'pickerMap' ID
        map = L.map('pickerMap', { zoomControl: false, attributionControl: false }).setView([15.5007, 32.5599], 13);

        const darkLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { maxZoom: 19 });
        const googleHybrid = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
            maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'], attribution: 'Google'
        }).addTo(map);

        L.control.layers({ "┘é┘à╪▒ ╪╡┘å╪º╪╣┘è ≡ƒ¢░∩╕Å": googleHybrid, "╪º┘ä┘ê╪╢╪╣ ╪º┘ä┘ä┘è┘ä┘è ≡ƒîÖ": darkLayer }, null, { position: 'topright' }).addTo(map);

        mapInitialized = true;
        setTimeout(locateMe, 500);
    } catch (err) {
        console.error('Map Init Error:', err);
        alert('┘ü╪┤┘ä ╪¬┘ç┘è╪ª╪⌐ ╪º┘ä╪«╪▒┘è╪╖╪⌐╪î ┘è╪▒╪¼┘ë ╪º┘ä┘à╪¡╪º┘ê┘ä╪⌐ ┘à╪▒╪⌐ ╪ú╪«╪▒┘ë');
    }
}

function confirmLocationSelection() {
    const center = map.getCenter();
    const mode = currentSelectionMode;

    document.getElementById(`${mode}-lat`).value = center.lat;
    document.getElementById(`${mode}-lng`).value = center.lng;
    document.getElementById(`${mode}-addr`).value = `┘à┘ê┘é╪╣ ┘à╪¡╪»╪» (${center.lat.toFixed(4)}, ${center.lng.toFixed(4)})`;

    // Auto reverse geocode for better UI
    fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${center.lat}&lon=${center.lng}`)
        .then(res => res.json())
        .then(data => {
            if (data.display_name) {
                const addr = data.address.road || data.address.suburb || data.display_name.split(',')[0];
                document.getElementById(`${mode}-addr`).value = addr;
            }
        }).catch(() => { });

    bootstrap.Modal.getInstance(document.getElementById('locationPickerModal')).hide();
}

function locateMe() {
    if (!navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(
        (pos) => map.setView([pos.coords.latitude, pos.coords.longitude], 16),
        (err) => console.log('Geolocation disabled/failed'),
        { enableHighAccuracy: true }
    );
}

// ≡ƒƒó Utils
function calculatePrice() {
    // Basic Client-Side Estimation
    const type = document.getElementById('distance-type').value;
    const priceInput = document.getElementById('price');
    if (type === 'short') priceInput.value = 3000;
    else if (type === 'medium') priceInput.value = 6000;
    else if (type === 'long') priceInput.value = 10000;
}

function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = (e) => {
            document.getElementById('img-preview').classList.remove('d-none');
            document.getElementById('img-preview').querySelector('img').src = e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function clearImage() {
    document.getElementById('parcel-image').value = '';
    document.getElementById('img-preview').classList.add('d-none');
}

// ≡ƒû╝∩╕Å Client-Side Compression using browser-image-compression
async function compressImage(file) {
    const options = {
        maxSizeMB: 0.5,          // Max size in MB (very efficient)
        maxWidthOrHeight: 1280,  // Good for mobile screens
        useWebWorker: true,      // Run in background to avoid freezing UI
        fileType: 'image/jpeg'
    };

    try {
        const compressedFile = await imageCompression(file, options);
        // Convert Blob to Base64 for the backend
        return await imageCompression.getDataUrlFromFile(compressedFile);
    } catch (error) {
        console.error('Compression Error:', error);
        return await imageCompression.getDataUrlFromFile(file);
    }
}

// ≡ƒÜÇ Validation & Submission
function validateOrder() {
    const pLat = document.getElementById('pickup-lat').value;
    const dLat = document.getElementById('dropoff-lat').value;
    const pPhone = document.getElementById('pickup-phone').value;
    const dPhone = document.getElementById('dropoff-phone').value;
    const price = document.getElementById('price').value;

    const warn = (msg) => {
        Swal.fire({ icon: 'warning', text: msg, confirmButtonText: '╪¡╪│┘å╪º┘ï', confirmButtonColor: '#0a8754' });
        return false;
    };

    if (!pLat) return warn('┘è╪▒╪¼┘ë ╪¬╪¡╪»┘è╪» ┘à┘ê┘é╪╣ ╪º┘ä╪º╪│╪¬┘ä╪º┘à ┘à┘å ╪º┘ä╪«╪▒┘è╪╖╪⌐');
    if (!dLat) return warn('┘è╪▒╪¼┘ë ╪¬╪¡╪»┘è╪» ┘ê╪¼┘ç╪⌐ ╪º┘ä╪¬╪│┘ä┘è┘à ┘à┘å ╪º┘ä╪«╪▒┘è╪╖╪⌐');
    if (!pPhone || pPhone.length < 10) return warn('╪▒┘é┘à ┘ç╪º╪¬┘ü ╪º┘ä┘à╪▒╪│┘ä ╪║┘è╪▒ ╪╡╪¡┘è╪¡');
    if (!dPhone || dPhone.length < 10) return warn('╪▒┘é┘à ┘ç╪º╪¬┘ü ╪º┘ä┘à╪│╪¬┘ä┘à ╪║┘è╪▒ ╪╡╪¡┘è╪¡');
    if (!price || price <= 0) return warn('┘è╪▒╪¼┘ë ╪¬╪¡╪»┘è╪» ╪│╪╣╪▒ ╪º┘ä╪╣╪▒╪╢');

    return true;
}

async function createOrder() {
    // Guard
    if (!localStorage.getItem('token')) {
        const res = await Swal.fire({
            title: '╪¬╪│╪¼┘è┘ä ╪º┘ä╪»╪«┘ê┘ä ┘à╪╖┘ä┘ê╪¿',
            text: '╪╣╪┤╪º┘å ╪¬┘é╪»╪▒ ╪¬╪╖┘ä╪¿ ┘â╪º╪¿╪¬┘å╪î ┘ä╪º╪▓┘à ╪¬╪│╪¼┘ä ╪»╪«┘ê┘ä┘â ╪ú┘ê┘ä╪º┘ï.',
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: '╪¬╪│╪¼┘è┘ä ╪º┘ä╪»╪«┘ê┘ä',
            cancelButtonText: '╪Ñ┘ä╪║╪º╪í',
            confirmButtonColor: '#0a8754'
        });
        if (res.isConfirmed) window.location.href = 'client-login.html';
        return;
    }

    if (!validateOrder()) return;

    const btn = document.getElementById('submit-btn');
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> ╪¼╪º╪▒┘è ╪º┘ä╪Ñ╪▒╪│╪º┘ä...';

    let base64Image = null;
    const fileInput = document.getElementById('parcel-image');
    if (fileInput.files.length > 0) {
        base64Image = await compressImage(fileInput.files[0]);
    }

    const data = {
        pickup: {
            address: document.getElementById('pickup-addr').value,
            contactName: document.getElementById('pickup-name').value,
            contactPhone: document.getElementById('pickup-phone').value,
            lat: parseFloat(document.getElementById('pickup-lat').value),
            lng: parseFloat(document.getElementById('pickup-lng').value)
        },
        dropoff: {
            address: document.getElementById('dropoff-addr').value,
            receiverName: document.getElementById('dropoff-name').value,
            receiverPhone: document.getElementById('dropoff-phone').value,
            lat: parseFloat(document.getElementById('dropoff-lat').value),
            lng: parseFloat(document.getElementById('dropoff-lng').value)
        },
        details: document.getElementById('details').value,
        distanceType: document.getElementById('distance-type').value,
        price: parseFloat(document.getElementById('price').value),
        parcelImage: base64Image
    };

    try {
        const res = await fetch(`${API_URL}/api/orders`, {
            method: 'POST',
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}`, 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        if (res.ok) {
            Swal.fire({ icon: 'success', title: '╪¬┘à ╪º┘ä╪╖┘ä╪¿ ╪¿┘å╪¼╪º╪¡! ≡ƒÄë', text: '╪¼╪º╪▒┘è ╪º┘ä╪¿╪¡╪½ ╪╣┘å ┘â╪º╪¿╪¬┘å...', timer: 3000, showConfirmButton: false });
            setTimeout(() => window.location.href = 'client-my-orders.html', 3000);
        } else {
            const err = await res.json();
            Swal.fire({ icon: 'error', text: err.message || '┘ü╪┤┘ä ╪Ñ╪▒╪│╪º┘ä ╪º┘ä╪╖┘ä╪¿' });
            btn.disabled = false; btn.innerHTML = originalHTML;
        }
    } catch (err) {
        Swal.fire({ icon: 'error', text: '╪¡╪»╪½ ╪«╪╖╪ú ┘ü┘è ╪º┘ä╪º╪¬╪╡╪º┘ä ╪¿╪º┘ä╪│┘è╪▒┘ü╪▒' });
        btn.disabled = false; btn.innerHTML = originalHTML;
    }
}

// Notification Init
if (userId && typeof initNotificationSocket === 'function') initNotificationSocket(userId);

// ≡ƒöî Offline Handling
window.addEventListener('online', () => {
    Swal.fire({
        position: 'top-end',
        icon: 'success',
        title: '╪▒╪¼╪╣ ╪º┘ä╪Ñ┘å╪¬╪▒┘å╪¬! ≡ƒîÉ',
        showConfirmButton: false,
        timer: 1500,
        toast: true
    });
});

window.addEventListener('offline', () => {
    Swal.fire({
        position: 'top-end',
        icon: 'warning',
        title: '╪º┘å┘é╪╖╪╣ ╪º┘ä╪º╪¬╪╡╪º┘ä ╪¿╪º┘ä╪Ñ┘å╪¬╪▒┘å╪¬ ΓÜá∩╕Å',
        showConfirmButton: false,
        timer: 3000,
        toast: true
    });
});

