

<?php $__env->startSection('title', 'Interactive Map Editor'); ?>

<?php $__env->startSection('content'); ?>
<div class="admin-content">
    <div class="dashboard-header">
        <h1>Interactive Map Editor</h1>
        <p>Add and manage locations on the server map</p>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="dashboard-card dashboard-card-tall">
                <div class="dashboard-card-header">
                    <h3>Map Configuration</h3>
                </div>
                <div class="dashboard-card-body">
                    <form action="<?php echo e(route('admin.map.update')); ?>" method="POST" enctype="multipart/form-data" id="mapSettingsForm">
                        <?php echo csrf_field(); ?>
                        <div class="form-group">
                            <label for="map_title">Map Title</label>
                            <input type="text" id="map_title" name="map_title" class="form-control" value="<?php echo e($mapSettings->title ?? 'Interactive Server Map'); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="map_description">Map Description</label>
                            <textarea id="map_description" name="map_description" class="form-control"><?php echo e($mapSettings->description ?? 'Explore key locations on our DarkRP server. Click on markers to see details.'); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="map_image">Map Image</label>
                            <div class="file-upload-wrapper">
                                <input type="file" id="map_image" name="map_image" class="file-upload-input" accept="image/*">
                                <label for="map_image" class="file-upload-label">
                                    <i class="fas fa-upload file-upload-icon"></i>
                                    <span>Choose a map image</span>
                                </label>
                                <div class="file-upload-preview">
                                    <?php if(isset($mapSettings->image_path)): ?>
                                    <div class="current-file">
                                        <span class="file-name">Current Image</span>
                                        <img src="<?php echo e(asset('storage/' . $mapSettings->image_path)); ?>" alt="Current Map" class="file-preview">
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Settings
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="dashboard-card dashboard-card-tall">
                <div class="dashboard-card-header">
                    <h3>Add New Location</h3>
                </div>
                <div class="dashboard-card-body">
                    <form id="locationForm">
                        <div class="form-group">
                            <label for="location_name">Location Name</label>
                            <input type="text" id="location_name" name="location_name" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="location_type">Location Type</label>
                            <select id="location_type" name="location_type" class="form-control" required>
                                <option value="">Select Type</option>
                                <option value="government">Government</option>
                                <option value="commercial">Commercial</option>
                                <option value="residential">Residential</option>
                                <option value="illegal">Illegal</option>
                                <option value="public">Public</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="location_description">Description</label>
                            <textarea id="location_description" name="location_description" class="form-control" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label>Position</label>
                            <div class="position-info alert alert-success">
                                <i class="fas fa-info-circle"></i> Click on the map to place this location or adjust coordinates manually
                            </div>
                            <div class="row">
                                <div class="col-md-5">
                                    <label for="location_x">X Position (%)</label>
                                    <input type="number" id="location_x" name="location_x" class="form-control" min="0" max="100" step="0.1" required>
                                </div>
                                <div class="col-md-5">
                                    <label for="location_y">Y Position (%)</label>
                                    <input type="number" id="location_y" name="location_y" class="form-control" min="0" max="100" step="0.1" required>
                                </div>
                                <div class="col-md-2">
                                    <label>&nbsp;</label>
                                    <button type="button" id="place_on_map" class="btn btn-primary form-control">
                                        <i class="fas fa-map-marker-alt"></i> Place
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Details</label>
                            <div id="location_details_container">
                                <!-- Dynamic details fields will be added here -->
                            </div>
                            <div class="mt-2">
                                <button type="button" id="add_detail_section" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-plus"></i> Add Detail Section
                                </button>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Location
                            </button>
                            <button type="button" id="clear_form" class="btn btn-secondary">
                                <i class="fas fa-eraser"></i> Clear
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <div class="dashboard-card dashboard-card-full">
        <div class="dashboard-card-header">
            <h3>Interactive Map Preview</h3>
            <div class="map-actions">
                <button type="button" id="add_marker_btn" class="btn btn-primary">
                    <i class="fas fa-map-marker-alt"></i> Add Marker on Map
                </button>
            </div>
        </div>
        <div class="dashboard-card-body">
            <div class="map-editor-container">
                <div class="map-editor-controls">
                    <button class="btn btn-sm btn-primary" id="editor-zoom-in">
                        <i class="fas fa-plus"></i> Zoom In
                    </button>
                    <button class="btn btn-sm btn-primary" id="editor-zoom-out">
                        <i class="fas fa-minus"></i> Zoom Out
                    </button>
                    <button class="btn btn-sm btn-secondary" id="editor-reset-view">
                        <i class="fas fa-sync-alt"></i> Reset View
                    </button>
                </div>
                
                <div class="map-editor-wrapper">
                    <div class="map-editor-container-inner" id="map-editor-container">
                        <div class="map-editor-image-container">
                            <img src="<?php echo e(isset($mapSettings->image_path) ? asset('storage/' . $mapSettings->image_path) : asset('images/download.jpeg')); ?>" 
                                alt="Server Map" id="map-editor-image">
                            
                            <div id="map-editor-markers">
                                <!-- Markers will be added here by JavaScript -->
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="placement-instruction" id="placement-instruction" style="display: none;">
                    <i class="fas fa-info-circle"></i> Click anywhere on the map to place your marker
                </div>
            </div>
        </div>
    </div>
    
    <div class="dashboard-card">
        <div class="dashboard-card-header d-flex justify-content-between align-items-center">
            <h3>Existing Locations</h3>
            <div>
                <button class="btn btn-danger" id="delete-selected">
                    <i class="fas fa-trash"></i> Delete Selected
                </button>
            </div>
        </div>
        <div class="dashboard-card-body">
            <div class="table-responsive">
                <table class="table" id="locations-table">
                    <thead>
                        <tr>
                            <th width="40px">
                                <input type="checkbox" id="select-all-locations">
                            </th>
                            <th>Name</th>
                            <th>Type</th>
                            <th>Position</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Location rows will be added here by JavaScript -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Hidden confirmation modal -->
