<?php
defined( 'ABSPATH' ) || exit;

wp_enqueue_style(
    'mw-card11-style',
    plugin_dir_url( __FILE__ ) . '../assets/card/card11-style.css',
    [],
    time()
);

$mwpl_current = $weather['current'];
$mwpl_tz_offset = isset( $weather['timezone_offset'] ) ? (int) $weather['timezone_offset'] : 0;
$mwpl_daily   = $weather['daily'][0];

$mwpl_label = $atts['label'] ?? "{$atts['lat']}, {$atts['lon']}";
$mwpl_unit  = isset( $atts['units'] ) ? $atts['units'] : 'metric';

$mwpl_icon_url = "https://openweathermap.org/img/wn/{$mwpl_current['weather'][0]['icon']}@2x.png";
$mwpl_desc_raw = strtolower( $mwpl_current['weather'][0]['description'] ?? '' );

$mwpl_conditions_map = array(
	// Clear / Clouds
	'clear sky'            => '☀️',
	'few clouds'           => '🌤️',
	'scattered clouds'     => '🌥️',
	'broken clouds'        => '☁️',
	'overcast clouds'      => '☁️',

	// Atmosphere
	'mist'                 => '🌫️',
	'smoke'                => '🌫️',
	'haze'                 => '🌫️',
	'fog'                  => '🌫️',
	'sand'                 => '🌪️',
	'dust'                 => '🌪️',
	'ash'                  => '🌪️',
	'squalls'              => '🌬️',
	'tornado'              => '🌪️',

	// Drizzle (all OpenWeather drizzle descriptions)
	'light intensity drizzle'         => '🌦️',
	'drizzle'                         => '🌦️',
	'heavy intensity drizzle'         => '🌦️',
	'light intensity drizzle rain'    => '🌦️',
	'drizzle rain'                    => '🌦️',
	'heavy intensity drizzle rain'    => '🌦️',
	'shower rain and drizzle'         => '🌦️',
	'heavy shower rain and drizzle'   => '🌦️',
	'shower drizzle'                  => '🌦️',

	// Rain (all OpenWeather rain descriptions)
	'light rain'                      => '🌦️',
	'moderate rain'                   => '🌧️',
	'heavy intensity rain'            => '🌧️',
	'very heavy rain'                 => '🌧️',
	'extreme rain'                    => '🌧️',
	'freezing rain'                   => '🌧️❄️',
	'light intensity shower rain'     => '🌦️',
	'shower rain'                     => '🌦️',
	'heavy intensity shower rain'     => '🌧️',
	'ragged shower rain'              => '🌦️',

	// Thunderstorm (all OpenWeather thunderstorm descriptions)
	'thunderstorm with light rain'    => '⛈️',
	'thunderstorm with rain'          => '⛈️',
	'thunderstorm with heavy rain'    => '⛈️',
	'light thunderstorm'              => '🌩️',
	'thunderstorm'                    => '⛈️',
	'heavy thunderstorm'              => '🌩️⚡',
	'ragged thunderstorm'             => '⛈️',
	'thunderstorm with light drizzle' => '⛈️',
	'thunderstorm with drizzle'       => '⛈️',
	'thunderstorm with heavy drizzle' => '⛈️',

	// Snow (all OpenWeather snow descriptions)
	'light snow'                      => '🌨️',
	'snow'                            => '❄️',
	'heavy snow'                      => '🌨️❄️',
	'sleet'                           => '🌨️',
	'light shower sleet'              => '🌨️',
	'shower sleet'                    => '🌨️',
	'light rain and snow'             => '🌧️❄️',
	'rain and snow'                   => '🌧️❄️',
	'light shower snow'               => '🌨️',
	'shower snow'                     => '🌨️',
	'heavy shower snow'               => '🌨️❄️',
);


$mwpl_condition_icon = $mwpl_conditions_map[ $mwpl_desc_raw ] ?? '❔';

