<?php
/**
 * FansPaysite asset enqueuing.
 *
 * Loads Fomantic UI as individual components (~300 KB) instead of the
 * monolithic bundle (~1.6 MB CSS + 394 KB JS) for better Core Web Vitals.
 *
 * @package FansPaysite
 * @since   2.2
 */

/**
 * Whether bundled libraries should be loaded from a CDN instead of local files.
 *
 * Disabled by default to preserve WordPress.org-friendly local bundling.
 *
 * @since 2.6
 * @return bool
 */
function fanspaysite_use_cdn_libraries() {
	return (bool) get_option( 'fanspaysite_use_cdn_libraries', false );
}

/**
 * Resolve the URL for a bundled theme library asset.
 *
 * @since 2.6
 * @param string $asset     Asset identifier.
 * @param string $component Optional Fomantic component name.
 * @return string
 */
function fanspaysite_get_library_asset_url( $asset, $component = '' ) {
	$tpl       = get_template_directory_uri();
	$component = sanitize_key( $component );

	if ( fanspaysite_use_cdn_libraries() ) {
		switch ( $asset ) {
			case 'font-awesome-css':
				return 'https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@7.1.0/css/all.min.css';
			case 'font-awesome-solid-woff2':
				return 'https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@7.1.0/webfonts/fa-solid-900.woff2';
			case 'fa-picker-css':
				return 'https://cdn.jsdelivr.net/npm/fontawesome-iconpicker@3.2.0/dist/css/fontawesome-iconpicker.min.css';
			case 'fa-picker-js':
				return 'https://cdn.jsdelivr.net/npm/fontawesome-iconpicker@3.2.0/dist/js/fontawesome-iconpicker.min.js';
			case 'fomantic-css':
				return 'https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.4/dist/components/' . $component . '.min.css';
			case 'fomantic-js':
				return 'https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.4/dist/components/' . $component . '.min.js';
		}
	}

	switch ( $asset ) {
		case 'font-awesome-css':
			return $tpl . '/lib/fa/css/all.min.css';
		case 'font-awesome-solid-woff2':
			return $tpl . '/lib/fa/webfonts/fa-solid-900.woff2';
		case 'fa-picker-css':
			return $tpl . '/lib/fa-picker/css/fontawesome-iconpicker.min.css';
		case 'fa-picker-js':
			return $tpl . '/lib/fa-picker/js/fontawesome-iconpicker.min.js';
		case 'fomantic-css':
			return $tpl . '/lib/fomantic/components/' . $component . '.min.css';
		case 'fomantic-js':
			return $tpl . '/lib/fomantic/components/' . $component . '.min.js';
		default:
			return '';
	}
}

/**
 * Check whether a bundled library asset exists locally.
 *
 * When CDN delivery is enabled, remote assets are assumed to exist.
 *
 * @since 2.3
 * @param string $asset     Asset identifier.
 * @param string $component Optional Fomantic component name.
 * @return bool
 */
function fanspaysite_library_asset_exists( $asset, $component = '' ) {
	if ( fanspaysite_use_cdn_libraries() ) {
		return true;
	}

	$tpl_dir    = get_template_directory();
	$component  = sanitize_key( $component );
	$asset_path = '';

	switch ( $asset ) {
		case 'font-awesome-css':
			$asset_path = $tpl_dir . '/lib/fa/css/all.min.css';
			break;
		case 'font-awesome-solid-woff2':
			$asset_path = $tpl_dir . '/lib/fa/webfonts/fa-solid-900.woff2';
			break;
		case 'fa-picker-css':
			$asset_path = $tpl_dir . '/lib/fa-picker/css/fontawesome-iconpicker.min.css';
			break;
		case 'fa-picker-js':
			$asset_path = $tpl_dir . '/lib/fa-picker/js/fontawesome-iconpicker.min.js';
			break;
		case 'fomantic-css':
			$asset_path = $tpl_dir . '/lib/fomantic/components/' . $component . '.min.css';
			break;
		case 'fomantic-js':
			$asset_path = $tpl_dir . '/lib/fomantic/components/' . $component . '.min.js';
			break;
	}

	return '' !== $asset_path && file_exists( $asset_path );
}

/**
 * Get the Fomantic CSS components bundled and used by the theme.
 *
 * Plugins can extend this list with the `fanspaysite_fomantic_css_components`
 * filter when they want the theme to register and enqueue extra bundled
 * components on frontend requests.
 *
 * @since 2.3
 * @return string[]
 */
function fanspaysite_get_fomantic_css_components() {
	$components = array(
		'site',
		'reset',
		'menu',
		'dropdown',
		'button',
		'divider',
		'image',
		'label',
		'comment',
		'header',
		'segment',
		'form',
		'message',
		'transition',
	);

	$components = (array) apply_filters( 'fanspaysite_fomantic_css_components', $components );
	$components = array_map( 'sanitize_key', $components );
	$components = array_filter( $components );

	return array_values( array_unique( $components ) );
}

