<?php

declare(strict_types=1);

namespace Australcode\Rewards\Frontend;

use Australcode\Rewards\Domain\Settings\SettingsRepository;
use Australcode\Rewards\Service\WalletService;

defined( 'ABSPATH' ) || exit;

/**
 * Optional floating points badge (FREE, opt-in via show_floating_widget). Shows
 * the logged-in customer's balance fixed at the corner of the storefront,
 * linking to My Account. Honors dark mode / accent via the frontend CSS vars.
 */
final class FloatingWidget {

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

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

	public function render(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$settings = $this->settings->get();
		if ( ! $settings->show_floating_widget ) {
			return;
		}

		$balance = $this->wallet->get_balance( get_current_user_id() )->points_balance;
		$label   = 1 === $balance ? $settings->points_label_singular : $settings->points_label_plural;
		// Deep-link to the Rewards tab (same filterable slug as MyAccountRewards).
		$endpoint = (string) apply_filters( 'acrwd_account_endpoint', MyAccountRewards::ENDPOINT );
		$url      = function_exists( 'wc_get_account_endpoint_url' )
			? (string) wc_get_account_endpoint_url( '' !== $endpoint ? $endpoint : MyAccountRewards::ENDPOINT )
			: '#';

		printf(
			'<a class="acrwd-widget%s" href="%s" aria-label="%s"><span class="acrwd-widget-balance">%s</span> <span class="acrwd-widget-label">%s</span></a>',
			esc_attr( 'bottom-left' === $settings->floating_widget_position ? ' acrwd-widget--left' : '' ),
			esc_url( $url ),
			esc_attr__( 'View your rewards', 'australcode-points-rewards' ),
			esc_html( number_format_i18n( $balance ) ),
			esc_html( $label )
		);
	}
}