$mwpl_hourly = isset( $weather['hourly'] ) ? $weather['hourly'] : [];
?>

<div class="weather-card mw-card card-11"
     data-lat="<?php echo esc_attr( $atts['lat'] ); ?>"
     data-lon="<?php echo esc_attr( $atts['lon'] ); ?>"
    data-tzoffset="<?php echo esc_attr( $mwpl_tz_offset ); ?>">

    <h3 class="mw-title"><?php echo esc_html( $mwpl_label ); ?></h3>

    <div class="mw-now">
        <img
            src="<?php echo esc_url( $mwpl_icon_url ); ?>"
            alt="<?php echo esc_attr( $mwpl_current['weather'][0]['description'] ?? 'Current weather' ); ?>"
            class="mw-main-icon"
        />

        <div class="mw-hourly-strip">
            <?php for ( $mwpl_i = 0; $mwpl_i < 6; $mwpl_i++ ) : ?>
                <?php
                $mwpl_hour = $mwpl_hourly[ $mwpl_i ] ?? null;
                if ( ! $mwpl_hour ) {
                    continue;
                }

                $mwpl_icon       = $mwpl_hour['weather'][0]['icon'] ?? '01d';
                $mwpl_desc       = $mwpl_hour['weather'][0]['description'] ?? 'N/A';
                $mwpl_temp       = isset( $mwpl_hour['temp'] ) ? round( $mwpl_hour['temp'] ) : null;
                $mwpl_hour_label = mwpl_gmdate( 'g A', $mwpl_hour['dt'] );
                ?>
                <div class="mw-hour">
                    <div class="mw-hour-time" data-unixtime="<?php echo esc_attr( $mwpl_hour['dt'] ); ?>">
                        <?php echo esc_html( $mwpl_hour_label ); ?>
                    </div>

                    <img
                        class="mw-hour-icon"
                        src="https://openweathermap.org/img/wn/<?php echo esc_attr( $mwpl_icon ); ?>.png"
                        alt="<?php echo esc_attr( $mwpl_desc ); ?>"
                    />

                    <div class="mw-hour-temp">
                        <?php
                        if ( null !== $mwpl_temp ) {
                            echo esc_html( $mwpl_temp ) . '°';
                        } else {
                            echo esc_html( 'N/A' );
                        }
                        ?>
                    </div>
                </div>
            <?php endfor; ?>
        </div>

        <div class="mw-temp">
            <?php echo esc_html( $mwpl_condition_icon ); ?>
            <?php if ( isset( $mwpl_current['temp'] ) ) : ?>
                <?php echo esc_html( round( $mwpl_current['temp'] ) ); ?>°
            <?php endif; ?>

            <?php if ( isset( $mwpl_current['feels_like'] ) ) : ?>
                (<?php
                $mwpl_feels_text = 'Feels like ' . round( $mwpl_current['feels_like'] ) . '°';
                echo esc_html( $mwpl_feels_text );
                ?>)
            <?php endif; ?>
        </div>

        <div class="mw-desc">
            <?php echo esc_html( ucwords( $mwpl_current['weather'][0]['description'] ?? '' ) ); ?>
        </div>
    </div>

    <div class="mw-stats-wrapper">
        <div class="mw-stat">
            🌅 Sunrise:
            <span class="local-time" data-utc="<?php echo esc_attr( $mwpl_current['sunrise'] ); ?>"></span>
        </div>

        <div class="mw-stat">
            🌇 Sunset:
            <span class="local-time" data-utc="<?php echo esc_attr( $mwpl_current['sunset'] ); ?>"></span>
        </div>

        <?php
        if ( isset( $mwpl_current['wind_speed'], $mwpl_current['wind_deg'] ) ) {
            $mwpl_speed_mps = $mwpl_current['wind_speed'];
            $mwpl_deg       = $mwpl_current['wind_deg'];

            $mwpl_dirs     = [ 'N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW' ];
            $mwpl_dirIndex = (int) ( ( $mwpl_deg / 22.5 ) + 0.5 ) % 16;
            $mwpl_compass  = $mwpl_dirs[ $mwpl_dirIndex ];

            $mwpl_wind_speed = ( 'imperial' === $mwpl_unit )
                ? round( $mwpl_speed_mps * 2.237, 1 ) . ' mph'
                : round( $mwpl_speed_mps * 3.6, 1 ) . ' km/h';

            echo '<div class="mw-stat">💨 Wind: ' . esc_html( $mwpl_wind_speed . ' 🧭 ' . $mwpl_compass ) . '</div>';
        } else {
            echo '<div class="mw-stat">💨 Wind: --</div>';
        }
        ?>

        <div class="mw-stat">📡 Visibility: <?php echo esc_html( $mwpl_current['visibility'] / 1000 ); ?> km</div>
        <div class="mw-stat">☁️ Cloudiness: <?php echo esc_html( $mwpl_current['clouds'] ); ?>%</div>
        <div class="mw-stat">💧 Humidity: <?php echo esc_html( $mwpl_current['humidity'] ); ?>%</div>
        <div class="mw-stat">📈 Pressure: <?php echo esc_html( $mwpl_current['pressure'] ); ?> hPa</div>
        <div class="mw-stat">🔆 UV Index: <?php echo esc_html( $mwpl_current['uvi'] ); ?></div>
    </div>

    <h4 class="mw-forecast-title">3 Day Outlook</h4>

    <div class="mw-forecast-strip">
        <?php for ( $mwpl_i = 1; $mwpl_i <= 3; $mwpl_i++ ) : ?>
            <?php
            $mwpl_day = $weather['daily'][ $mwpl_i ] ?? null;
            if ( ! $mwpl_day ) {
                continue;
            }
            $mwpl_day_label = mwpl_gmdate( 'D', $mwpl_day['dt'] );
            ?>
            <div class="mw-forecast-item">
                <div class="mw-day local-day" data-utc="<?php echo esc_attr( $mwpl_day['dt'] ); ?>">
                    <?php echo esc_html( $mwpl_day_label ); ?>
                </div>

                <div class="mw-icon">
                    <img src="https://openweathermap.org/img/wn/<?php echo esc_attr( $mwpl_day['weather'][0]['icon'] ); ?>.png"
                         alt="<?php echo esc_attr( $mwpl_day['weather'][0]['description'] ); ?>" />
                </div>

                <div class="mw-temps">
                    <?php
                    if ( isset( $mwpl_day['temp']['min'], $mwpl_day['temp']['max'] ) ) {
                        echo esc_html( round( $mwpl_day['temp']['min'] ) ) . '° / ' . esc_html( round( $mwpl_day['temp']['max'] ) ) . '°';
                    }
                    ?>
                </div>

                <div class="mw-cond">
                    <?php echo esc_html( ucwords( $mwpl_day['weather'][0]['description'] ) ); ?>
                </div>
            </div>
        <?php endfor; ?>
    </div>

    <?php if ( isset( $weather['current']['dt'] ) ) : ?>
        <?php $mwpl_timestamp = $weather['current']['dt']; ?>
        <div class="mw-freshness">
            🕒 Last updated:
            <span class="local-time" data-utc="<?php echo esc_attr( $mwpl_timestamp ); ?>"></span>
            <?php
            $mwpl_minutes_ago = floor( ( time() - $mwpl_timestamp ) / 60 );
            if ( $mwpl_minutes_ago >= 1 ) {
                $mwpl_minutes_text = $mwpl_minutes_ago . ' min' . ( $mwpl_minutes_ago > 1 ? 's' : '' ) . ' ago';
                echo '<span>(' . esc_html( $mwpl_minutes_text ) . ')</span>';
            }
            ?>
        </div>
    <?php endif; ?>

</div>
