<?php
/**
 * Bundled maintenance background images.
 *
 * @package MacaHold
 */

defined( 'ABSPATH' ) || exit;

/**
 * Discovers and resolves hold#.png backgrounds from assets.
 */
class Maca_Hold_Backgrounds {

	/**
	 * Get available background images keyed by slug.
	 *
	 * @return array<string, array{id: string, label: string, url: string}>
	 */
	public static function get_available() {
		$backgrounds = array();
		$files         = glob( MACA_HOLD_PATH . 'assets/hold*.png' );

		if ( ! is_array( $files ) ) {
			$files = array();
		}

		foreach ( $files as $file ) {
			$filename = basename( $file );
			$slug     = basename( $file, '.png' );

			if ( ! preg_match( '/^hold\d+$/', $slug ) ) {
				continue;
			}

			$backgrounds[ $slug ] = array(
				'id'    => $slug,
				'label' => Maca_Hold_I18n::get_background_label( $slug ),
				'url'   => MACA_HOLD_URL . 'assets/' . $filename,
				'path'  => $file,
			);
		}

		ksort( $backgrounds, SORT_NATURAL );

		/**
		 * Filter bundled maintenance background images.
		 *
		 * @param array<string, array{id: string, label: string, url: string}> $backgrounds Background options.
		 */
		return apply_filters( 'maca_hold_backgrounds', $backgrounds );
	}

	/**
	 * Resolve a background image URL from a stored slug.
	 *
	 * @param string $slug Background slug.
	 * @return string
	 */
	public static function get_url( $slug ) {
		$slug        = sanitize_key( $slug );
		$backgrounds = self::get_available();

		if ( '' === $slug || ! isset( $backgrounds[ $slug ] ) ) {
			return '';
		}

		return $backgrounds[ $slug ]['url'];
	}

	/**
	 * Sanitize a selected background slug.
	 *
	 * @param string $slug Raw slug.
	 * @return string
	 */
	public static function sanitize( $slug ) {
		$slug        = sanitize_key( $slug );
		$backgrounds = self::get_available();

		if ( '' === $slug || ! isset( $backgrounds[ $slug ] ) ) {
			return '';
		}

		return $slug;
	}

	/**
	 * Get the filesystem path for a background slug.
	 *
	 * @param string $slug Background slug.
	 * @return string
	 */
	public static function get_path( $slug ) {
		$slug        = sanitize_key( $slug );
		$backgrounds = self::get_available();

		if ( '' === $slug || ! isset( $backgrounds[ $slug ] ) ) {
			return '';
		}

		return $backgrounds[ $slug ]['path'];
	}

	/**
	 * Detect whether an image is visually dark.
	 *
	 * @param string $slug Background slug.
	 * @return bool|null True when dark, false when light, null when unknown.
	 */
	public static function is_image_dark( $slug ) {
		$path = self::get_path( $slug );

		if ( '' === $path || ! extension_loaded( 'gd' ) || ! function_exists( 'imagecreatefrompng' ) ) {
			return null;
		}

		$image = @imagecreatefrompng( $path );

		if ( false === $image ) {
			return null;
		}

		$width  = imagesx( $image );
		$height = imagesy( $image );
		$total  = 0.0;
		$count  = 0;

		for ( $x = 1; $x <= 12; $x++ ) {
			for ( $y = 1; $y <= 12; $y++ ) {
				$pixel_x = (int) floor( ( $x - 0.5 ) / 12 * $width );
				$pixel_y = (int) floor( ( $y - 0.5 ) / 12 * $height );
				$rgb     = imagecolorat( $image, min( $pixel_x, $width - 1 ), min( $pixel_y, $height - 1 ) );
				$alpha   = ( $rgb & 0x7F000000 ) >> 24;

				if ( $alpha >= 120 ) {
					continue;
				}

				$red   = ( $rgb >> 16 ) & 0xFF;
				$green = ( $rgb >> 8 ) & 0xFF;
				$blue  = $rgb & 0xFF;
				$total += ( 0.299 * $red ) + ( 0.587 * $green ) + ( 0.114 * $blue );
				$count++;
			}
		}

		if ( 0 === $count ) {
			return null;
		}

		return ( $total / $count ) < 140;
	}

	/**
	 * Get text contrast settings for a background image.
	 *
	 * @param string $slug Background slug.
	 * @return array{text: string, accent: string, class: string, is_dark_image: bool|null}
	 */
	public static function get_contrast_profile( $slug ) {
		$is_dark = self::is_image_dark( $slug );

		if ( true === $is_dark || null === $is_dark ) {
			return array(
				'text'            => '#f8f8f8',
				'accent'          => '#d4e4f8',
				'class'           => 'maca-hold-contrast-light',
				'is_dark_image'   => $is_dark,
			);
		}

		return array(
			'text'            => '#171717',
			'accent'          => '#2f4f75',
			'class'           => 'maca-hold-contrast-dark',
			'is_dark_image'   => false,
		);
	}
}
