<?php

declare(strict_types=1);

namespace Australcode\Rewards\Frontend;

use Australcode\Rewards\Domain\Settings\SettingsRepository;

defined( 'ABSPATH' ) || exit;

/**
 * Enqueues the frontend stylesheet and injects the configured accent color as a
 * CSS variable. When dark mode is enabled it also overrides the surface/ink
 * variables so the Australcode Rewards surfaces (widget, messages, rewards) render dark.
 */
final class FrontendAssets {

	public function __construct( private readonly SettingsRepository $settings ) {
	}

	public function register(): void {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	public function enqueue(): void {
		if ( ! $this->should_enqueue() ) {
			return;
		}

		wp_register_style( 'acrwd-frontend', ACRWD_URL . 'assets/frontend.css', array(), ACRWD_VERSION );

		$settings = $this->settings->get();
		// accent_color is validated as a 6-digit hex in the Settings VO.
		$css = sprintf( ':root{--acrwd-accent:%s;}', $settings->accent_color );
		if ( $settings->dark_mode_default ) {
			$css .= ':root{--acrwd-fg:#e2e8f0;--acrwd-muted:#94a3b8;--acrwd-border:#334155;--acrwd-surface:#0f172a;}';
		}
		wp_add_inline_style( 'acrwd-frontend', $css );

		wp_enqueue_style( 'acrwd-frontend' );
	}

	/**
	 * Only ship CSS where a rewards surface can render: the floating widget
	 * (any page, logged-in), WC surfaces (account/cart/checkout/product) or a
	 * page embedding one of the shortcodes. Builders rendering the shortcode
	 * outside post_content can force it via the acrwd_enqueue_frontend filter.
	 */
	private function should_enqueue(): bool {
		$should = false;

		if ( $this->settings->get()->show_floating_widget && is_user_logged_in() ) {
			$should = true;
		} elseif ( function_exists( 'is_account_page' ) && ( is_account_page() || is_cart() || is_checkout() || is_product() ) ) {
			$should = true;
		} else {
			$post   = get_post();
			$should = $post instanceof \WP_Post && (
				has_shortcode( (string) $post->post_content, 'acrwd_balance' )
				|| has_shortcode( (string) $post->post_content, 'acrwd_history' )
				|| has_shortcode( (string) $post->post_content, 'acrwd_earn_message' )
				|| has_shortcode( (string) $post->post_content, 'acrwd_redeem' )
				|| has_block( 'acrwd/balance', $post )
				|| has_block( 'acrwd/history', $post )
				|| has_block( 'acrwd/earn-message', $post )
				|| has_block( 'acrwd/redeem', $post )
			);
		}

		return (bool) apply_filters( 'acrwd_enqueue_frontend', $should );
	}
}
