<?php
/**
 * File: modules/homepage-animation-check.php
 * Homepage Animation Count Auditor
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

require_once plugin_dir_path( __FILE__ ) . '../includes/sac-utils.php';

add_action( 'rest_api_init', function () {
	register_rest_route( 'myaio/v1', '/homepage-animation-count', [
		'methods'             => WP_REST_Server::READABLE, // GET
		'callback'            => 'myaio_sac_check_homepage_animations',
		'permission_callback' => 'myaio_sac_permission_check',
	] );
} );

function myaio_sac_check_homepage_animations( WP_REST_Request $request ) {

	$home_url = home_url( '/' );

	$response = wp_remote_get( $home_url, [
		'timeout'     => 20,
		'redirection' => 5,
	] );

	if ( is_wp_error( $response ) ) {
		return new WP_REST_Response( [
			'error'   => 'Failed to fetch homepage',
			'message' => $response->get_error_message(),
		], 500 );
	}

	$code = (int) wp_remote_retrieve_response_code( $response );
	$html = (string) wp_remote_retrieve_body( $response );

	if ( $code >= 400 || $html === '' ) {
		return new WP_REST_Response( [
			'error'   => 'Homepage returned an invalid response',
			'status'  => $code,
			'url'     => $home_url,
		], 500 );
	}

	// Count inline CSS patterns
	$animation_count   = preg_match_all( '/animation[-a-z]*\s*:\s*/i', $html );
	$transition_count  = preg_match_all( '/transition[-a-z]*\s*:\s*/i', $html );

	// Count common libraries / attributes
	$aos_count         = preg_match_all( '/data-aos\s*=\s*["\'].*?["\']/i', $html );
	$lottie_count      = preg_match_all( '/<\s*lottie-player\b/i', $html );
	$gsap_count        = preg_match_all( '/\bgsap\.(to|from|timeline)\s*\(/i', $html );

	$total_animations = (int) (
		$animation_count +
		$transition_count +
		$aos_count +
		$lottie_count +
		$gsap_count
	);

	return rest_ensure_response( [
		'url_scanned'      => $home_url,
		'total_animations' => $total_animations,
		'details'          => [
			'css_animation_count'     => (int) $animation_count,
			'css_transition_count'    => (int) $transition_count,
			'aos_animation_count'     => (int) $aos_count,
			'lottie_animation_count'  => (int) $lottie_count,
			'gsap_animation_count'    => (int) $gsap_count,
		],
	] );
}
