jQuery(document).ready(function($) {
    
    // Geocode location lookup
    $('#waypoint-geocode-btn').on('click', function(e) {
        e.preventDefault();
        
        var location = $('#waypoint-location-input').val();
        var $button = $(this);
        var $results = $('#waypoint-geocode-results');
        
        if (!location) {
            alert('Please enter a location');
            return;
        }
        
        // Show loading state
        $button.prop('disabled', true).text('Searching...');
        $results.html('<p>Searching for "' + location + '"...</p>');
        
        $.ajax({
            url: waypointWeather.ajaxurl,
            type: 'POST',
            data: {
                action: 'waypoint_weather_geocode',
                nonce: waypointWeather.nonce,
                location: location
            },
            success: function(response) {
                $button.prop('disabled', false).text('Find Location');
                
                if (response.success && response.data.length > 0) {
                    var html = '<div style="margin-top: 15px;"><h4>Select Your Location:</h4><ul style="list-style: none; padding: 0;">';
                    
                    response.data.forEach(function(loc) {
                        var displayName = loc.name;
                        if (loc.state) displayName += ', ' + loc.state;
                        if (loc.country) displayName += ', ' + loc.country;
                        
                        html += '<li style="margin: 10px 0; padding: 10px; background: #f0f0f1; border-left: 3px solid #2271b1;">';
                        html += '<strong>' + displayName + '</strong><br>';
                        html += '<code style="font-size: 12px;">Lat: ' + loc.lat + ', Lon: ' + loc.lon + '</code><br>';
                        html += '<button class="button button-primary select-location" data-lat="' + loc.lat + '" data-lon="' + loc.lon + '" data-name="' + displayName + '" style="margin-top: 5px;">Use This Location</button>';
                        html += '</li>';
                    });
                    
                    html += '</ul></div>';
                    $results.html(html);
                } else {
                    $results.html('<p style="color: #d63638;">Location not found. Try being more specific (e.g., "Paris, FR" or "Los Angeles, CA, US")</p>');
                }
            },
            error: function() {
                $button.prop('disabled', false).text('Find Location');
                $results.html('<p style="color: #d63638;">Error connecting to geocoding service. Please try again.</p>');
            }
        });
    });
    
    // Handle location selection
    $(document).on('click', '.select-location', function(e) {
        e.preventDefault();
        
        var lat = $(this).data('lat');
        var lon = $(this).data('lon');
        var name = $(this).data('name');
        
        // Populate the builder
        $('#builder-lat').val(lat);
        $('#builder-lon').val(lon);
        $('#builder-location-name').val(name);
        
        // Highlight selection
        $('.select-location').removeClass('button-primary').addClass('button-secondary');
        $(this).removeClass('button-secondary').addClass('button-primary');
        
        // Update shortcode
        updateShortcode();
        
        // Scroll to builder
        $('html, body').animate({
            scrollTop: $('#waypoint-shortcode-builder').offset().top - 50
        }, 500);
    });
    
    // Update shortcode when any option changes
    $('#builder-lat, #builder-lon, #builder-units, #builder-size, #builder-forecast, #builder-hide-stats, #builder-show-link, #builder-location-name').on('change keyup', function() {
        updateShortcode();
    });
    
    // Copy shortcode to clipboard
    $('#copy-shortcode-btn').on('click', function(e) {
        e.preventDefault();
        
        var $output = $('#shortcode-output');
        $output.select();
        
        try {
            document.execCommand('copy');
            $(this).text('✓ Copied!').css('background', '#00a32a');
            
            setTimeout(function() {
                $('#copy-shortcode-btn').text('Copy Shortcode').css('background', '');
            }, 2000);
        } catch (err) {
            alert('Please manually copy the shortcode');
        }
    });
    
    // Function to build shortcode
    function updateShortcode() {
        var lat = $('#builder-lat').val();
        var lon = $('#builder-lon').val();
        var units = $('#builder-units').val();
        var size = $('#builder-size').val();
        var forecast = $('#builder-forecast').val();
        var hideStats = $('#builder-hide-stats').is(':checked') ? '1' : '0';
        var showLink = $('#builder-show-link').is(':checked') ? '1' : '0';
        var locationName = $('#builder-location-name').val();
        
        if (!lat || !lon) {
            $('#shortcode-output').val('Please select a location above first');
            return;
        }
        
        var shortcode = '[waypoint-weather';
        shortcode += ' lat="' + lat + '"';
        shortcode += ' lon="' + lon + '"';
        
        if (units) {
            shortcode += ' units="' + units + '"';
        }
        
        if (size && size !== 'wide') {
            shortcode += ' size="' + size + '"';
        }
        
        if (forecast && forecast !== '5') {
            shortcode += ' forecast_days="' + forecast + '"';
        }
        
        if (hideStats === '1') {
            shortcode += ' hide_stats="1"';
        }
        
        if (showLink === '1') {
            shortcode += ' show_link="1"';
        }
        
        if (locationName) {
            shortcode += ' override_title="' + locationName + '"';
        }
        
        shortcode += ']';
        
        $('#shortcode-output').val(shortcode);
    }
});
