<?php

namespace Waypoint\Agent\Admin;

use Waypoint\Agent\Base\Thing;

class Login_Logo extends Thing {

	const CUSTOMIZE_SETTING = 'waypoint_login_logo';

	public function attach_hooks(): void {
		add_action( 'customize_register',    [ $this, 'register_customizer_control' ] );
		add_action( 'login_enqueue_scripts', [ $this, 'enqueue_logo_css' ] );
	}

	public function register_customizer_control( \WP_Customize_Manager $wp_customize ): void {
		$wp_customize->add_setting(
			self::CUSTOMIZE_SETTING,
			[
				'type'              => 'option',
				'capability'        => 'manage_options',
				'sanitize_callback' => 'absint',
				'transport'         => 'refresh',
			]
		);

		$wp_customize->add_control(
			new \WP_Customize_Media_Control(
				$wp_customize,
				self::CUSTOMIZE_SETTING,
				[
					'label'       => __( 'Login Page Logo', 'waypoint-agent' ),
					'description' => __( 'Replaces the WordPress logo on the login page. Falls back to Site Icon, then the Waypoint logo.', 'waypoint-agent' ),
					'section'     => 'title_tagline',
					'mime_type'   => 'image',
					'priority'    => 70,
				]
			)
		);
	}

	public function enqueue_logo_css(): void {
		$attachment_id = (int) get_option( self::CUSTOMIZE_SETTING, 0 );

		if ( $attachment_id ) {
			$url = wp_get_attachment_image_url( $attachment_id, 'full' );
		}

		// Fallback: Site Icon.
		if ( empty( $url ) ) {
			$url = get_site_icon_url( 84 );
		}

		if ( ! empty( $url ) ) {
			$css = $this->single_image_css( esc_url( $url ) );
		} else {
			// Final fallback: bundled Waypoint SVGs, with dark-mode variant.
			$light_url = plugins_url( 'assets/images/normal-mode.svg', WAYPOINT_AGENT_FILE );
			$dark_url  = plugins_url( 'assets/images/dark-mode.svg', WAYPOINT_AGENT_FILE );
			$css       = $this->dual_image_css( esc_url( $light_url ), esc_url( $dark_url ) );
		}

		wp_add_inline_style( 'login', $css );
	}

	private function single_image_css( string $url ): string {
		return "
.login h1 a {
	background-image: url({$url});
	background-size: contain;
	background-repeat: no-repeat;
	background-position: center top;
	width: 84px;
	height: 84px;
}";
	}

	private function dual_image_css( string $light_url, string $dark_url ): string {
		return "
.login h1 a {
	background-image: url({$light_url});
	background-size: contain;
	background-repeat: no-repeat;
	background-position: center top;
	width: 84px;
	height: 84px;
}
@media (prefers-color-scheme: dark) {
	.login h1 a {
		background-image: url({$dark_url});
	}
}";
	}
}
