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

// Icon pack is used by the icon loader; keep the name but silence PHPCS.
$icon_pack = 'vclouds-v2'; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Load CSS for this card.
wp_enqueue_style(
	'mw-card2-style',
	plugin_dir_url( __FILE__ ) . '../assets/card/card2-style.css',
	array(),
	time()
);

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

$mwpl_current = $weather['current'];
$mwpl_daily   = $weather['daily'][0] ?? array();

// Store raw label and escape on output.
$mwpl_label_raw = $atts['label'] ?? "{$atts['lat']}, {$atts['lon']}";
$mwpl_unit      = $atts['units'] ?? 'metric';

$mwpl_icon_url = mw_get_icon_url( $mwpl_current['weather'][0]['icon'], $icon_pack );

$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 ] ?? '❔';

// Hourly once, reused below.
$mwpl_hourly = isset( $weather['hourly'] ) ? $weather['hourly'] : array();
?>

<div class="weather-card mw-card card-2"
	data-card="<?php echo esc_attr( isset( $card ) ? intval( $card ) : 2 ); ?>"
	data-lat="<?php echo esc_attr( $atts['lat'] ); ?>"
	data-lon="<?php echo esc_attr( $atts['lon'] ); ?>">

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

	<div class="mw-now">
	  <img
		  class="mw-icon-now"
		  src="<?php echo esc_url( $mwpl_icon_url ); ?>"
		  alt="<?php echo esc_attr( $mwpl_current['weather'][0]['description'] ?? '' ); ?>"
	  />
		<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_hour_icon = $mwpl_hour['weather'][0]['icon'] ?? '01d';
				$mwpl_hour_desc = $mwpl_hour['weather'][0]['description'] ?? 'N/A';
				$mwpl_hour_temp = isset( $mwpl_hour['temp'] ) ? round( $mwpl_hour['temp'] ) : 'N/A';
				?>
				<div class="mw-hour">
					<div class="mw-hour-time" data-unixtime="<?php echo esc_attr( $mwpl_hour['dt'] ); ?>"></div>
					<img
						class="mw-hour-icon"
						src="<?php echo esc_url( mw_get_icon_url( $mwpl_hour_icon, $icon_pack ) ); ?>"
						alt="<?php echo esc_attr( $mwpl_hour_desc ); ?>"
					/>
					<div class="mw-hour-temp">
						<?php echo esc_html( $mwpl_hour_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>

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

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

		<?php
		if ( isset( $mwpl_current['wind_speed'] ) ) {
			$mwpl_speed_mps  = $mwpl_current['wind_speed'];
			$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 ) . '</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;
			}
			?>
			<div class="mw-forecast-item">
				<div class="mw-day local-day"
			     data-utc="<?php echo esc_attr( $mwpl_day['dt'] ); ?>">
				<?php
				// Fallback day label so it shows even if JS doesn’t run.
				echo esc_html( gmdate( 'D', $mwpl_day['dt'] ) );
				?>
			</div>
				<div class="mw-icon">
					<img
						src="<?php echo esc_url( mw_get_icon_url( $mwpl_day['weather'][0]['icon'], $icon_pack ) ); ?>"
						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> <!-- ✅ Closes .mw-card here -->
