<?php
$pageTitle = 'Weather Comparison - Compare Two Cities';
$pageDescription = 'Compare weather conditions between two cities side by side. See temperature, humidity, wind, and forecast differences.';
$currentPage = 'compare';
include 'header.php';
?>

<section class="page-header">
    <h1 class="page-title" data-translate="compare">Weather Comparison</h1>
    <p class="page-subtitle" data-translate="compareSubtitle">Compare weather between two cities side by side</p>
</section>

<div class="comparison-selectors">
    <div class="city-selector">
        <label data-translate="city1Label">City 1:</label>
        <input type="text" id="city1Search" class="compare-input" data-placeholder="searchCity" autocomplete="off">
        <div class="search-results compare-results" id="city1Results"></div>
        <div class="selected-city" id="city1Selected"></div>
    </div>
    
    <div class="vs-divider" data-translate="vs">VS</div>
    
    <div class="city-selector">
        <label data-translate="city2Label">City 2:</label>
        <input type="text" id="city2Search" class="compare-input" data-placeholder="searchCity" autocomplete="off">
        <div class="search-results compare-results" id="city2Results"></div>
        <div class="selected-city" id="city2Selected"></div>
    </div>
</div>

<button class="compare-btn" id="compareBtn" disabled data-translate="compareCities">Compare Cities</button>

<div class="comparison-container" id="comparisonResults" style="display: none;">
    <div class="comparison-grid">
        <div class="compare-card" id="city1Weather">
            <div class="compare-card-header">
                <h3 id="city1Name">-</h3>
            </div>
            <div class="compare-weather">
                <div class="compare-temp">
                    <span class="compare-icon" id="city1Icon">&#9728;</span>
                    <span class="compare-temp-value" id="city1Temp">--</span>
                </div>
                <div class="compare-condition" id="city1Condition">--</div>
            </div>
            <div class="compare-details">
                <div class="compare-detail">
                    <span class="detail-label" data-translate="humidity">Humidity</span>
                    <span class="detail-value" id="city1Humidity">--%</span>
                </div>
                <div class="compare-detail">
                    <span class="detail-label" data-translate="wind">Wind</span>
                    <span class="detail-value" id="city1Wind">-- km/h</span>
                </div>
                <div class="compare-detail">
                    <span class="detail-label" data-translate="feelsLike">Feels Like</span>
                    <span class="detail-value" id="city1FeelsLike">--°C</span>
                </div>
                <div class="compare-detail">
                    <span class="detail-label" data-translate="uvIndex">UV Index</span>
                    <span class="detail-value" id="city1UV">--</span>
                </div>
            </div>
        </div>
        
        <div class="compare-difference">
            <h4 data-translate="difference">Difference</h4>
            <div class="diff-item">
                <span class="diff-label" data-translate="temperature">Temperature</span>
                <span class="diff-value" id="diffTemp">--</span>
            </div>
            <div class="diff-item">
                <span class="diff-label" data-translate="humidity">Humidity</span>
                <span class="diff-value" id="diffHumidity">--</span>
            </div>
            <div class="diff-item">
                <span class="diff-label" data-translate="wind">Wind</span>
                <span class="diff-value" id="diffWind">--</span>
            </div>
        </div>
        
        <div class="compare-card" id="city2Weather">
            <div class="compare-card-header">
                <h3 id="city2Name">-</h3>
            </div>
            <div class="compare-weather">
                <div class="compare-temp">
                    <span class="compare-icon" id="city2Icon">&#9728;</span>
                    <span class="compare-temp-value" id="city2Temp">--</span>
                </div>
                <div class="compare-condition" id="city2Condition">--</div>
            </div>
            <div class="compare-details">
                <div class="compare-detail">
                    <span class="detail-label" data-translate="humidity">Humidity</span>
                    <span class="detail-value" id="city2Humidity">--%</span>
                </div>
                <div class="compare-detail">
                    <span class="detail-label" data-translate="wind">Wind</span>
                    <span class="detail-value" id="city2Wind">-- km/h</span>
                </div>
                <div class="compare-detail">
                    <span class="detail-label" data-translate="feelsLike">Feels Like</span>
                    <span class="detail-value" id="city2FeelsLike">--°C</span>
                </div>
                <div class="compare-detail">
                    <span class="detail-label" data-translate="uvIndex">UV Index</span>
                    <span class="detail-value" id="city2UV">--</span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let cities = [];