<div class="modal-backdrop" id="confirm-modal">
    <div class="modal">
        <div class="modal-header">
            <h3 id="modal-title">Confirm Action</h3>
            <button class="close-btn" id="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <p id="modal-message">Are you sure you want to perform this action?</p>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" id="modal-cancel">Cancel</button>
            <button class="btn btn-danger" id="modal-confirm">Confirm</button>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>


<?php $__env->startPush('scripts'); ?>
<script>
// =============================================================================
// ADMIN MAP EDITOR - OPTIMIZED WITH FIXED COORDINATES
// =============================================================================

class AdminMapEditor {
    constructor() {
        this.state = {
            scale: 1,
            translateX: 0,
            translateY: 0,
            isDragging: false,
            startX: 0,
            startY: 0,
            currentX: 0,
            currentY: 0,
            isPlacingMarker: false,
            placingMarker: null,
            selectedLocation: null,
            editingLocationId: null,
            locations: []
        };

        this.elements = {};
        this.modalCallback = null;

        this.init();
    }

    // =============================================================================
    // COORDINATE SYSTEM UTILITIES
    // =============================================================================

    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) {
            // Image is wider - letterboxing on top/bottom
            displayWidth = containerRect.width;
            displayHeight = containerRect.width / imageNaturalRatio;
            offsetX = 0;
            offsetY = (containerRect.height - displayHeight) / 2;
        } else {
            // Image is taller - letterboxing on left/right
            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
        };
    }

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

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

    positionMarker(marker, percentX, percentY) {
        const imageElement = this.elements.mapImage;
        if (!imageElement.complete || !imageElement.naturalWidth) {
            // Fallback to old system if image isn't loaded
            marker.style.left = `${percentX}%`;
            marker.style.top = `${percentY}%`;
            return;
        }
        
        const pixel = this.percentToPixel(percentX, percentY, imageElement);
        const containerRect = this.elements.mapWrapper.getBoundingClientRect();
        
        marker.style.left = `${(pixel.x / containerRect.width) * 100}%`;
        marker.style.top = `${(pixel.y / containerRect.height) * 100}%`;
    }

    // =============================================================================
    // INITIALIZATION
    // =============================================================================

    init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        console.log('Map Editor initialized');
        
        this.initializeElements();
        this.initializeEventListeners();
        this.createCoordinatesDisplay();
        this.loadLocations();
        
        // Make globally accessible for debugging
        window.mapEditor = this;
    }

    initializeElements() {
        this.elements = {
            // Map elements
            mapContainer: document.getElementById('map-editor-container'),
            mapWrapper: document.querySelector('.map-editor-wrapper'),
            mapImage: document.getElementById('map-editor-image'),
            markersContainer: document.getElementById('map-editor-markers'),
            
            // Control elements
            zoomIn: document.getElementById('editor-zoom-in'),
            zoomOut: document.getElementById('editor-zoom-out'),
            resetView: document.getElementById('editor-reset-view'),
            
            // Form elements
            locationForm: document.getElementById('locationForm'),
            locationNameInput: document.getElementById('location_name'),
            locationTypeInput: document.getElementById('location_type'),
            locationDescInput: document.getElementById('location_description'),
            locationXInput: document.getElementById('location_x'),
            locationYInput: document.getElementById('location_y'),
            detailsContainer: document.getElementById('location_details_container'),
            addDetailSectionBtn: document.getElementById('add_detail_section'),
            clearFormBtn: document.getElementById('clear_form'),
            
            // Action buttons
            placeOnMapBtn: document.getElementById('place_on_map'),
            addMarkerBtn: document.getElementById('add_marker_btn'),
            placementInstruction: document.getElementById('placement-instruction'),
            
            // Table elements
            locationsTable: document.getElementById('locations-table')?.querySelector('tbody'),
            selectAllCheckbox: document.getElementById('select-all-locations'),
            deleteSelectedBtn: document.getElementById('delete-selected'),
            
            // Modal elements
            confirmModal: document.getElementById('confirm-modal'),
            modalTitle: document.getElementById('modal-title'),
            modalMessage: document.getElementById('modal-message'),
            modalClose: document.getElementById('modal-close'),
            modalCancel: document.getElementById('modal-cancel'),
            modalConfirm: document.getElementById('modal-confirm'),
            
            // File upload
            mapImageInput: document.getElementById('map_image')
        };
    }

    initializeEventListeners() {
        this.bindMapControls();
        this.bindFormHandlers();
        this.bindTableHandlers();
        this.bindModalHandlers();
        this.bindFileHandlers();
    }

    // =============================================================================
    // API FUNCTIONS
    // =============================================================================

    get csrfToken() {
        return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    }

    get isTestEnvironment() {
        return !this.csrfToken;
    }

    async loadLocationsFromServer() {
        if (this.isTestEnvironment) {
            throw new Error('Test environment - using demo data');
        }

        const response = await fetch('/admin/map/locations');
        if (!response.ok) {
            throw new Error(`Server error: ${response.status}`);
        }
        return response.json();
    }

    async saveNewLocation(locationData) {
        if (this.isTestEnvironment) {
            // Simulate server response in test mode
            return { ...locationData, id: Date.now() };
        }

        const validatedData = this.validateLocationData(locationData);
        
        const response = await fetch('/admin/map/locations', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': this.csrfToken,
                'Accept': 'application/json'
            },
            body: JSON.stringify(validatedData)
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `Server error: ${response.status}`);
        }

        return response.json();
    }

    async updateExistingLocation(id, locationData) {
        if (this.isTestEnvironment) {
            return { ...locationData, id };
        }

        const validatedData = this.validateLocationData(locationData);
        
        const response = await fetch(`/admin/map/locations/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': this.csrfToken,
                'Accept': 'application/json'
            },
            body: JSON.stringify(validatedData)
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `Server error: ${response.status}`);
        }

        return response.json();
    }

    async deleteLocationFromServer(id) {
        if (this.isTestEnvironment) {
            return { message: 'Location deleted successfully.' };
        }

        const response = await fetch(`/admin/map/locations/${id}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': this.csrfToken,
                'Accept': 'application/json'
            }
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `Server error: ${response.status}`);
        }

        return response.json();
    }

    async deleteMultipleLocations(ids) {
        if (this.isTestEnvironment) {
            return { message: `${ids.length} locations deleted successfully.` };
        }

        const response = await fetch('/admin/map/locations', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': this.csrfToken,
                'Accept': 'application/json'
            },
            body: JSON.stringify({ ids })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `Server error: ${response.status}`);
        }

        return response.json();
    }

    validateLocationData(locationData) {
        return {
            name: locationData.name || '',
            type: locationData.type || 'public',
            description: locationData.description || '',
            x: parseFloat(locationData.x) || 0,
            y: parseFloat(locationData.y) || 0,
            details: locationData.details || {}
        };
    }

    // =============================================================================
    // MAP FUNCTIONALITY
    // =============================================================================

    async loadLocations() {
        try {
            console.log('Loading locations from server...');
            const data = await this.loadLocationsFromServer();
            console.log(`Successfully loaded ${data.length} locations`);
            this.state.locations = data;
        } catch (error) {
            console.warn('Failed to load from server, using demo data:', error.message);
            this.state.locations = this.getDemoData();
        } finally {
            this.renderLocations();
            this.updateLocationsTable();
        }
    }

    getDemoData() {
        return [
            {
                id: 1,
                name: "Spawn",
                x: 50,
                y: 50,
                type: "public",
                description: "The area which all players spawn in once they die/join the server.",
                details: {
                    features: ["Food Vendors", "Public Events Space"],
                    activities: ["Trading", "Socializing"]
                }
            },
            {
                id: 2,
                name: "City Hall",
                x: 53,
                y: 32,
                type: "government",
                description: "The administrative center where the mayor spawns and laws can be changed.",
                details: {
                    jobs: ["Mayor", "Government Official"],
                    features: ["Mayor's Office", "Council Chamber", "Public Records"]
                }
            }
        ];
    }

    renderLocations() {
        const container = this.elements.markersContainer;
        if (!container) return;

        container.innerHTML = '';
        
        this.state.locations.forEach(location => {
            this.createMarker(location);
        });
    }

    createMarker(location) {
        const container = this.elements.markersContainer;
        if (!container) return null;

        // Create marker element
        const marker = document.createElement('div');
        marker.className = `map-editor-marker ${location.type}`;
        marker.dataset.id = location.id;

        // Position marker using the new coordinate system
        this.positionMarker(marker, location.x, location.y);

        // Create label
        const label = document.createElement('div');
        label.className = 'map-editor-marker-label';
        label.textContent = location.name;
        
        // Position label using the same system
        this.positionMarker(label, location.x, location.y);

        // Add click event
        marker.addEventListener('click', (e) => {
            e.stopPropagation();
            if (!this.state.isPlacingMarker) {
                this.selectLocation(location);
            }
        });

        container.appendChild(marker);
        container.appendChild(label);

        return marker;
    }

    selectLocation(location) {
        console.log('Selecting location:', location);

        this.clearSelection();

        // Populate form
        this.populateForm(location);

        // Update state
        this.state.selectedLocation = location;
        this.state.editingLocationId = location.id;

        // Highlight marker
        const marker = this.elements.markersContainer?.querySelector(`[data-id="${location.id}"]`);
        if (marker) {
            marker.classList.add('selected');
        }

        // Highlight table row
        const row = this.elements.locationsTable?.querySelector(`[data-id="${location.id}"]`);
        if (row) {
            row.classList.add('table-active');
        }

        // Scroll to form
        this.scrollToElement('.dashboard-card:nth-child(2)');
    }

    clearSelection() {
        // Clear form highlights
        const selectedMarker = this.elements.markersContainer?.querySelector('.selected');
        if (selectedMarker) {
            selectedMarker.classList.remove('selected');
        }

        const activeRow = this.elements.locationsTable?.querySelector('.table-active');
        if (activeRow) {
            activeRow.classList.remove('table-active');
        }

        this.state.selectedLocation = null;
    }

    populateForm(location) {
        const elements = this.elements;
        
        elements.locationNameInput.value = location.name;
        elements.locationTypeInput.value = location.type;
        elements.locationDescInput.value = location.description;
        elements.locationXInput.value = location.x;
        elements.locationYInput.value = location.y;

        // Clear and rebuild details
        elements.detailsContainer.innerHTML = '';
        if (location.details) {
            Object.entries(location.details).forEach(([key, values]) => {
                this.addDetailSection(key, values);
            });
        }
    }

    updateLocationsTable() {
        const table = this.elements.locationsTable;
        if (!table) return;

        table.innerHTML = '';

        this.state.locations.forEach(location => {
            const row = this.createTableRow(location);
            table.appendChild(row);
        });
    }

    createTableRow(location) {
        const row = document.createElement('tr');
        row.dataset.id = location.id;

        row.innerHTML = `
            <td>
                <input type="checkbox" class="location-checkbox" data-id="${location.id}">
            </td>
            <td>${this.escapeHtml(location.name)}</td>
            <td><span class="type-badge ${location.type}">${location.type}</span></td>
            <td>X: ${location.x}%, Y: ${location.y}%</td>
            <td class="user-actions">
                <button class="btn-icon btn-primary" title="Edit location">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn-icon btn-success" title="Edit position on map">
                    <i class="fas fa-map-marker-alt"></i>
                </button>
                <button class="btn-icon btn-danger" title="Delete location">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;

        // Add event listeners
        row.addEventListener('click', (e) => {
            if (!e.target.closest('button') && !e.target.closest('input')) {
                this.selectLocation(location);
            }
        });

        // Button event listeners
        const buttons = row.querySelectorAll('button');
        buttons[0].addEventListener('click', () => this.selectLocation(location));
        buttons[1].addEventListener('click', () => {
            this.selectLocation(location);
            this.startPlacingMarker();
        });
        buttons[2].addEventListener('click', () => this.deleteLocation(location.id));

        return row;
    }

    // =============================================================================
    // FORM MANAGEMENT
    // =============================================================================

    addDetailSection(title = '', items = []) {
        const container = this.elements.detailsContainer;
        if (!container) return null;

        const sectionId = 'detail-section-' + Date.now();
        const section = document.createElement('div');
        section.className = 'detail-section-container';
        section.dataset.id = sectionId;

        section.innerHTML = `
            <div class="detail-section-header">
                <div>
                    <input type="text" class="form-control" 
                           name="detail_title_${sectionId}" 
                           placeholder="Section Title (e.g., Features, Jobs)" 
                           value="${this.escapeHtml(title)}" required>
                </div>
                <button type="button" class="remove-detail-section">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="detail-items-container"></div>
            <button type="button" class="btn btn-sm btn-secondary">
                <i class="fas fa-plus"></i> Add Item
            </button>
        `;

        const itemsContainer = section.querySelector('.detail-items-container');
        const removeBtn = section.querySelector('.remove-detail-section');
        const addItemBtn = section.querySelector('.btn');

        // Add existing items
        if (items.length > 0) {
            items.forEach(item => this.addDetailItem(itemsContainer, item));
        } else {
            this.addDetailItem(itemsContainer);
        }

        // Event listeners
        removeBtn.addEventListener('click', () => section.remove());
        addItemBtn.addEventListener('click', () => this.addDetailItem(itemsContainer));

        container.appendChild(section);
        return section;
    }

    addDetailItem(container, value = '') {
        if (!container) return null;

        const itemId = 'detail-item-' + Date.now();
        const item = document.createElement('div');
        item.className = 'detail-item';

        item.innerHTML = `
            <input type="text" class="form-control detail-item-input" 
                   name="detail_item_${itemId}" 
                   placeholder="Detail item" 
                   value="${this.escapeHtml(value)}">
            <button type="button" class="remove-detail-item">
                <i class="fas fa-times"></i>
            </button>
        `;

        const removeBtn = item.querySelector('.remove-detail-item');
        removeBtn.addEventListener('click', () => item.remove());

        container.appendChild(item);
        return item;
    }

    collectFormData() {
        const elements = this.elements;
        
        const location = {
            name: elements.locationNameInput.value,
            type: elements.locationTypeInput.value,
            description: elements.locationDescInput.value,
            x: parseFloat(elements.locationXInput.value),
            y: parseFloat(elements.locationYInput.value),
            details: {}
        };

        // Collect details
        const detailSections = elements.detailsContainer.querySelectorAll('.detail-section-container');
        detailSections.forEach(section => {
            const sectionId = section.dataset.id;
            const titleInput = section.querySelector(`[name="detail_title_${sectionId}"]`);
            const title = titleInput?.value.trim();

            if (title) {
                const items = [];
                const itemInputs = section.querySelectorAll('.detail-item-input');
                itemInputs.forEach(input => {
                    const value = input.value.trim();
                    if (value) items.push(value);
                });

                if (items.length > 0) {
                    location.details[title] = items;
                }
            }
        });

        return location;
    }

    clearForm() {
        if (this.elements.locationForm) {
            this.elements.locationForm.reset();
        }

        this.elements.detailsContainer.innerHTML = '';
        this.state.editingLocationId = null;
        this.clearSelection();
    }

    async saveLocation(location) {
        console.log('Saving location:', location);

        // Validation
        if (!this.validateLocation(location)) {
            return;
        }

        try {
            const savedLocation = this.state.editingLocationId
                ? await this.updateExistingLocation(this.state.editingLocationId, location)
                : await this.saveNewLocation(location);

            // Update local state
            if (this.state.editingLocationId) {
                const index = this.state.locations.findIndex(loc => loc.id === this.state.editingLocationId);
                if (index !== -1) {
                    this.state.locations[index] = savedLocation;
                } else {
                    this.state.locations.push(savedLocation);
                }
            } else {
                this.state.locations.push(savedLocation);
            }

            // Update UI
            this.renderLocations();
            this.updateLocationsTable();
            this.clearForm();

            // Show success message
            this.showNotification(
                this.state.editingLocationId ? 'Location updated successfully' : 'Location added successfully',
                'success'
            );

            // Refresh in background for consistency
            setTimeout(() => this.loadLocations(), 500);

        } catch (error) {
            console.error('Error saving location:', error);
            this.showNotification('Error saving location: ' + error.message, 'danger');
        }
    }

    validateLocation(location) {
        if (!location.name || !location.type || !location.description) {
            this.showNotification('Please fill in all required fields', 'danger');
            return false;
        }

        if (isNaN(location.x) || isNaN(location.y)) {
            this.showNotification('Please provide valid coordinates', 'danger');
            return false;
        }

        return true;
    }

    async deleteLocation(id) {
        this.showConfirmModal(
            'Delete Location',
            'Are you sure you want to delete this location? This action cannot be undone.',
            async () => {
                try {
                    await this.deleteLocationFromServer(id);

                    // Clear form if editing this location
                    if (this.state.editingLocationId === id) {
                        this.clearForm();
                    }

                    // Remove from local state
                    this.state.locations = this.state.locations.filter(loc => loc.id !== id);

                    // Update UI
                    this.renderLocations();
                    this.updateLocationsTable();

                    this.showNotification('Location deleted successfully', 'success');
                } catch (error) {
                    console.error('Error deleting location:', error);
                    this.showNotification('Error deleting location: ' + error.message, 'danger');
                }
            }
        );
    }

    // =============================================================================
    // MAP CONTROLS & INTERACTION
    // =============================================================================

    applyTransform() {
        if (this.elements.mapContainer) {
            const { translateX, translateY, scale } = this.state;
            this.elements.mapContainer.style.transform = 
                `translate(${translateX}px, ${translateY}px) scale(${scale})`;
        }
    }

    startPlacingMarker() {
        const elements = this.elements;
        
        if (!elements.locationTypeInput.value) {
            alert('Please select a location type first');
            elements.locationTypeInput.focus();
            return;
        }

        this.state.isPlacingMarker = true;

        // Create placing marker
        if (this.state.placingMarker) {
            this.state.placingMarker.remove();
        }

        this.state.placingMarker = document.createElement('div');
        this.state.placingMarker.className = `map-editor-marker ${elements.locationTypeInput.value} placing`;
        elements.markersContainer.appendChild(this.state.placingMarker);

        // Update UI
        elements.mapWrapper.style.cursor = 'crosshair';
        elements.mapWrapper.classList.add('placement-mode');
        elements.placementInstruction.style.display = 'block';

        this.scrollToElement('.dashboard-card:nth-child(3)');
    }

    endPlacingMarker() {
        this.state.isPlacingMarker = false;

        if (this.state.placingMarker) {
            this.state.placingMarker.remove();
            this.state.placingMarker = null;
        }

        // Reset UI
        const elements = this.elements;
        if (elements.mapWrapper) {
            elements.mapWrapper.style.cursor = 'move';
            elements.mapWrapper.classList.remove('placement-mode');
        }

        if (elements.placementInstruction) {
            elements.placementInstruction.style.display = 'none';
        }
    }

    createCoordinatesDisplay() {
        if (this.elements.mapWrapper) {
            const display = document.createElement('div');
            display.className = 'coordinates-display';
            display.textContent = 'X: 0%, Y: 0%';
            this.elements.mapWrapper.appendChild(display);
            this.coordinatesDisplay = display;
        }
    }

    updateCoordinatesDisplay(e) {
        if (!this.coordinatesDisplay || !this.elements.mapWrapper) return;

        const rect = this.elements.mapWrapper.getBoundingClientRect();
        const imageElement = this.elements.mapImage;
        
        if (!imageElement.complete || !imageElement.naturalWidth) {
            this.coordinatesDisplay.textContent = 'Image loading...';
            return;
        }
        
        // Get coordinates relative to the actual image display area
        const coords = this.pixelToPercent(
            e.clientX - rect.left,
            e.clientY - rect.top,
            imageElement
        );
        
        // Clamp coordinates to valid range
        const x = Math.max(0, Math.min(100, coords.x)).toFixed(1);
        const y = Math.max(0, Math.min(100, coords.y)).toFixed(1);
        
        this.coordinatesDisplay.textContent = `X: ${x}%, Y: ${y}%`;

        // Update placing marker position
        if (this.state.isPlacingMarker && this.state.placingMarker) {
            this.positionMarker(this.state.placingMarker, x, y);
        }

        return { x, y };
    }

    // =============================================================================
    // EVENT HANDLERS
    // =============================================================================

    bindMapControls() {
        const elements = this.elements;

        // Zoom controls
        elements.zoomIn?.addEventListener('click', () => {
            if (this.state.scale < 3) {
                this.state.scale += 0.2;
                this.applyTransform();
            }
        });

        elements.zoomOut?.addEventListener('click', () => {
            if (this.state.scale > 0.5) {
                this.state.scale -= 0.2;
                this.applyTransform();
            }
        });

        elements.resetView?.addEventListener('click', () => {
            this.state.scale = 1;
            this.state.translateX = 0;
            this.state.translateY = 0;
            this.applyTransform();
        });

        // Mouse events for dragging
        elements.mapContainer?.addEventListener('mousedown', (e) => {
            if (!this.state.isPlacingMarker) {
                this.state.isDragging = true;
                this.state.startX = e.clientX;
                this.state.startY = e.clientY;
                this.state.currentX = this.state.translateX;
                this.state.currentY = this.state.translateY;
                elements.mapContainer.style.transition = 'none';
            }
        });

        document.addEventListener('mousemove', (e) => {
            this.updateCoordinatesDisplay(e);

            if (this.state.isDragging) {
                this.state.translateX = this.state.currentX + (e.clientX - this.state.startX);
                this.state.translateY = this.state.currentY + (e.clientY - this.state.startY);
                this.applyTransform();
            }
        });

        document.addEventListener('mouseup', () => {
            this.state.isDragging = false;
            if (elements.mapContainer) {
                elements.mapContainer.style.transition = '';
            }
        });

        // Map click for placing markers
        elements.mapWrapper?.addEventListener('click', (e) => {
            if (this.state.isPlacingMarker) {
                const coords = this.updateCoordinatesDisplay(e);
                
                elements.locationXInput.value = coords.x;
                elements.locationYInput.value = coords.y;
                
                this.endPlacingMarker();
                this.scrollToElement('.dashboard-card:nth-child(2)');
            }
        });
    }

    bindFormHandlers() {
        const elements = this.elements;

        // Place marker buttons
        elements.placeOnMapBtn?.addEventListener('click', () => this.startPlacingMarker());
        elements.addMarkerBtn?.addEventListener('click', () => {
            this.clearForm();
            elements.locationNameInput.value = 'New Location';
            elements.locationTypeInput.value = 'public';
            elements.locationDescInput.value = 'Description for this location.';
            this.startPlacingMarker();
        });

        // Coordinate inputs
        elements.locationXInput?.addEventListener('click', () => this.startPlacingMarker());
        elements.locationYInput?.addEventListener('click', () => this.startPlacingMarker());

        // Form actions
        elements.addDetailSectionBtn?.addEventListener('click', () => this.addDetailSection());
        elements.clearFormBtn?.addEventListener('click', () => this.clearForm());

        // Form submission
        elements.locationForm?.addEventListener('submit', (e) => {
            e.preventDefault();

            if (!elements.locationForm.checkValidity()) {
                elements.locationForm.reportValidity();
                return;
            }

            if (!elements.locationXInput.value || !elements.locationYInput.value) {
                this.showNotification('Please place the marker on the map', 'danger');
                this.startPlacingMarker();
                return;
            }

            const location = this.collectFormData();
            this.saveLocation(location);
        });
    }

    bindTableHandlers() {
        const elements = this.elements;

        // Select all checkbox
        elements.selectAllCheckbox?.addEventListener('change', () => {
            const checkboxes = document.querySelectorAll('.location-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = elements.selectAllCheckbox.checked;
            });
        });

        // Delete selected button
        elements.deleteSelectedBtn?.addEventListener('click', () => {
            const selectedIds = Array.from(document.querySelectorAll('.location-checkbox:checked'))
                .map(checkbox => parseInt(checkbox.dataset.id));

            if (selectedIds.length === 0) {
                alert('Please select at least one location to delete');
                return;
            }

            this.showConfirmModal(
                'Delete Selected Locations',
                `Are you sure you want to delete ${selectedIds.length} selected location(s)? This action cannot be undone.`,
                async () => {
                    try {
                        await this.deleteMultipleLocations(selectedIds);

                        if (this.state.editingLocationId && selectedIds.includes(this.state.editingLocationId)) {
                            this.clearForm();
                        }

                        this.state.locations = this.state.locations.filter(loc => !selectedIds.includes(loc.id));
                        this.renderLocations();
                        this.updateLocationsTable();
                        elements.selectAllCheckbox.checked = false;

                        this.showNotification(`${selectedIds.length} location(s) deleted successfully`, 'success');
                    } catch (error) {
                        console.error('Error deleting locations:', error);
                        this.showNotification('Error deleting locations: ' + error.message, 'danger');
                    }
                }
            );
        });
    }

    bindModalHandlers() {
        const elements = this.elements;

        elements.modalClose?.addEventListener('click', () => this.hideConfirmModal());
        elements.modalCancel?.addEventListener('click', () => this.hideConfirmModal());
        elements.modalConfirm?.addEventListener('click', () => {
            if (this.modalCallback) {
                this.modalCallback();
            }
            this.hideConfirmModal();
        });

        // Prevent closing when clicking inside modal
        elements.confirmModal?.querySelector('.modal')?.addEventListener('click', (e) => {
            e.stopPropagation();
        });

        // Close on backdrop click
        elements.confirmModal?.addEventListener('click', () => this.hideConfirmModal());
    }

    bindFileHandlers() {
        this.elements.mapImageInput?.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (event) => {
                // Update preview
                this.updateFilePreview(file.name, event.target.result);
                
                // Update editor image
                if (this.elements.mapImage) {
                    this.elements.mapImage.src = event.target.result;
                }
            };
            reader.readAsDataURL(file);
        });
    }

    updateFilePreview(fileName, src) {
        const preview = document.querySelector('.file-upload-preview');
        if (!preview) return;

        // Remove existing new file preview
        const existingNewFile = preview.querySelector('.new-file');
        if (existingNewFile) {
            existingNewFile.remove();
        }

        // Create new preview
        const newFile = document.createElement('div');
        newFile.className = 'new-file';
        newFile.innerHTML = `
            <span class="file-name">${this.escapeHtml(fileName)}</span>
            <img class="file-preview" src="${src}" alt="New Map Preview">
        `;

        preview.appendChild(newFile);
    }

    // =============================================================================
    // UTILITY FUNCTIONS
    // =============================================================================

    showConfirmModal(title, message, onConfirm) {
        const elements = this.elements;
        
        if (!elements.confirmModal) {
            // Fallback to native confirm
            if (confirm(message)) {
                onConfirm();
            }
            return;
        }

        elements.modalTitle.textContent = title;
        elements.modalMessage.textContent = message;
        this.modalCallback = onConfirm;
        elements.confirmModal.classList.add('active');
    }

    hideConfirmModal() {
        if (this.elements.confirmModal) {
            this.elements.confirmModal.classList.remove('active');
            this.modalCallback = null;
        }
    }

    showNotification(message, type = 'info') {
        console.log('Notification:', type, message);

        const notification = document.createElement('div');
        notification.className = `alert alert-${type}`;
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            max-width: 300px;
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
        `;

        document.body.appendChild(notification);

        // Animate in
        requestAnimationFrame(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateY(0)';
        });

        // Auto remove
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateY(-20px)';
            setTimeout(() => notification.remove(), 300);
        }, 5000);
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    scrollToElement(selector) {
        const element = document.querySelector(selector);
        if (element) {
            element.scrollIntoView({ behavior: 'smooth' });
        }
    }

    // =============================================================================
    // PUBLIC API (for debugging)
    // =============================================================================

    getPublicAPI() {
        return {
            loadLocations: () => this.loadLocations(),
            renderLocations: () => this.renderLocations(),
            updateTable: () => this.updateLocationsTable(),
            selectLocation: (id) => {
                const location = this.state.locations.find(loc => loc.id === id);
                if (location) this.selectLocation(location);
            },
            clearSelection: () => this.clearSelection(),
            clearForm: () => this.clearForm(),
            startPlacing: () => this.startPlacingMarker(),
            endPlacing: () => this.endPlacingMarker(),
            getState: () => ({ ...this.state }),
            showNotification: (msg, type) => this.showNotification(msg, type)
        };
    }
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.mapEditor = new AdminMapEditor();
    console.log('Map Editor initialized and available at window.mapEditor');
});
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('layouts.admin', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /var/www/siedestudios.co.uk/edge/resources/views/admin/map-editor.blade.php ENDPATH**/ ?>