/**
 * Get the Fomantic JS components bundled and used by the theme.
 *
 * Plugins can extend this list with the `fanspaysite_fomantic_js_components`
 * filter. Values may be passed as a keyed array of component => dependencies
 * or as a flat component list, in which case sensible defaults are applied for
 * the bundled dropdown stack.
 *
 * @since 2.3
 * @return array<string, string[]>
 */
function fanspaysite_get_fomantic_js_components() {
	$components = array(
		'site'       => array( 'jquery' ),
		'transition' => array( 'jquery', 'fomantic-site' ),
		'dropdown'   => array( 'jquery', 'fomantic-transition' ),
	);

	$components = (array) apply_filters( 'fanspaysite_fomantic_js_components', $components );
	$normalized = array();

	foreach ( $components as $component => $dependencies ) {
		if ( is_int( $component ) ) {
			$component    = sanitize_key( $dependencies );
			$dependencies = array( 'jquery' );

			if ( 'transition' === $component ) {
				$dependencies[] = 'fomantic-site';
			} elseif ( 'dropdown' === $component ) {
				$dependencies[] = 'fomantic-transition';
			}
		} else {
			$component    = sanitize_key( $component );
			$dependencies = array_map( 'sanitize_key', (array) $dependencies );
			$dependencies = array_filter( $dependencies );
		}

		if ( '' === $component ) {
			continue;
		}

		$normalized[ $component ] = array_values( array_unique( $dependencies ) );
	}

	return $normalized;
}

/**
 * Build the shared Fomantic style handle for a component.
 *
 * @since 2.3
 * @param string $component Fomantic component name.
 * @return string
 */
function fanspaysite_get_fomantic_style_handle( $component ) {
	return 'fomantic-' . sanitize_key( $component );
}

/**
 * Build the shared Fomantic script handle for a component.
 *
 * @since 2.3
 * @param string $component Fomantic component name.
 * @return string
 */
function fanspaysite_get_fomantic_script_handle( $component ) {
	return 'fomantic-' . sanitize_key( $component );
}

/**
 * Get the Fomantic style handles used by the theme.
 *
 * @since 2.3
 * @return string[]
 */
function fanspaysite_get_fomantic_style_handles() {
	$handles = array();

	foreach ( fanspaysite_get_fomantic_css_components() as $component ) {
		$handles[] = fanspaysite_get_fomantic_style_handle( $component );
	}

	return $handles;
}

/**
 * Get the Fomantic script handles used by the theme.
 *
 * @since 2.3
 * @return string[]
 */
function fanspaysite_get_fomantic_script_handles() {
	$handles = array();

	foreach ( array_keys( fanspaysite_get_fomantic_js_components() ) as $component ) {
		$handles[] = fanspaysite_get_fomantic_script_handle( $component );
	}

	return $handles;
}

/**
 * Register a single shared Fomantic stylesheet.
 *
 * @since 2.3
 * @param string $component Fomantic component name.
 * @return string Style handle, or empty string when unavailable.
 */
function fanspaysite_register_fomantic_style( $component ) {
	$component = sanitize_key( $component );

	if ( '' === $component || ! fanspaysite_library_asset_exists( 'fomantic-css', $component ) ) {
		return '';
	}

	$handle = fanspaysite_get_fomantic_style_handle( $component );

	if ( ! wp_style_is( $handle, 'registered' ) ) {
		wp_register_style(
			$handle,
			fanspaysite_get_library_asset_url( 'fomantic-css', $component ),
			array(),
			'2.9.4'
		);
	}

	return $handle;
}

/**
 * Register a single shared Fomantic script.
 *
 * @since 2.3
 * @param string   $component    Fomantic component name.
 * @param string[] $dependencies Script dependencies.
 * @return string Script handle, or empty string when unavailable.
 */
function fanspaysite_register_fomantic_script( $component, $dependencies = array() ) {
	$component = sanitize_key( $component );

	if ( '' === $component || ! fanspaysite_library_asset_exists( 'fomantic-js', $component ) ) {
		return '';
	}

	$handle = fanspaysite_get_fomantic_script_handle( $component );

	if ( ! wp_script_is( $handle, 'registered' ) ) {
		wp_register_script(
			$handle,
			fanspaysite_get_library_asset_url( 'fomantic-js', $component ),
			array_values( array_unique( array_filter( array_map( 'sanitize_key', (array) $dependencies ) ) ) ),
			'2.9.4',
			true
		);
	}

	return $handle;
}

