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

require_once plugin_dir_path( __FILE__ ) . '../inc/icon-loader.php';
require_once plugin_dir_path( __FILE__ ) . '../inc/utilities.php';

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

// Store raw label and escape on output.
$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-<?php echo esc_attr( intval( $card ) ); ?>"
     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 ); ?>"
     style="
        background:#ffffff;
        color:#111;
        padding:1.5rem;
        border-radius:12px;
        box-shadow:0 0 12px rgba(0,0,0,0.05);
        font-family:'Segoe UI', Roboto, sans-serif;
        font-size:16px;
        text-align:center;
        width:100%;
        max-width:480px;
        margin:0 auto;
        box-sizing:border-box;
        overflow:hidden;
     ">

	<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' ); ?>"
			style="width:150px;height:auto;display:block;margin:0 auto 0.75rem;"
		/>

		<!-- HOURLY STRIP -->
		<div class="mw-hourly-strip"
		     style="
                 display:flex;
                 flex-wrap:nowrap;
                 justify-content:center;
                 align-items:flex-start;
                 gap:0.5rem;
                 overflow-x:auto;
                 scrollbar-width:none;
                 -webkit-overflow-scrolling:touch;
             ">
			<?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'] ) : 'N/A';
				$mwpl_hour_label = mwpl_gmdate( 'g A', $mwpl_hour['dt'] ); // simple fallback hour label
				?>
				<div class="mw-hour"
				     style="
                        flex:0 0 70px;
                        text-align:center;
                        display:flex;
                        flex-direction:column;
                        align-items:center;
                        justify-content:flex-start;
                     ">
					<div class="mw-hour-time"
					     data-unixtime="<?php echo esc_attr( $mwpl_hour['dt'] ); ?>"
					     style="
                            font-size:12px;
                            font-weight:600;
                            margin-bottom:2px;
                            color:#111;
                            line-height:1.2;
                            white-space:nowrap;
                         ">
						<?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 ); ?>"
						style="
                            width:64px;
                            height:64px;
                            display:block;
                            margin:0 auto 3px;
                        "
					/>

					<div class="mw-hour-temp"
					     style="
                            font-size:13px;
                            font-weight:600;
                            margin-top:0;
                         ">
						<?php echo esc_html( $mwpl_temp ); ?>°
					</div>
				</div>
			<?php endfor; ?>
		</div>

		<div class="mw-temp">
			<?php echo esc_html( $mwpl_condition_icon ); ?>
			<?php echo esc_html( round( $mwpl_current['temp'] ) ); ?>°
			(Feels like <?php echo esc_html( round( $mwpl_current['feels_like'] ) ); ?>°)
		</div>

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

	<!-- STATS GRID -->
	<div class="mw-stats-wrapper"
	     style="
             display:grid;
             grid-template-columns:1fr 1fr;
             gap:0.5rem 1.25rem;
             justify-items:center;
             text-align:center;
         ">
		<div class="mw-stat">
			🌅 Sunrise:
			<?php if ( ! empty( $mwpl_current['sunrise'] ) ) : ?>
				<span class="local-time" data-utc="<?php echo esc_attr( $mwpl_current['sunrise'] ); ?>">
					<?php echo esc_html( mwpl_gmdate( 'H:i', (int) $mwpl_current['sunrise'] ) ); ?>
				</span>
			<?php else : ?>
				<span>--</span>
			<?php endif; ?>
		</div>

		<div class="mw-stat">
			🌇 Sunset:
			<?php if ( ! empty( $mwpl_current['sunset'] ) ) : ?>
				<span class="local-time" data-utc="<?php echo esc_attr( $mwpl_current['sunset'] ); ?>">
					<?php echo esc_html( mwpl_gmdate( 'H:i', (int) $mwpl_current['sunset'] ) ); ?>
				</span>
			<?php else : ?>
				<span>--</span>
			<?php endif; ?>
		</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
			if ( isset( $mwpl_current['visibility'] ) && is_numeric( $mwpl_current['visibility'] ) ) {
				echo esc_html( ( (int) $mwpl_current['visibility'] / 1000 ) ) . ' km';
			} else {
				echo '--';
			}
			?>
		</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>

	<!-- 3-DAY STRIP -->
	<div class="mw-forecast-strip"
	     style="
             display:flex;
             flex-wrap:nowrap;
             justify-content:center;
             gap:0.4rem;
             overflow-x:auto;
             padding-bottom:0.5rem;
             scrollbar-width:none;
             -webkit-overflow-scrolling:touch;
         ">
		<?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'] ); // Wed / Thu / Fri
			?>
			<div class="mw-forecast-item"
			     style="
                     background:#f2f2f2;
                     border-radius:8px;
                     padding:0.5rem 0.4rem;
                     text-align:center;
                     flex:0 0 auto;
                     min-width:100px;
                 ">
				<div class="mw-day local-day"
				     data-utc="<?php echo esc_attr( $mwpl_day['dt'] ); ?>"
				     style="
                        font-weight:600;
                        margin-bottom:0.3rem;
                        color:#000;
                     ">
					<?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 echo esc_html( round( $mwpl_day['temp']['min'] ) ); ?>° /
					<?php echo 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_ago_label = $mwpl_minutes_ago . ' min' . ( $mwpl_minutes_ago > 1 ? 's' : '' ) . ' ago';
				echo '<span>(' . esc_html( $mwpl_ago_label ) . ')</span>';
			}
			?>
		</div>
	<?php endif; ?>

</div>
