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

// Needed by icon-loader; keep name but silence PHPCS.
$icon_pack = 'erikflowers'; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

wp_enqueue_style(
	'erik-icons-core',
	plugin_dir_url( __FILE__ ) . '../weather-icons/css/weather-icons.css',
	array(),
	'1.0.0'
);

wp_enqueue_style(
	'mw-card10-style',
	plugin_dir_url( __FILE__ ) . '../assets/card/card10-style.css',
	array(),
	time()
);

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

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

$mwpl_moon_phase = $mwpl_daily[0]['moon_phase'] ?? null;
$mwpl_moon_image = 'moon-new.png';

if ( null !== $mwpl_moon_phase ) {
	if ( 0 === $mwpl_moon_phase || 1 === $mwpl_moon_phase ) {
		$mwpl_moon_image = 'moon-new.png';
	} elseif ( $mwpl_moon_phase > 0 && $mwpl_moon_phase < 0.25 ) {
		$mwpl_moon_image = 'moon-waxing-crescent.png';
	} elseif ( 0.25 === $mwpl_moon_phase ) {
		$mwpl_moon_image = 'moon-first-quarter.png';
	} elseif ( $mwpl_moon_phase > 0.25 && $mwpl_moon_phase < 0.5 ) {
		$mwpl_moon_image = 'moon-waxing-gibbous.png';
	} elseif ( 0.5 === $mwpl_moon_phase ) {
		$mwpl_moon_image = 'moon-full.png';
	} elseif ( $mwpl_moon_phase > 0.5 && $mwpl_moon_phase < 0.75 ) {
		$mwpl_moon_image = 'moon-waning-gibbous.png';
	} elseif ( 0.75 === $mwpl_moon_phase ) {
		$mwpl_moon_image = 'moon-last-quarter.png';
	} elseif ( $mwpl_moon_phase > 0.75 && $mwpl_moon_phase < 1.0 ) {
		$mwpl_moon_image = 'moon-waning-crescent.png';
	}
}

$mwpl_moon_image_url = plugin_dir_url( __FILE__ ) . '../assets/icons/moon/' . $mwpl_moon_image;

$mwpl_alerts   = $weather['alerts'] ?? array();
$mwpl_location = $weather['weather'][0] ?? array();

// Store raw label; escape on output.
$mwpl_label_raw   = $atts['label'] ?? "{$atts['lat']}, {$atts['lon']}";
$mwpl_unit        = $atts['units'] ?? 'metric';
$mwpl_unit_symbol = ( 'imperial' === $mwpl_unit ) ? '°F' : '°C';

