/**
 * WCMLIM Address Management
 * Modern address management system for WooCommerce Multi-Locations
 */

(function ($) {
    'use strict';

    class WCMLIMAddressManager {
        constructor() {
            this.addresses = [];
            this.selectedAddressId = null;
            this.map = null;
            this.marker = null;
            this.currentLat = null;
            this.currentLng = null;
            this.editingAddressId = null;

            this.init();
        }

        init() {
            // Only initialize if widget exists in DOM (from shortcode)
            if ($('.wcmlim-address-header').length === 0) {
                console.log('WCMLIM Address: Widget not found. Please add the shortcode [wcmlim_address_selector] to your header.');
                return;
            }
            this.createModal();
            this.bindEvents();
            this.loadAddresses();
            this.autoSelectAddress();
        }

        createModal() {
            const modal = `
                <div class="wcmlim-modal-overlay">
                    <div class="wcmlim-modal">
                        <div class="wcmlim-modal-header">
                            <h2 class="wcmlim-modal-title">Add New Address</h2>
                            <button class="wcmlim-modal-close">&times;</button>
                        </div>
                        <div class="wcmlim-modal-body">
                            <form id="wcmlim-address-form">
                                <div class="wcmlim-form-group">
                                    <label class="wcmlim-form-label required">Address Label</label>
                                    <input type="text" name="label" class="wcmlim-form-input" 
                                           placeholder="e.g., Home, Office, etc." required>
                                </div>
                                
                                <div class="wcmlim-form-group">
                                    <label class="wcmlim-form-label required">Address Line 1</label>
                                    <input type="text" name="address_line1" class="wcmlim-form-input" 
                                           placeholder="Street address, P.O. box" required>
                                </div>
                                
                                <div class="wcmlim-form-group">
                                    <label class="wcmlim-form-label">Address Line 2</label>
                                    <input type="text" name="address_line2" class="wcmlim-form-input" 
                                           placeholder="Apartment, suite, unit, etc.">
                                </div>
                                
                                <div class="wcmlim-form-row">
                                    <div class="wcmlim-form-group">
                                        <label class="wcmlim-form-label required">City</label>
                                        <input type="text" name="city" class="wcmlim-form-input" 
                                               placeholder="City" required>
                                    </div>
                                    
                                    <div class="wcmlim-form-group">
                                        <label class="wcmlim-form-label required">State</label>
                                        <input type="text" name="state" class="wcmlim-form-input" 
                                               placeholder="State" required>
                                    </div>
                                </div>
                                
                                <div class="wcmlim-form-row">
                                    <div class="wcmlim-form-group">
                                        <label class="wcmlim-form-label required">Country</label>
                                        <input type="text" name="country" class="wcmlim-form-input" 
                                               placeholder="Country" required>
                                    </div>
                                    
                                    <div class="wcmlim-form-group">
                                        <label class="wcmlim-form-label required">Postcode</label>
                                        <input type="text" name="postcode" class="wcmlim-form-input" 
                                               placeholder="Postcode" required>
                                    </div>
                                </div>
                                
                                <div class="wcmlim-form-group">
                                    <label class="wcmlim-form-label">Pin Location on Map</label>
                                    <div class="wcmlim-map-info">
                                        <strong>📍 Tip:</strong> Click on the map to set your exact location for better accuracy.
                                    </div>
                                    <div id="wcmlim-address-map" class="wcmlim-map-container"></div>
                                </div>
                                
                                <input type="hidden" name="latitude" id="wcmlim-latitude">
                                <input type="hidden" name="longitude" id="wcmlim-longitude">
                                <input type="hidden" name="address_id" id="wcmlim-address-id">
                            </form>
                        </div>
                        <div class="wcmlim-modal-footer">
                            <button type="button" class="wcmlim-btn wcmlim-btn-secondary wcmlim-modal-cancel">Cancel</button>
                            <button type="button" class="wcmlim-btn wcmlim-btn-primary wcmlim-save-address-btn">
                                Save Address
                            </button>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(modal);
        }

        bindEvents() {
            // Toggle dropdown
            $(document).on('click', '.wcmlim-address-trigger', (e) => {
                e.stopPropagation();
                $('.wcmlim-address-trigger').toggleClass('active');
                $('.wcmlim-address-dropdown').toggleClass('show');
            });

            // Close dropdown when clicking outside
            $(document).on('click', (e) => {
                if (!$(e.target).closest('.wcmlim-address-header').length) {
                    $('.wcmlim-address-trigger').removeClass('active');
                    $('.wcmlim-address-dropdown').removeClass('show');
                }
            });

            // Open modal for new address
            $(document).on('click', '.wcmlim-add-address-btn', (e) => {
                e.stopPropagation();
                this.editingAddressId = null;
                this.openModal();
            });

            // Edit address
            $(document).on('click', '.wcmlim-address-edit-btn', (e) => {
                e.stopPropagation();
                const addressId = $(e.currentTarget).data('address-id');
                this.editAddress(addressId);
            });

            // Delete address
            $(document).on('click', '.wcmlim-address-delete-btn', (e) => {
                e.stopPropagation();
                const addressId = $(e.currentTarget).data('address-id');
                this.deleteAddress(addressId);
            });

            // Set default address
            $(document).on('click', '.wcmlim-address-default-btn', (e) => {
                e.stopPropagation();
                const addressId = $(e.currentTarget).data('address-id');
                this.setDefaultAddress(addressId);
            });

            // Select address
            $(document).on('click', '.wcmlim-address-item', (e) => {
                if (!$(e.target).closest('.wcmlim-address-actions').length) {
                    const addressId = $(e.currentTarget).data('address-id');
                    this.selectAddress(addressId);
                }
            });

            // Close modal
            $(document).on('click', '.wcmlim-modal-close, .wcmlim-modal-cancel', () => {
                this.closeModal();
            });

            // Close modal on overlay click
            $(document).on('click', '.wcmlim-modal-overlay', (e) => {
                if ($(e.target).hasClass('wcmlim-modal-overlay')) {
                    this.closeModal();
                }
            });

            // Save address
            $(document).on('click', '.wcmlim-save-address-btn', () => {
                this.saveAddress();
            });

            // Form submission
            $(document).on('submit', '#wcmlim-address-form', (e) => {
                e.preventDefault();
                this.saveAddress();
            });
        }

        loadAddresses() {
            $.ajax({
                url: wcmlim_address_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'wcmlim_get_user_addresses',
                    security: wcmlim_address_vars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.addresses = response.data.addresses;
                        this.selectedAddressId = response.data.selected_address_id;
                        
                        // If no address is selected but we have a default address, auto-select it
                        if (!this.selectedAddressId && Object.keys(this.addresses).length > 0) {
                            const defaultAddress = Object.values(this.addresses).find(addr => addr.is_default);
                            if (defaultAddress) {
                                this.selectedAddressId = defaultAddress.id;
                                // Automatically select the default address
                                this.selectAddress(defaultAddress.id, true);
                            }
                        }
                        
                        this.renderAddressList();
                        this.updateHeaderText();
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Error loading addresses:', error);
                }
            });
        }

        renderAddressList() {
            const $list = $('.wcmlim-address-list');
            $list.empty();

            if (Object.keys(this.addresses).length === 0) {
                $list.html(`
                    <div class="wcmlim-no-address">
                        <svg class="wcmlim-no-address-icon" viewBox="0 0 24 24" fill="#ccc">
                            <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                        </svg>
                        <p class="wcmlim-no-address-text">No saved addresses yet</p>
                        <button class="wcmlim-btn wcmlim-btn-primary wcmlim-add-address-btn">Add Your First Address</button>
                    </div>
                `);
                return;
            }

            Object.values(this.addresses).forEach(address => {
                const isSelected = address.id === this.selectedAddressId;
                const addressHtml = `
                    <div class="wcmlim-address-item ${isSelected ? 'selected' : ''}" data-address-id="${address.id}">
                        <div class="wcmlim-address-label">
                            <svg class="wcmlim-address-label-icon" viewBox="0 0 24 24">
                                <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                            </svg>
                            <span class="wcmlim-address-label-text">${this.escapeHtml(address.label)}</span>
                            ${address.is_default ? '<span class="wcmlim-address-default-badge">Default</span>' : ''}
                        </div>
                        <div class="wcmlim-address-details">
                            ${this.escapeHtml(address.address_line1)}${address.address_line2 ? ', ' + this.escapeHtml(address.address_line2) : ''}<br>
                            ${this.escapeHtml(address.city)}, ${this.escapeHtml(address.state)} ${this.escapeHtml(address.postcode)}<br>
                            ${this.escapeHtml(address.country)}
                        </div>
                        <div class="wcmlim-address-actions">
                            <button class="wcmlim-address-action-btn wcmlim-address-edit-btn" data-address-id="${address.id}">
                                Edit
                            </button>
                            ${!address.is_default ? `
                                <button class="wcmlim-address-action-btn wcmlim-address-default-btn" data-address-id="${address.id}">
                                    Set Default
                                </button>
                            ` : ''}
                            <button class="wcmlim-address-action-btn wcmlim-address-delete-btn" data-address-id="${address.id}">
                                Delete
                            </button>
                        </div>
                    </div>
                `;
                $list.append(addressHtml);
            });
        }

        updateHeaderText() {
            if (this.selectedAddressId && this.addresses[this.selectedAddressId]) {
                const address = this.addresses[this.selectedAddressId];
                const shortAddress = `${address.label}${address.city ? ', ' + address.city : ''}`;
                $('.wcmlim-address-text').text(shortAddress);
            } else {
                $('.wcmlim-address-text').text('Select Address');
            }
        }

        openModal(title = 'Add New Address') {
            $('.wcmlim-modal-title').text(title);
            $('.wcmlim-modal-overlay').addClass('show');
            
            // Initialize map and autocomplete after modal is visible
            setTimeout(() => {
                this.initializeMap();
                this.initializeAutocomplete();
                this.bindAddressFieldListeners();
            }, 300);
        }

        closeModal() {
            $('.wcmlim-modal-overlay').removeClass('show');
            $('#wcmlim-address-form')[0].reset();
            this.editingAddressId = null;
        }

        initializeAutocomplete() {
            if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
                return;
            }

            const addressInput = document.querySelector('input[name="address_line1"]');
            if (!addressInput) {
                return;
            }

            // Always use the legacy Autocomplete (it still works despite deprecation notice)
            // The new PlaceAutocompleteElement is a web component that requires different implementation
            try {
                const autocomplete = new google.maps.places.Autocomplete(addressInput, {
                    types: ['address'],
                    fields: ['address_components', 'geometry', 'formatted_address']
                });

                autocomplete.addListener('place_changed', () => {
                    const place = autocomplete.getPlace();
                    if (place.geometry) {
                        this.handlePlaceSelectionLegacy(place);
                    }
                });
            } catch (error) {
                console.error('Error initializing autocomplete:', error);
            }
        }

        handlePlaceSelectionLegacy(place) {
            const addressComponents = {};
            place.address_components.forEach(component => {
                const types = component.types;
                if (types.includes('street_number')) {
                    addressComponents.street_number = component.long_name;
                }
                if (types.includes('route')) {
                    addressComponents.route = component.long_name;
                }
                if (types.includes('locality')) {
                    addressComponents.city = component.long_name;
                }
                if (types.includes('administrative_area_level_1')) {
                    addressComponents.state = component.long_name;
                }
                if (types.includes('country')) {
                    addressComponents.country = component.long_name;
                }
                if (types.includes('postal_code')) {
                    addressComponents.postcode = component.long_name;
                }
                if (types.includes('sublocality_level_1') && !addressComponents.city) {
                    addressComponents.city = component.long_name;
                }
            });

            this.fillAddressFields(addressComponents);

            if (place.geometry) {
                const lat = place.geometry.location.lat();
                const lng = place.geometry.location.lng();
                this.updateMapPosition(lat, lng);
            }
        }

        fillAddressFields(addressComponents) {
            if (addressComponents.city) {
                $('input[name="city"]').val(addressComponents.city);
            }
            if (addressComponents.state) {
                $('input[name="state"]').val(addressComponents.state);
            }
            if (addressComponents.country) {
                $('input[name="country"]').val(addressComponents.country);
            }
            if (addressComponents.postcode) {
                $('input[name="postcode"]').val(addressComponents.postcode);
            }
        }

        updateMapPosition(lat, lng) {
            if (this.marker) {
                this.marker.setPosition({ lat, lng });
            }
            if (this.map) {
                this.map.setCenter({ lat, lng });
                this.map.setZoom(15);
            }
            this.updateCoordinates(lat, lng);
        }

        bindAddressFieldListeners() {
            // Debounce geocoding to avoid too many requests
            let geocodeTimeout = null;
            
            const addressFields = ['address_line1', 'address_line2', 'city', 'state', 'country', 'postcode'];
            
            addressFields.forEach(field => {
                $(`input[name="${field}"]`).off('input.wcmlim').on('input.wcmlim', () => {
                    clearTimeout(geocodeTimeout);
                    geocodeTimeout = setTimeout(() => {
                        this.geocodeAddress();
                    }, 1000); // Wait 1 second after user stops typing
                });
            });
        }

        geocodeAddress() {
            if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
                return;
            }

            const address = this.getFullAddress();
            if (!address) return;

            const geocoder = new google.maps.Geocoder();
            
            geocoder.geocode({ address: address }, (results, status) => {
                if (status === 'OK' && results[0]) {
                    const location = results[0].geometry.location;
                    const lat = location.lat();
                    const lng = location.lng();
                    
                    // Update map marker
                    this.updateMapPosition(lat, lng);
                }
            });
        }

        getFullAddress() {
            const parts = [];
            const address1 = $('input[name="address_line1"]').val();
            const address2 = $('input[name="address_line2"]').val();
            const city = $('input[name="city"]').val();
            const state = $('input[name="state"]').val();
            const country = $('input[name="country"]').val();
            const postcode = $('input[name="postcode"]').val();
            
            if (address1) parts.push(address1);
            if (address2) parts.push(address2);
            if (city) parts.push(city);
            if (state) parts.push(state);
            if (country) parts.push(country);
            if (postcode) parts.push(postcode);
            
            return parts.join(', ');
        }

        initializeMap() {
            if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
                return;
            }

            const mapCanvas = document.getElementById('wcmlim-address-map');
            if (!mapCanvas) {
                return;
            }

            // Get initial coordinates
            const lat = parseFloat($('#address-latitude').val()) || 40.7128;
            const lng = parseFloat($('#address-longitude').val()) || -74.0060;

            // Initialize map (simple configuration)
            this.map = new google.maps.Map(mapCanvas, {
                center: { lat, lng },
                zoom: 13
            });

            // Use legacy Marker (works reliably without Map ID requirement)
            this.marker = new google.maps.Marker({
                position: { lat, lng },
                map: this.map,
                draggable: true,
                title: 'Address Location'
            });

            // Add drag listener
            this.marker.addListener('dragend', (event) => {
                const newLat = event.latLng.lat();
                const newLng = event.latLng.lng();
                this.updateCoordinates(newLat, newLng);
            });
        }

        updateCoordinates(lat, lng) {
            $('#wcmlim-latitude').val(lat);
            $('#wcmlim-longitude').val(lng);
            this.currentLat = lat;
            this.currentLng = lng;
        }

        saveAddress() {
            const $form = $('#wcmlim-address-form');
            const $btn = $('.wcmlim-save-address-btn');

            if (!$form[0].checkValidity()) {
                $form[0].reportValidity();
                return;
            }

            const formData = {
                action: this.editingAddressId ? 'wcmlim_update_user_address' : 'wcmlim_add_user_address',
                security: wcmlim_address_vars.nonce,
                label: $form.find('[name="label"]').val(),
                address_line1: $form.find('[name="address_line1"]').val(),
                address_line2: $form.find('[name="address_line2"]').val(),
                city: $form.find('[name="city"]').val(),
                state: $form.find('[name="state"]').val(),
                country: $form.find('[name="country"]').val(),
                postcode: $form.find('[name="postcode"]').val(),
                latitude: $('#wcmlim-latitude').val(),
                longitude: $('#wcmlim-longitude').val(),
                is_default: false
            };

            if (this.editingAddressId) {
                formData.address_id = this.editingAddressId;
            }

            $btn.prop('disabled', true).html('<span class="wcmlim-spinner"></span> Saving...');

            $.ajax({
                url: wcmlim_address_vars.ajax_url,
                type: 'POST',
                data: formData,
                success: (response) => {
                    if (response.success) {
                        this.closeModal();
                        this.loadAddresses();
                        this.showMessage('Address saved successfully!', 'success');
                    } else {
                        this.showMessage(response.data.message || 'Error saving address', 'error');
                    }
                },
                error: () => {
                    this.showMessage('Error saving address', 'error');
                },
                complete: () => {
                    $btn.prop('disabled', false).text('Save Address');
                }
            });
        }

        editAddress(addressId) {
            const address = this.addresses[addressId];
            if (!address) return;

            this.editingAddressId = addressId;
            this.currentLat = address.latitude;
            this.currentLng = address.longitude;

            const $form = $('#wcmlim-address-form');
            $form.find('[name="label"]').val(address.label);
            $form.find('[name="address_line1"]').val(address.address_line1);
            $form.find('[name="address_line2"]').val(address.address_line2);
            $form.find('[name="city"]').val(address.city);
            $form.find('[name="state"]').val(address.state);
            $form.find('[name="country"]').val(address.country);
            $form.find('[name="postcode"]').val(address.postcode);
            $('#wcmlim-latitude').val(address.latitude);
            $('#wcmlim-longitude').val(address.longitude);

            this.openModal('Edit Address');
        }

        deleteAddress(addressId) {
            if (!confirm('Are you sure you want to delete this address?')) {
                return;
            }

            $.ajax({
                url: wcmlim_address_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'wcmlim_delete_user_address',
                    security: wcmlim_address_vars.nonce,
                    address_id: addressId
                },
                success: (response) => {
                    if (response.success) {
                        this.loadAddresses();
                        this.showMessage('Address deleted successfully', 'success');
                    } else {
                        this.showMessage(response.data.message || 'Error deleting address', 'error');
                    }
                },
                error: () => {
                    this.showMessage('Error deleting address', 'error');
                }
            });
        }

        setDefaultAddress(addressId) {
            $.ajax({
                url: wcmlim_address_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'wcmlim_set_default_address',
                    security: wcmlim_address_vars.nonce,
                    address_id: addressId
                },
                success: (response) => {
                    if (response.success) {
                        this.loadAddresses();
                        this.showMessage('Default address updated', 'success');
                    } else {
                        this.showMessage(response.data.message || 'Error updating default address', 'error');
                    }
                },
                error: () => {
                    this.showMessage('Error updating default address', 'error');
                }
            });
        }

        selectAddress(addressId, silent = false) {
            const $btn = $(`.wcmlim-address-item[data-address-id="${addressId}"]`);
            $btn.addClass('loading');

            $.ajax({
                url: wcmlim_address_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'wcmlim_select_address',
                    security: wcmlim_address_vars.nonce,
                    address_id: addressId
                },
                success: (response) => {
                    if (response.success) {
                        this.selectedAddressId = addressId;
                        this.renderAddressList();
                        this.updateHeaderText();
                        
                        $('.wcmlim-address-dropdown').removeClass('show');
                        $('.wcmlim-address-trigger').removeClass('active');
                        
                        // Show success message unless silent mode
                        if (!silent && response.data.message) {
                            this.showMessage(response.data.message, 'success');
                        }
                        
                        // Refresh the page to apply new location (unless silent)
                        if (!silent) {
                            setTimeout(() => {
                                location.reload();
                            }, 500);
                        }
                    } else {
                        this.showMessage(response.data.message || 'Error selecting address', 'error');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('AJAX error selecting address:', error);
                    this.showMessage('Error selecting address', 'error');
                },
                complete: () => {
                    $btn.removeClass('loading');
                }
            });
        }

        autoSelectAddress() {
            // Check if autodetect is enabled and user has saved addresses
            if (wcmlim_address_vars.autodetect_enabled === '1') {
                setTimeout(() => {
                    if (!this.selectedAddressId && Object.keys(this.addresses).length > 0) {
                        // Find default address or first address
                        let defaultAddress = null;
                        Object.values(this.addresses).forEach(address => {
                            if (address.is_default) {
                                defaultAddress = address;
                            }
                        });

                        if (defaultAddress) {
                            this.selectAddress(defaultAddress.id);
                        }
                    }
                }, 1000);
            }
        }

        showMessage(message, type = 'success') {
            const $message = $(`
                <div class="wcmlim-${type}-message wcmlim-fade-in">
                    ${type === 'success' ? '✓' : '✗'} ${message}
                </div>
            `);

            $('.wcmlim-modal-body').prepend($message);

            setTimeout(() => {
                $message.fadeOut(() => $message.remove());
            }, 3000);
        }

        escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }
    }

    // Initialize when DOM is ready
    $(document).ready(function () {
        // Check if user is logged in and feature is enabled
        if (typeof wcmlim_address_vars !== 'undefined' && wcmlim_address_vars.enabled === '1') {
            new WCMLIMAddressManager();
        }
    });

})(jQuery);