let selectedCity1 = null;
let selectedCity2 = null;

document.addEventListener('DOMContentLoaded', function() {
    fetch('data/cities.json')
        .then(res => res.json())
        .then(data => { cities = data; })
        .catch(err => console.error('Error loading cities:', err));
    
    setupCitySearch('city1Search', 'city1Results', 1);
    setupCitySearch('city2Search', 'city2Results', 2);
    
    document.getElementById('compareBtn').addEventListener('click', compareWeather);
    
    updateComparePlaceholders();
});

function updateComparePlaceholders() {
    document.querySelectorAll('[data-placeholder]').forEach(el => {
        const key = el.getAttribute('data-placeholder');
        el.placeholder = t(key);
    });
}

function setupCitySearch(inputId, resultsId, cityNum) {
    const input = document.getElementById(inputId);
    const results = document.getElementById(resultsId);
    
    input.addEventListener('input', function() {
        const query = this.value.toLowerCase().trim();
        
        // Enable button based on input text
        checkInputsForButton();
        
        if (query.length < 2) {
            results.classList.remove('active');
            return;
        }
        
        const matches = cities.filter(city => 
            city.city.toLowerCase().includes(query) || 
            city.country.toLowerCase().includes(query)
        ).slice(0, 6);
        
        if (matches.length > 0) {
            results.innerHTML = matches.map(city => 
                `<div class="search-result-item" data-city="${city.city}" data-country="${city.country}" 
                     data-lat="${city.latitude || ''}" data-lon="${city.longitude || ''}">
                    <strong>${city.city}</strong>, ${city.country}
                </div>`
            ).join('');
            results.classList.add('active');
            
            results.querySelectorAll('.search-result-item').forEach(item => {
                item.addEventListener('click', function() {
                    selectCity(cityNum, {
                        city: this.dataset.city,
                        country: this.dataset.country,
                        latitude: parseFloat(this.dataset.lat) || null,
                        longitude: parseFloat(this.dataset.lon) || null
                    });
                    input.value = this.dataset.city;
                    results.classList.remove('active');
                });
            });
        } else {
            results.classList.remove('active');
        }
    });
    
    document.addEventListener('click', function(e) {
        if (!input.contains(e.target) && !results.contains(e.target)) {
            results.classList.remove('active');
        }
    });
}

function checkInputsForButton() {
    const city1Input = document.getElementById('city1Search').value.trim();
    const city2Input = document.getElementById('city2Search').value.trim();
    const btn = document.getElementById('compareBtn');
    
    if (city1Input.length >= 2 && city2Input.length >= 2) {
        btn.disabled = false;
    } else if (!selectedCity1 || !selectedCity2) {
        btn.disabled = true;
    }
}

function selectCity(cityNum, city) {
    const removeText = t('removeFromFavorites') || 'Remove';
    if (cityNum === 1) {
        selectedCity1 = city;
        document.getElementById('city1Selected').innerHTML = `
            <span class="selected-name">${city.city}, ${city.country}</span>
            <button class="clear-selection" onclick="clearCity(1)" title="${removeText}">&times;</button>
        `;
    } else {
        selectedCity2 = city;
        document.getElementById('city2Selected').innerHTML = `
            <span class="selected-name">${city.city}, ${city.country}</span>
            <button class="clear-selection" onclick="clearCity(2)" title="${removeText}">&times;</button>
        `;
    }
    
    updateCompareButton();
}

function clearCity(cityNum) {
    if (cityNum === 1) {
        selectedCity1 = null;
        document.getElementById('city1Selected').innerHTML = '';
    } else {
        selectedCity2 = null;
        document.getElementById('city2Selected').innerHTML = '';
    }
    updateCompareButton();
}

function updateCompareButton() {
    const btn = document.getElementById('compareBtn');
    btn.disabled = !(selectedCity1 && selectedCity2);
    btn.textContent = t('compareCities');
}

