<?php
/**
 * Frontend Assets
 *
 * Enqueues CSS and JS on single post pages only.
 * No CDN URLs — all assets are local or bundled via webpack.
 *
 * @package Relatedly\Frontend
 * @since   2.0.0
 */

namespace Relatedly\Frontend;

use Relatedly\Core\Options;

defined( 'ABSPATH' ) || exit;

/**
 * Enqueues frontend assets when Relatedly can render on the current page.
 *
 * @since 2.0.0
 */
class Assets {

	/**
	 * Plugin settings repository.
	 *
	 * @since 2.0.0
	 * @var Options
	 */
	private Options $options;

	/**
	 * Create the frontend assets service.
	 *
	 * @since 2.0.0
	 * @param Options $options Plugin settings repository.
	 */
	public function __construct( Options $options ) {
		$this->options = $options;
	}

	/**
	 * Register frontend enqueue hooks.
	 *
	 * @since 2.0.0
	 */
	public function init_hooks(): void {
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue' ] );
	}

	/**
	 * Enqueue styles and scripts for single posts.
	 *
	 * @since 2.0.0
	 */
	public function enqueue(): void {
		if ( ! is_single() || ! $this->options->get( 'enabled', true ) ) {
			return;
		}

		// Main stylesheet — includes animation keyframes (no Animate.css CDN needed).
		wp_enqueue_style(
			'relatedly-frontend',
			RELATEDLY_PLUGIN_URL . 'assets/css/frontend.css',
			[],
			RELATEDLY_VERSION
		);

		$needs_tracking = (bool) $this->options->get( 'enable_click_tracking', true );
		$end_theme      = (string) $this->options->get( 'end_content_theme', 'theme1' );
		$needs_carousel = ( 'theme4' === $end_theme );
		$needs_floating = (bool) $this->options->get( 'floating_sidebar_enabled', false );

		if ( $needs_tracking || $needs_carousel || $needs_floating ) {
			wp_enqueue_script(
				'relatedly-tracking',
				RELATEDLY_PLUGIN_URL . 'assets/js/frontend/tracking.js',
				[],
				RELATEDLY_VERSION,
				true
			);

			if ( $needs_tracking ) {
				wp_localize_script(
					'relatedly-tracking',
					'relatedlyTracking',
					[
						'ajaxUrl' => admin_url( 'admin-ajax.php' ),
						'nonce'   => wp_create_nonce( 'relatedly_track_event' ),
					]
				);
			}
		}
	}
}
