/**
 * Location Template JavaScript Functions
 * Modern Base Template for Location Pages
 */

// Global variables
let currentImageIndex = 0;
let images = [];
let locationData = {};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    console.log('Location template JS loaded');
    
    // Get location data from the page
    const locationDataElement = document.getElementById('location-data');
    if (locationDataElement) {
        try {
            locationData = JSON.parse(locationDataElement.textContent);
            images = locationData.images || [];
            console.log('Location data loaded:', locationData);
        } catch (e) {
            console.error('Error parsing location data:', e);
        }
    }
    
    // Initialize map if coordinates are available
    if (locationData.lat && locationData.lng) {
        initializeMap();
    }
    
    // Initialize lightbox
    initializeLightbox();
});

// Map initialization
function initializeMap() {
    const mapElement = document.getElementById('locationMap');
    if (!mapElement || !window.L) {
        console.log('Map element or Leaflet not found, retrying...');
        setTimeout(initializeMap, 1000);
        return;
    }
    
    try {
        // Remove placeholder
        const placeholder = mapElement.querySelector('.map-placeholder');
        if (placeholder) {
            placeholder.style.display = 'none';
        }
        
        // Initialize map
        const map = L.map('locationMap', {
            center: [locationData.lat, locationData.lng],
            zoom: 15,
            zoomControl: true,
            scrollWheelZoom: false
        });
        
        // Add tile layer
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            maxZoom: 19
        }).addTo(map);
        
        // Custom marker icon
        const customIcon = L.divIcon({
            html: '<i class="fas fa-map-marker-alt" style="color: #dc3545; font-size: 24px;"></i>',
            iconSize: [30, 30],
            iconAnchor: [15, 30],
            popupAnchor: [0, -30],
            className: 'custom-marker'
        });
        
        // Add marker
        const marker = L.marker([locationData.lat, locationData.lng], {
            icon: customIcon
        }).addTo(map);
        
        // Add popup
        marker.bindPopup(`
            <div style="text-align: center; font-family: 'IRANSans', sans-serif;">
                <strong style="color: #333; font-size: 14px;">${locationData.title}</strong><br>
                <small style="color: #666;">${locationData.address || 'آدرس نامشخص'}</small>
            </div>
        `).openPopup();
        
        // Fit map to marker with padding
        setTimeout(() => {
            map.setView([locationData.lat, locationData.lng], 15);
        }, 100);
        
        console.log('Map initialized successfully');
        
    } catch (error) {
        console.error('Error initializing map:', error);
        const placeholder = mapElement.querySelector('.map-placeholder');
        if (placeholder) {
            placeholder.innerHTML = '<i class="fas fa-exclamation-triangle"></i><p>خطا در بارگذاری نقشه</p>';
        }
    }
}

// Lightbox functionality
function initializeLightbox() {
    // Keyboard navigation for lightbox
    document.addEventListener('keydown', function(e) {
        const modal = document.getElementById('lightboxModal');
        if (modal && modal.style.display === 'flex') {
            if (e.key === 'Escape') {
                closeLightbox();
            } else if (e.key === 'ArrowRight') {
                nextImage();
            } else if (e.key === 'ArrowLeft') {
                prevImage();
            }
        }
    });

    // Close lightbox when clicking outside image
    const lightboxModal = document.getElementById('lightboxModal');
    if (lightboxModal) {
        lightboxModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeLightbox();
            }
        });
    }
}

function openLightbox(index) {
    currentImageIndex = index;
    const modal = document.getElementById('lightboxModal');
    const img = document.getElementById('lightboxImage');
    const counter = document.getElementById('lightboxCounter');
    
    if (!modal || !img || !counter) {
        console.error('Lightbox elements not found');
        return;
    }
    
    if (images[index]) {
        const imagePath = typeof images[index] === 'string' ? images[index] : images[index].path;
        img.src = '/storage/' + imagePath;
        counter.textContent = `${index + 1} از ${images.length}`;
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }
}

function closeLightbox() {
    const modal = document.getElementById('lightboxModal');
    if (modal) {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
}

function nextImage() {
    currentImageIndex = (currentImageIndex + 1) % images.length;
    openLightbox(currentImageIndex);
}

function prevImage() {
    currentImageIndex = (currentImageIndex - 1 + images.length) % images.length;
    openLightbox(currentImageIndex);
}

// Share functionality
function shareLocation() {
    if (navigator.share) {
        navigator.share({
            title: locationData.title,
            text: `مشاهده ${locationData.title}`,
            url: window.location.href
        }).catch(console.error);
    } else {
        copyLink();
    }
}

function shareToTelegram() {
    const url = encodeURIComponent(window.location.href);
    const text = encodeURIComponent(`مشاهده ${locationData.title}`);
    window.open(`https://t.me/share/url?url=${url}&text=${text}`, '_blank');
}

function shareToWhatsApp() {
    const url = encodeURIComponent(window.location.href);
    const text = encodeURIComponent(`مشاهده ${locationData.title} - ${url}`);
    window.open(`https://wa.me/?text=${text}`, '_blank');
}

function shareToTwitter() {
    const url = encodeURIComponent(window.location.href);
    const text = encodeURIComponent(`مشاهده ${locationData.title}`);
    window.open(`https://twitter.com/intent/tweet?url=${url}&text=${text}`, '_blank');
}

function copyLink() {
    const url = window.location.href;
    
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(url).then(() => {
            showCopySuccess();
        }).catch(() => {
            fallbackCopyTextToClipboard(url);
        });
    } else {
        fallbackCopyTextToClipboard(url);
    }
}

function fallbackCopyTextToClipboard(text) {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        document.execCommand('copy');
        showCopySuccess();
    } catch (err) {
        console.error('Fallback: Oops, unable to copy', err);
        alert('لینک کپی نشد. لطفاً دستی کپی کنید: ' + text);
    }
    
    document.body.removeChild(textArea);
}

function showCopySuccess() {
    const btn = event.target.closest('.share-btn');
    if (btn) {
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> کپی شد!';
        btn.style.backgroundColor = '#28a745';
        
        setTimeout(() => {
            btn.innerHTML = originalText;
            btn.style.backgroundColor = '';
        }, 2000);
    }
}

// Make functions globally available
window.openLightbox = openLightbox;
window.closeLightbox = closeLightbox;
window.nextImage = nextImage;
window.prevImage = prevImage;
window.shareLocation = shareLocation;
window.shareToTelegram = shareToTelegram;
window.shareToWhatsApp = shareToWhatsApp;
window.shareToTwitter = shareToTwitter;
window.copyLink = copyLink;