async function compareWeather() {
    const city1Input = document.getElementById('city1Search').value.trim();
    const city2Input = document.getElementById('city2Search').value.trim();
    
    // Use input text if no city was selected from autocomplete
    if (!selectedCity1 && city1Input) {
        selectedCity1 = { city: city1Input, country: '', latitude: null, longitude: null };
    }
    if (!selectedCity2 && city2Input) {
        selectedCity2 = { city: city2Input, country: '', latitude: null, longitude: null };
    }
    
    if (!selectedCity1 || !selectedCity2) {
        alert('Please enter both city names');
        return;
    }
    
    const btn = document.getElementById('compareBtn');
    btn.textContent = t('loading') || 'Loading...';
    btn.disabled = true;
    
    try {
        let lat1 = selectedCity1.latitude;
        let lon1 = selectedCity1.longitude;
        let lat2 = selectedCity2.latitude;
        let lon2 = selectedCity2.longitude;
        
        if (!lat1 || !lon1) {
            const cityName1 = selectedCity1.country ? selectedCity1.city + ', ' + selectedCity1.country : selectedCity1.city;
            const geo1 = await geocodeCity(cityName1);
            lat1 = geo1.lat; lon1 = geo1.lon;
        }
        if (!lat2 || !lon2) {
            const cityName2 = selectedCity2.country ? selectedCity2.city + ', ' + selectedCity2.country : selectedCity2.city;
            const geo2 = await geocodeCity(cityName2);
            lat2 = geo2.lat; lon2 = geo2.lon;
        }
        
        if (!lat1 || !lon1 || !lat2 || !lon2) {
            throw new Error('Could not geocode cities');
        }
        
        const [weather1, weather2] = await Promise.all([
            fetch(`api/weather.php?lat=${lat1}&lon=${lon1}`).then(r => r.json()),
            fetch(`api/weather.php?lat=${lat2}&lon=${lon2}`).then(r => r.json())
        ]);
        
        displayComparison(weather1, weather2);
        
    } catch (error) {
        console.error('Comparison error:', error);
        alert(t('errorComparing') || 'Error comparing cities. Please try again.');
    }
    
    btn.textContent = t('compareCities');
    btn.disabled = false;
}

async function geocodeCity(cityName) {
    const response = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(cityName)}&format=json&limit=1`);
    const data = await response.json();
    if (data.length > 0) {
        return { lat: parseFloat(data[0].lat), lon: parseFloat(data[0].lon) };
    }
    return { lat: null, lon: null };
}

function displayComparison(w1, w2) {
    document.getElementById('comparisonResults').style.display = 'block';
    
    document.getElementById('city1Name').textContent = `${selectedCity1.city}, ${selectedCity1.country}`;
    document.getElementById('city2Name').textContent = `${selectedCity2.city}, ${selectedCity2.country}`;
    
    if (w1.today) {
        document.getElementById('city1Icon').innerHTML = getWeatherIcon(w1.today.icon);
        document.getElementById('city1Temp').textContent = `${w1.today.temp}°C`;
        document.getElementById('city1Condition').textContent = w1.today.condition;
        document.getElementById('city1Humidity').textContent = `${w1.today.humidity}%`;
        document.getElementById('city1Wind').textContent = `${w1.today.wind} km/h`;
        document.getElementById('city1FeelsLike').textContent = `${w1.today.feels_like}°C`;
        document.getElementById('city1UV').textContent = w1.today.uv;
    }
    
    if (w2.today) {
        document.getElementById('city2Icon').innerHTML = getWeatherIcon(w2.today.icon);
        document.getElementById('city2Temp').textContent = `${w2.today.temp}°C`;
        document.getElementById('city2Condition').textContent = w2.today.condition;
        document.getElementById('city2Humidity').textContent = `${w2.today.humidity}%`;
        document.getElementById('city2Wind').textContent = `${w2.today.wind} km/h`;
        document.getElementById('city2FeelsLike').textContent = `${w2.today.feels_like}°C`;
        document.getElementById('city2UV').textContent = w2.today.uv;
    }
    
    if (w1.today && w2.today) {
        const tempDiff = w1.today.temp - w2.today.temp;
        const humDiff = w1.today.humidity - w2.today.humidity;
        const windDiff = w1.today.wind - w2.today.wind;
        
        document.getElementById('diffTemp').textContent = `${tempDiff > 0 ? '+' : ''}${tempDiff}°C`;
        document.getElementById('diffHumidity').textContent = `${humDiff > 0 ? '+' : ''}${humDiff}%`;
        document.getElementById('diffWind').textContent = `${windDiff > 0 ? '+' : ''}${windDiff} km/h`;
    }
    
    document.getElementById('comparisonResults').scrollIntoView({ behavior: 'smooth' });
}
</script>

<?php include 'footer.php'; ?>