if ( ! function_exists( 'format_wind' ) ) {
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
	function format_wind( $speed, $deg ) {
		return round( $speed ) . ' ' . ( $speed > 0 ? '🧭 ' . $deg . '°' : '' );
	}
}
?>
<div class="mw-card card-10"
     data-lat="<?php echo esc_attr( $atts['lat'] ); ?>"
     data-lon="<?php echo esc_attr( $atts['lon'] ); ?>">

	<?php
	// Frost / alert logic (unit-safe).
	$mwpl_temp = $mwpl_current['temp'];
	$mwpl_dew  = $mwpl_current['dew_point'];

	if ( 'imperial' === $mwpl_unit ) {
		$mwpl_temp = ( $mwpl_temp - 32 ) * 5 / 9;
		$mwpl_dew  = ( $mwpl_dew - 32 ) * 5 / 9;
	}

	$mwpl_frost_risk = (
		$mwpl_temp <= 2 &&
		$mwpl_temp >= -5 &&
		( $mwpl_temp - $mwpl_dew ) <= 2
	);

	$mwpl_has_alerts = ! empty( $mwpl_alerts ) || $mwpl_frost_risk;
	?>

	<?php if ( $mwpl_has_alerts ) : ?>
		<div class="mw-alert-banner">
			<?php foreach ( $mwpl_alerts as $mwpl_alert ) : ?>
				<div class="mw-alert-item">
					<strong><?php echo esc_html( $mwpl_alert['event'] ); ?></strong>
					&nbsp;-&nbsp;
					<?php echo esc_html( $mwpl_alert['description'] ); ?>
					<small>
						<?php echo esc_html( gmdate( 'g:i A', $mwpl_alert['start'] ) ); ?>
						→
						<?php echo esc_html( gmdate( 'g:i A', $mwpl_alert['end'] ) ); ?>
						(<?php echo esc_html( $mwpl_alert['sender_name'] ); ?>)
					</small>
				</div>
			<?php endforeach; ?>

			<?php if ( $mwpl_frost_risk ) : ?>
				<div class="mw-alert-item frost-alert">
					<strong>❄️ Frost Risk Detected</strong> - Chance of frost based on local temperature and dew point.
				</div>
			<?php endif; ?>
		</div>
	<?php endif; ?>

	<div class="mw-header">
		<div class="mw-header-left">
			<div class="mw-city"><?php echo esc_html( $mwpl_label_raw ); ?></div>
			<?php
			$mwpl_tz = function_exists( 'mwpl_get_location_time' )
				? mwpl_get_location_time( $atts['lat'], $atts['lon'] )
				: null;
			?>
		</div>
		<div class="mw-date-wrap">
			<div class="mw-date"><?php echo esc_html( mwpl_gmdate( 'l, j F' ) ); ?></div>
			<div class="mw-local-time"
				<?php if ( ! empty( $mwpl_tz['name'] ) ) : ?>
					data-timezone="<?php echo esc_attr( $mwpl_tz['name'] ); ?>"
				<?php endif; ?>>
				🕓 Local time: <span class="mw-live-time">Loading...</span>
			</div>
		</div>
	</div>

	<div class="mw-current-hourly-wrap">
		<div class="mw-current">
			<div class="mw-weather-icon-wrapper">
				<i class="wi <?php echo esc_attr( mw_erikflowers_icon_map( $mwpl_current['weather'][0]['icon'] ) ); ?> mw-icon-now"></i>
				<img src="<?php echo esc_url( $mwpl_moon_image_url ); ?>" alt="Moon Phase" class="mw-moon-img" />
			</div>

			<div class="mw-temp">
				<?php echo esc_html( round( $mwpl_current['temp'] ) . $mwpl_unit_symbol ); ?>
			</div>

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

			<div class="mw-detail-grid">
				<span>
					Feels Like:
					<?php echo esc_html( round( $mwpl_current['feels_like'] ) . $mwpl_unit_symbol ); ?>
				</span>
				<span>
					Humidity:
					<?php echo esc_html( intval( $mwpl_current['humidity'] ) ); ?>%
				</span>
				<span>
					Pressure:
					<?php echo esc_html( intval( $mwpl_current['pressure'] ) ); ?> hPa
				</span>
				<span>
					Dew Point:
					<?php echo esc_html( round( $mwpl_current['dew_point'] ) . $mwpl_unit_symbol ); ?>
				</span>
				<span>
					UVI:
					<?php echo esc_html( $mwpl_current['uvi'] ); ?>
				</span>
				<span>
					Clouds:
					<?php echo esc_html( intval( $mwpl_current['clouds'] ) ); ?>%
				</span>
				<span>
					Visibility:
					<?php echo esc_html( $mwpl_current['visibility'] / 1000 ); ?> km
				</span>

				<?php
				// Wind.
				if ( isset( $mwpl_current['wind_speed'], $mwpl_current['wind_deg'] ) ) {
					$mwpl_dirs      = array( 'N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW' );
					$mwpl_deg       = $mwpl_current['wind_deg'];
					$mwpl_dir_index = (int) ( ( $mwpl_deg / 22.5 ) + 0.5 ) % 16;
					$mwpl_compass   = $mwpl_dirs[ $mwpl_dir_index ];

					$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 '<span>💨 Wind: ' . esc_html( $mwpl_wind_speed . ' ' . $mwpl_compass ) . '</span>';
				} else {
					echo '<span>💨 Wind: --</span>';
				}

				// Gust.
				if ( isset( $mwpl_current['wind_gust'] ) ) {
					$mwpl_gust           = $mwpl_current['wind_gust'];
					$mwpl_gust_converted = ( 'imperial' === $mwpl_unit )
						? round( $mwpl_gust * 2.237, 1 ) . ' mph'
						: round( $mwpl_gust * 3.6, 1 ) . ' km/h';

					echo '<span>🌬️ Gust: ' . esc_html( $mwpl_gust_converted ) . '</span>';
				} else {
					echo '<span>🌬️ Gust: --</span>';
				}
				?>

				<span>
					Rain:
					<?php echo esc_html( $mwpl_current['rain']['1h'] ?? 0 ); ?> mm
				</span>
				<span>
					Snow:
					<?php echo esc_html( $mwpl_current['snow']['1h'] ?? 0 ); ?> mm
				</span>

				<span class="mw-inline-icon">
					<i class="wi wi-sunrise"></i>
					<span class="local-time" data-utc="<?php echo esc_attr( $mwpl_current['sunrise'] ); ?>"></span>
				</span>
				<span>  </span>
				<span class="mw-inline-icon">
					<i class="wi wi-sunset"></i>
					<span class="local-time" data-utc="<?php echo esc_attr( $mwpl_current['sunset'] ); ?>"></span>
				</span>
			</div>
		</div>

		<div class="mw-hourly">
			<?php for ( $mwpl_i = 0; $mwpl_i < 6; $mwpl_i++ ) : ?>
				<?php
				$mwpl_h = $mwpl_hourly[ $mwpl_i ] ?? null;
				if ( ! $mwpl_h ) {
					continue;
				}
				?>
				<div class="mw-hour-block">
					<div class="mw-hour-time" data-unixtime="<?php echo esc_attr( $mwpl_h['dt'] ); ?>"></div>
					<i class="wi <?php echo esc_attr( mw_erikflowers_icon_map( $mwpl_h['weather'][0]['icon'] ) ); ?>"></i>
					<div class="mw-hour-temp">
						<?php echo esc_html( round( $mwpl_h['temp'] ) . $mwpl_unit_symbol ); ?>
					</div>
					<div class="mw-hour-pop">
						💧<?php echo esc_html( round( $mwpl_h['pop'] * 100 ) ); ?>%
					</div>

					<?php
					if ( isset( $mwpl_h['wind_speed'] ) ) {
						$mwpl_speed_mps  = $mwpl_h['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-hour-wind">🌬 ' . esc_html( $mwpl_wind_speed ) . '</div>';
					} else {
						echo '<div class="mw-hour-wind">🌬 --</div>';
					}
					?>

					<div class="mw-hour-extra">
						☁️ <?php echo esc_html( intval( $mwpl_h['clouds'] ) ); ?>% /
						🌧 <?php echo esc_html( $mwpl_h['rain']['1h'] ?? 0 ); ?> mm /
						❄️ <?php echo esc_html( $mwpl_h['snow']['1h'] ?? 0 ); ?> mm
					</div>
				</div>
			<?php endfor; ?>
		</div>
	</div>

	<h4 class="mw-forecast-title">7 Day Forecast</h4>

	<div class="mw-forecast-strip">
		<?php for ( $mwpl_i = 0; $mwpl_i < 7; $mwpl_i++ ) : ?>
			<?php
			$mwpl_d = $mwpl_daily[ $mwpl_i ] ?? null;
			if ( ! $mwpl_d ) {
				continue;
			}
			?>
			<div class="mw-forecast-item">
				<div class="mw-day local-day" data-utc="<?php echo esc_attr( $mwpl_d['dt'] ); ?>"></div>
				<i class="wi <?php echo esc_attr( mw_erikflowers_icon_map( $mwpl_d['weather'][0]['icon'] ) ); ?>"></i>
				<div class="mw-temps">
					<?php echo esc_html( round( $mwpl_d['temp']['min'] ) ); ?>° /
					<?php echo esc_html( round( $mwpl_d['temp']['max'] ) ); ?>°
				</div>
				<div class="mw-pop">
					💧<?php echo esc_html( round( $mwpl_d['pop'] * 100 ) ); ?>%
				</div>

				<?php
				if ( isset( $mwpl_d['wind_speed'] ) ) {
					$mwpl_wind_speed_val = $mwpl_d['wind_speed'];
					$mwpl_wind_gust_val  = $mwpl_d['wind_gust'] ?? null;

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

					if ( null !== $mwpl_wind_gust_val ) {
						$mwpl_gust_str = ( 'imperial' === $mwpl_unit )
							? round( $mwpl_wind_gust_val * 2.237, 1 ) . ' mph'
							: round( $mwpl_wind_gust_val * 3.6, 1 ) . ' km/h';

						echo '<div class="mw-wind">🌬 ' . esc_html( $mwpl_speed_str . ' (' . $mwpl_gust_str . ')' ) . '</div>';
					} else {
						echo '<div class="mw-wind">🌬 ' . esc_html( $mwpl_speed_str ) . '</div>';
					}
				} else {
					echo '<div class="mw-wind">🌬 --</div>';
				}
				?>
			</div>
		<?php endfor; ?>
	</div>

	<?php if ( isset( $weather['current']['dt'] ) ) : ?>
		<?php $mwpl_timestamp = $weather['current']['dt']; ?>
		<p class="mw-timezone-hint">
			🕒 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>';
			}
			?>
		</p>
	<?php endif; ?>

</div>
