<?php
/**
 * Performance optimizations.
 *
 * @package EasySite_Pro
 */

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

/**
 * Apply performance tweaks based on theme mods.
 */
function easysite_performance_init() {
	$lazy = easysite_get_mod( 'easysite_lazy_load', true );

	// Basic tier: lazy load on by default via filter.
	if ( $lazy ) {
		add_filter( 'wp_lazy_loading_enabled', '__return_true' );
		add_filter( 'the_content', 'easysite_add_loading_lazy' );
	}

	if ( easysite_is_bundle() ) {
		if ( easysite_get_mod( 'easysite_disable_emojis', true ) ) {
			remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
			remove_action( 'wp_print_styles', 'print_emoji_styles' );
			remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
			remove_action( 'admin_print_styles', 'print_emoji_styles' );
		}

		if ( easysite_get_mod( 'easysite_disable_widgets', false ) ) {
			add_action( 'widgets_init', 'easysite_disable_unused_widgets', 99 );
		}

		if ( easysite_get_mod( 'easysite_preload_fonts', false ) ) {
			add_action( 'wp_head', 'easysite_preload_fonts', 1 );
		}
	}
}
add_action( 'init', 'easysite_performance_init' );

/**
 * Add loading="lazy" to content images without it.
 *
 * @param string $content Post content.
 * @return string
 */
function easysite_add_loading_lazy( $content ) {
	if ( false === strpos( $content, '<img' ) ) {
		return $content;
	}
	return preg_replace( '/<img((?![^>]*loading=)[^>]*)>/i', '<img$1 loading="lazy">', $content );
}

/**
 * Disable block widgets if toggled (classic widgets only simplification).
 */
function easysite_disable_unused_widgets() {
	remove_theme_support( 'widgets-block-editor' );
}

/**
 * Preload Google Fonts.
 */
function easysite_preload_fonts() {
	$pair_key = easysite_get_mod( 'easysite_font_pair', 'inter-system' );
	$pairs    = easysite_get_font_pairs();
	if ( empty( $pairs[ $pair_key ]['google'] ) ) {
		return;
	}
	$url = 'https://fonts.googleapis.com/css2?family=' . rawurlencode( str_replace( '|', '&family=', $pairs[ $pair_key ]['google'] ) ) . '&display=swap';
	printf( '<link rel="preload" href="%s" as="style" />', esc_url( $url ) );
}

/**
 * Optionally minify enqueued styles (basic concatenation stub).
 *
 * @param string $html   Link tag HTML.
 * @param string $handle Handle.
 * @return string
 */
function easysite_maybe_minify_style( $html, $handle ) {
	if ( ! easysite_is_bundle() || ! easysite_get_mod( 'easysite_minify_assets', false ) ) {
		return $html;
	}
	if ( 0 === strpos( $handle, 'easysite-' ) ) {
		$html = str_replace( "media='all'", "media='all' data-easysite-minify='1'", $html );
	}
	return $html;
}
add_filter( 'style_loader_tag', 'easysite_maybe_minify_style', 10, 2 );
