/**
 * Cincinnati Fire Department Portal — Weather Widget + Forecast Modal
 * Click the header weather to open a detailed 5-day forecast.
 */
(function() {
    'use strict';

    const P = window.CFD_PORTAL || {};
    const widget = document.getElementById('weatherWidget');
    if (!widget) return;

    let currentWeather = null;

    async function fetchWeather() {
        const data = await window.portalAPI('weather.php');
        if (!data || data.error) {
            widget.innerHTML = '<span class="weather-loading">Weather unavailable</span>';
            return;
        }
        currentWeather = data;

        widget.innerHTML = `
            <img src="https://openweathermap.org/img/wn/${data.icon}@2x.png" alt="${data.conditions}" width="28" height="28">
            <span class="weather-temp">${Math.round(data.temp)}&deg;</span>
            <span class="weather-cond">${data.conditions}</span>
        `;
        widget.style.cursor = 'pointer';
        widget.title = 'Click for 5-day forecast';
    }

    widget.addEventListener('click', () => {
        if (!currentWeather) return;
        openWeatherModal();
    });

    async function openWeatherModal() {
        let modal = document.getElementById('weatherModal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'weatherModal';
            modal.className = 'modal-overlay';
            modal.addEventListener('click', (e) => { if (e.target === modal) modal.classList.remove('open'); });
            document.body.appendChild(modal);
        }

        const w = currentWeather;
        const sunrise = new Date(w.sunrise * 1000).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
        const sunset = new Date(w.sunset * 1000).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
        const windDir = getWindDirection(w.wind_deg);

        modal.innerHTML = `
            <div class="modal weather-modal">
                <div class="weather-modal-header">
                    <div class="weather-modal-current">
                        <img src="https://openweathermap.org/img/wn/${w.icon}@2x.png" alt="" class="weather-modal-icon">
                        <div>
                            <div class="weather-modal-temp">${Math.round(w.temp)}&deg;F</div>
                            <div class="weather-modal-cond">${w.conditions}</div>
                            <div class="weather-modal-city">${w.city}</div>
                        </div>
                    </div>
                    <button class="weather-modal-close" onclick="document.getElementById('weatherModal').classList.remove('open')">&times;</button>
                </div>

                <div class="weather-modal-details">
                    <div class="weather-detail-item">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z"/></svg>
                        <span class="weather-detail-label">Feels Like</span>
                        <span class="weather-detail-value">${Math.round(w.feels_like)}&deg;</span>
                    </div>
                    <div class="weather-detail-item">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>
                        <span class="weather-detail-label">Humidity</span>
                        <span class="weather-detail-value">${w.humidity}%</span>
                    </div>
                    <div class="weather-detail-item">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.59 4.59A2 2 0 1 1 11 8H2m10.59 11.41A2 2 0 1 0 14 16H2m15.73-8.27A2.5 2.5 0 1 1 19.5 12H2"/></svg>
                        <span class="weather-detail-label">Wind</span>
                        <span class="weather-detail-value">${Math.round(w.wind_speed)} mph ${windDir}</span>
                    </div>
                    <div class="weather-detail-item">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                        <span class="weather-detail-label">Sunrise</span>
                        <span class="weather-detail-value">${sunrise}</span>
                    </div>
                    <div class="weather-detail-item">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 18a5 5 0 0 0-10 0"/><line x1="12" y1="9" x2="12" y2="2"/><line x1="4.22" y1="10.22" x2="5.64" y2="11.64"/><line x1="1" y1="18" x2="3" y2="18"/><line x1="21" y1="18" x2="23" y2="18"/><line x1="18.36" y1="11.64" x2="19.78" y2="10.22"/></svg>
                        <span class="weather-detail-label">Sunset</span>
                        <span class="weather-detail-value">${sunset}</span>
                    </div>
                    <div class="weather-detail-item">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        <span class="weather-detail-label">Visibility</span>
                        <span class="weather-detail-value">${w.visibility} mi</span>
                    </div>
                </div>

                <div class="weather-modal-divider"></div>
                <h3 class="weather-forecast-title">5-Day Forecast</h3>
                <div class="weather-forecast-list" id="weatherForecastList">
                    <div style="text-align:center; padding:20px; color:rgba(255,255,255,0.4); font-size:13px;">Loading forecast...</div>
                </div>
            </div>
        `;

        modal.classList.add('open');
        loadForecast();
    }

    async function loadForecast() {
        const container = document.getElementById('weatherForecastList');
        if (!container) return;

        const data = await window.portalAPI('weather.php?action=forecast');
        if (!data || !data.forecast || data.forecast.length === 0) {
            container.innerHTML = '<div style="text-align:center; padding:20px; color:rgba(255,255,255,0.4);">Forecast unavailable</div>';
            return;
        }

        container.innerHTML = data.forecast.map((day, i) => `
            <div class="weather-forecast-day ${i === 0 ? 'weather-forecast-today' : ''}">
                <div class="forecast-day-name">${i === 0 ? 'Today' : day.day_name}</div>
                <div class="forecast-date">${day.month_day}</div>
                <img src="https://openweathermap.org/img/wn/${day.icon}@2x.png" alt="" class="forecast-icon">
                <div class="forecast-temps">
                    <span class="forecast-high">${day.high}&deg;</span>
                    <span class="forecast-low">${day.low}&deg;</span>
                </div>
                <div class="forecast-cond">${day.conditions}</div>
                ${day.rain_pct > 0 ? `<div class="forecast-rain"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg> ${day.rain_pct}%</div>` : ''}
            </div>
        `).join('');
    }

    function getWindDirection(deg) {
        const dirs = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW'];
        return dirs[Math.round(deg / 22.5) % 16] || '';
    }

    fetchWeather();
    setInterval(fetchWeather, P.weatherRefresh || 600000);
})();
