<?php
/**
 * Prepares response payload for the SpectatorViews main view endpoint.
 *
 * @package Ilabs\Firevert\Modules\SpectatorViews\Api\Preparer
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\SpectatorViews\Api\Preparer;

use Ilabs\Firevert\Core\Services\Helper\Integration\LanguageHelper;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Helper\SpectatorTextPreparer;
use Ilabs\Firevert\Modules\SpectatorViews\Services\SpectatorTrackingService;
use WP_Post;

/**
 * Class RenderResponsePreparer
 */
class RenderResponsePreparer {

	/**
	 * Prepares the final frontend payload based on the widget data.
	 *
	 * @param int|null                 $product_id Product ID.
	 * @param WP_Post                  $post Widget post instance.
	 * @param array                    $data SpectatorViews data.
	 * @param SpectatorTrackingService $service SpectatorTrackingService.
	 *
	 * @return array<string, mixed> Final response data structure for frontend rendering.
	 */
	public static function prepare_main_response(
		?int $product_id,
		WP_Post $post,
		array $data,
		SpectatorTrackingService $service
	): array {
		$count = null !== $product_id ? $service->count_active( $product_id ) : 0;
		return array(
			'el'     => '#spectator-views-' . $post->ID,
			'locale' => LanguageHelper::get_active_region_code(),
			'config' => array(
				'visibleForAdminOnly' => $data['firevert_spectator_views_visible_admin_only'] ?? false,
				'isAdmin'             => current_user_can( 'manage_options' ),
			),
			'theme'  => array(
				'backgroundColor' => $data['firevert_spectator_views_background'] ?? '#ffffff',
				'accentColor'     => $data['firevert_spectator_views_accent_color'] ?? '#9900ff',
				'textColor'       => $data['firevert_spectator_views_primary_text'] ?? '#000000',
				'border'          => array(
					'enabled' => $data['firevert_spectator_views_add_border'] ?? false,
					'color'   => $data['firevert_spectator_views_border_color'] ?? '#cccccc',
				),
				'shadow'          => $data['firevert_spectator_views_add_shadow'] ?? false,
				'borderRadius'    => $data['firevert_spectator_views_border_radius'] ?? '0',
			),
			'state'  => array(
				'viewersCount' => $count,
				'productId'    => $product_id,
				'text'         => SpectatorTextPreparer::get_spectator_text( $count ),
			),
		);
	}
}
