@extends('layouts.app')

@section('title', 'Server Map')

@section('content')
<div class="container mt-4">
    <div class="map-header">
        <h1>Interactive Map</h1>
        <p>Explore key locations. Click on markers to see details.</p>
    </div>
    
    @include('components.interactive-map')
    
    <div class="map-disclaimer">
        <p>This map is a visual representation of the servers layout. Actual in-game locations may vary slightly.</p>
    </div>
</div>
@endsection

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
    const mapContainer = document.getElementById('map-container');
    const mapWrapper = document.getElementById('map-wrapper');
    const mapMarkers = document.getElementById('map-markers');
    const zoomIn = document.getElementById('zoom-in');
    const zoomOut = document.getElementById('zoom-out');
    const resetView = document.getElementById('reset-view');
    const locationInfo = document.getElementById('location-info');
    const locationName = document.getElementById('location-name');
    const locationDescription = document.getElementById('location-description');
    const locationDetails = document.getElementById('location-details');
    const closeInfo = document.getElementById('close-info');

    // Map state
    let scale = 1;
    let translateX = 0;
    let translateY = 0;
    let isDragging = false;
    let startX = 0;
    let startY = 0;
    let currentX = 0;
    let currentY = 0;
    let activeMarker = null;

    const mapLocations = window.mapLocations || [];

    function getImageDisplayBounds(imageElement) {
        const containerRect = imageElement.getBoundingClientRect();
        const imageNaturalRatio = imageElement.naturalWidth / imageElement.naturalHeight;
        const containerRatio = containerRect.width / containerRect.height;
        
        let displayWidth, displayHeight, offsetX, offsetY;
        
        if (imageNaturalRatio > containerRatio) {
            displayWidth = containerRect.width;
            displayHeight = containerRect.width / imageNaturalRatio;
            offsetX = 0;
            offsetY = (containerRect.height - displayHeight) / 2;
        } else {
            displayWidth = containerRect.height * imageNaturalRatio;
            displayHeight = containerRect.height;
            offsetX = (containerRect.width - displayWidth) / 2;
            offsetY = 0;
        }
        
        return {
            left: containerRect.left + offsetX,
            top: containerRect.top + offsetY,
            width: displayWidth,
            height: displayHeight,
            offsetX,
            offsetY
        };
    }

    function percentToPixel(percentX, percentY, imageElement) {
        const bounds = getImageDisplayBounds(imageElement);
        return {
            x: bounds.offsetX + (percentX / 100) * bounds.width,
            y: bounds.offsetY + (percentY / 100) * bounds.height
        };
    }

    function pixelToPercent(pixelX, pixelY, imageElement) {
        const bounds = getImageDisplayBounds(imageElement);
        return {
            x: ((pixelX - bounds.offsetX) / bounds.width) * 100,
            y: ((pixelY - bounds.offsetY) / bounds.height) * 100
        };
    }

    function positionMarker(marker, percentX, percentY) {
        const imageElement = document.getElementById('map-image');
        if (!imageElement.complete || !imageElement.naturalWidth) {
            marker.style.left = `${percentX}%`;
            marker.style.top = `${percentY}%`;
            return;
        }
        
        const pixel = percentToPixel(percentX, percentY, imageElement);
        const containerRect = mapWrapper.getBoundingClientRect();
        
        marker.style.left = `${(pixel.x / containerRect.width) * 100}%`;
        marker.style.top = `${(pixel.y / containerRect.height) * 100}%`;
    }

    function initializeMarkers() {
        if (mapMarkers) {
            mapMarkers.innerHTML = '';
        }

        mapLocations.forEach(location => {
            const marker = document.createElement('div');
            marker.className = `map-marker ${location.type}`;
            marker.dataset.id = location.id;
            
            const label = document.createElement('div');
            label.className = 'marker-label';
            label.textContent = location.name;
            
            positionMarker(marker, location.x, location.y);
            positionMarker(label, location.x, location.y);
            
            marker.addEventListener('click', (e) => {
                e.stopPropagation(); 
                showLocationInfo(location);
                setActiveMarker(marker);
            });
            
            mapMarkers.appendChild(marker);
            mapMarkers.appendChild(label);
        });
    }

    // Show location information
    function showLocationInfo(location) {
        
        locationName.textContent = location.name;
        locationDescription.textContent = location.description;
        
        locationDetails.innerHTML = '';
        
        if (location.details) {
            for (const [key, value] of Object.entries(location.details)) {
                if (Array.isArray(value) && value.length > 0) {
                    const section = document.createElement('div');
                    section.className = 'detail-section';
                    
                    const heading = document.createElement('h4');
                    heading.textContent = key.charAt(0).toUpperCase() + key.slice(1);
                    section.appendChild(heading);
                    
                    const list = document.createElement('ul');
                    value.forEach(item => {
                        const listItem = document.createElement('li');
                        listItem.textContent = item;
                        list.appendChild(listItem);
                    });
                    
                    section.appendChild(list);
                    locationDetails.appendChild(section);
                } else if (typeof value === 'string') {
                    const section = document.createElement('div');
                    section.className = 'detail-section';
                    
                    const heading = document.createElement('h4');
                    heading.textContent = key.charAt(0).toUpperCase() + key.slice(1);
                    section.appendChild(heading);
                    
                    const paragraph = document.createElement('p');
                    paragraph.textContent = value;
                    section.appendChild(paragraph);
                    
                    locationDetails.appendChild(section);
                }
            }
        }
        
        locationInfo.classList.add('active');
    }

    function setActiveMarker(marker) {
        if (activeMarker) {
            activeMarker.classList.remove('active');
        }
        
        marker.classList.add('active');
        activeMarker = marker;
    }

    function applyTransform() {
        mapContainer.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
    }

    function zoomInMap() {
        if (scale < 3) {
            scale += 0.2;
            applyTransform();
        }
    }

    function zoomOutMap() {
        if (scale > 0.5) {
            scale -= 0.2;
            applyTransform();
        }
    }

    function resetMap() {
        scale = 1;
        translateX = 0;
        translateY = 0;
        applyTransform();
        
        locationInfo.classList.remove('active');
        
        if (activeMarker) {
            activeMarker.classList.remove('active');
            activeMarker = null;
        }
    }

    function startDrag(e) {
        if (e.type === 'mousedown') {
            isDragging = true;
            startX = e.clientX;
            startY = e.clientY;
        } else if (e.type === 'touchstart') {
            isDragging = true;
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
        }
        
        currentX = translateX;
        currentY = translateY;
        mapContainer.style.transition = 'none';
    }

    function drag(e) {
        if (!isDragging) return;
        
        let clientX, clientY;
        
        if (e.type === 'mousemove') {
            clientX = e.clientX;
            clientY = e.clientY;
            e.preventDefault();
        } else if (e.type === 'touchmove') {
            clientX = e.touches[0].clientX;
            clientY = e.touches[0].clientY;
        }
        
        translateX = currentX + (clientX - startX);
        translateY = currentY + (clientY - startY);
        
        applyTransform();
    }

    function endDrag() {
        isDragging = false;
        mapContainer.style.transition = '';
    }

    zoomIn.addEventListener('click', zoomInMap);
    zoomOut.addEventListener('click', zoomOutMap);
    resetView.addEventListener('click', resetMap);
    closeInfo.addEventListener('click', () => {
        locationInfo.classList.remove('active');
        if (activeMarker) {
            activeMarker.classList.remove('active');
            activeMarker = null;
        }
    });

    mapContainer.addEventListener('mousedown', startDrag);
    mapContainer.addEventListener('touchstart', startDrag);
    
    document.addEventListener('mousemove', drag);
    document.addEventListener('touchmove', drag);
    
    document.addEventListener('mouseup', endDrag);
    document.addEventListener('touchend', endDrag);

    mapContainer.addEventListener('contextmenu', e => e.preventDefault());

    const coordinatesDisplay = document.createElement('div');
    coordinatesDisplay.className = 'coordinates-display';
    coordinatesDisplay.textContent = 'X: 0%, Y: 0%';
    mapWrapper.appendChild(coordinatesDisplay);
    
    mapWrapper.addEventListener('mousemove', (e) => {
        const imageElement = document.getElementById('map-image');
        if (!imageElement.complete || !imageElement.naturalWidth) {
            coordinatesDisplay.textContent = 'Image loading...';
            return;
        }
        
        const mapRect = mapWrapper.getBoundingClientRect();
        const coords = pixelToPercent(
            e.clientX - mapRect.left,
            e.clientY - mapRect.top,
            imageElement
        );
        
        const x = Math.max(0, Math.min(100, coords.x)).toFixed(1);
        const y = Math.max(0, Math.min(100, coords.y)).toFixed(1);
        coordinatesDisplay.textContent = `X: ${x}%, Y: ${y}%`;
    });

    window.addEventListener('resize', () => {
        setTimeout(() => {
            mapLocations.forEach(location => {
                const marker = mapMarkers.querySelector(`[data-id="${location.id}"]`);
                const label = marker ? marker.nextElementSibling : null;
                
                if (marker) {
                    positionMarker(marker, location.x, location.y);
                }
                if (label && label.classList.contains('marker-label')) {
                    positionMarker(label, location.x, location.y);
                }
            });
        }, 100);
    });

    const mapImage = document.getElementById('map-image');
    if (mapImage.complete) {
        initializeMarkers();
    } else {
        mapImage.addEventListener('load', initializeMarkers);
    }
});
</script>
@endpush