/**
 * Enqueue bundled Fomantic components through the theme asset resolver.
 *
 * This helper lets plugins reuse the theme's local/CDN choice and shared
 * handles instead of shipping duplicate copies of the same Fomantic files.
 *
 * @since 2.3
 * @param string[]              $css_components CSS component names.
 * @param array<string,string[]> $js_components JS component names keyed to dependencies.
 * @return void
 */
function fanspaysite_enqueue_fomantic_components( $css_components = array(), $js_components = array() ) {
	foreach ( array_map( 'sanitize_key', (array) $css_components ) as $component ) {
		$handle = fanspaysite_register_fomantic_style( $component );

		if ( '' !== $handle ) {
			wp_enqueue_style( $handle );
		}
	}

	foreach ( (array) $js_components as $component => $dependencies ) {
		if ( is_int( $component ) ) {
			$component    = sanitize_key( $dependencies );
			$dependencies = array( 'jquery' );

			if ( 'transition' === $component ) {
				$dependencies[] = 'fomantic-site';
			} elseif ( 'dropdown' === $component ) {
				$dependencies[] = 'fomantic-transition';
			}
		}

		$handle = fanspaysite_register_fomantic_script( $component, (array) $dependencies );

		if ( '' !== $handle ) {
			wp_enqueue_script( $handle );
		}
	}
}

/**
 * Add a preconnect hint when CDN-hosted assets are enabled.
 *
 * @since 2.6
 * @param array  $urls          Existing resource hints.
 * @param string $relation_type Hint type.
 * @return array
 */
function fanspaysite_cdn_resource_hints( $urls, $relation_type ) {
	if ( ! fanspaysite_use_cdn_libraries() || 'preconnect' !== $relation_type ) {
		return $urls;
	}

	$urls[] = array(
		'href'        => 'https://cdn.jsdelivr.net',
		'crossorigin' => 'anonymous',
	);

	return $urls;
}
add_filter( 'wp_resource_hints', 'fanspaysite_cdn_resource_hints', 10, 2 );

/**
 * Enqueue the main theme stylesheet with cache-busting version.
 */
function fanspaysite_styles() {
	$path    = get_stylesheet_directory() . '/style.css';
	$version = file_exists( $path ) ? filemtime( $path ) : '2.2';
	wp_enqueue_style( 'fanspaysite-style', get_stylesheet_uri(), array(), $version );
	wp_style_add_data( 'fanspaysite-style', 'rtl', 'replace' );
}
add_action( 'wp_enqueue_scripts', 'fanspaysite_styles' );

/**
 * Enqueue scripts and styles.
 *
 * Fomantic UI is loaded as individual component files for the modules
 * actually used by the theme. This reduces CSS from ~1.6 MB to ~300 KB
 * and JS from ~394 KB to ~80 KB.
 */
function fanspaysite_enqueue_scripts() {
	$font_awesome_version = '7.1.0';

	// Font Awesome CSS.
	wp_enqueue_style( 'font-awesome', fanspaysite_get_library_asset_url( 'font-awesome-css' ), array(), $font_awesome_version );

	// Fomantic UI - shared components used by the theme and available to plugins.
	fanspaysite_enqueue_fomantic_components(
		fanspaysite_get_fomantic_css_components(),
		fanspaysite_get_fomantic_js_components()
	);

	// Theme menu handler.
	$menu_path = get_template_directory() . '/js/menu.js';
	$menu_ver  = file_exists( $menu_path ) ? filemtime( $menu_path ) : '2.2';
	wp_enqueue_script( 'fanspaysite-menu', get_template_directory_uri() . '/js/menu.js', array( 'jquery', 'fomantic-dropdown' ), $menu_ver, true );

	// Archive mode JS - handles fullpage navigation and auto-pagination for all modes.
	if ( is_home() || is_archive() || is_search() ) {
		$archive_path = get_template_directory() . '/js/archive.js';
		$archive_ver  = file_exists( $archive_path ) ? filemtime( $archive_path ) : '2.3';
		wp_enqueue_script( 'fanspaysite-archive', get_template_directory_uri() . '/js/archive.js', array(), $archive_ver, true );
	}
}
add_action( 'wp_enqueue_scripts', 'fanspaysite_enqueue_scripts' );

/**
 * Preload critical font files to reduce icon rendering delay.
 */
function fanspaysite_preload_fonts() {
	$woff2 = fanspaysite_get_library_asset_url( 'font-awesome-solid-woff2' );
	echo '<link rel="preload" href="' . esc_url( $woff2 ) . '" as="font" type="font/woff2" crossorigin>' . "\n";
}
add_action( 'wp_head', 'fanspaysite_preload_fonts', 2 );

/**
 * Register editor styles for the block editor.
 */
function fanspaysite_add_editor_styles() {
	add_editor_style( 'editor-style.css' );
}
add_action( 'admin_init', 'fanspaysite_add_editor_styles' );
