<?php
declare(strict_types=1);

/**
 * CSS / JS Enqueue.
 *
 * @package WTE_Business_Card
 * @since   1.0.0
 */

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

// ── Google Fonts URL Builder ───────────────────────────────
function wte_get_google_fonts_url(): string {
	$body_font    = get_theme_mod( 'wte_font_body', 'noto_sans_jp' );
	$heading_font = get_theme_mod( 'wte_font_heading', 'noto_serif_jp' );

	$font_map = [
		'noto_sans_jp'     => 'Noto+Sans+JP:wght@400;500;700',
		'noto_serif_jp'    => 'Noto+Serif+JP:wght@400;500;700',
		'zen_kaku_gothic'  => 'Zen+Kaku+Gothic+New:wght@400;500;700',
		'shippori_mincho'  => 'Shippori+Mincho:wght@400;500;700',
		'm_plus_1p'        => 'M+PLUS+1p:wght@400;500;700',
	];

	$families = [];
	if ( isset( $font_map[ $body_font ] ) ) {
		$families[] = $font_map[ $body_font ];
	}
	if ( $heading_font !== $body_font && isset( $font_map[ $heading_font ] ) ) {
		$families[] = $font_map[ $heading_font ];
	}

	if ( empty( $families ) ) {
		return '';
	}

	return 'https://fonts.googleapis.com/css2?' .
		implode( '&', array_map( fn( $f ) => 'family=' . $f, $families ) ) .
		'&display=swap';
}

// ── Font Family CSS Value ──────────────────────────────────
function wte_get_font_family( string $font_id ): string {
	$map = [
		'noto_sans_jp'     => "'Noto Sans JP', sans-serif",
		'noto_serif_jp'    => "'Noto Serif JP', serif",
		'zen_kaku_gothic'  => "'Zen Kaku Gothic New', sans-serif",
		'shippori_mincho'  => "'Shippori Mincho', serif",
		'm_plus_1p'        => "'M PLUS 1p', sans-serif",
	];
	return $map[ $font_id ] ?? "'Noto Sans JP', sans-serif";
}

// ── Frontend Assets ────────────────────────────────────────
function wte_enqueue_assets(): void {

	$uri = WTE_THEME_URI . '/assets/css';
	$ver = WTE_THEME_VERSION;

	// Google Fonts.
	$fonts_url = wte_get_google_fonts_url();
	if ( $fonts_url ) {
		wp_enqueue_style( 'wte-google-fonts', $fonts_url, [], null );
	}

	// ── CSS: Load each file individually (no @import) ──
	// Foundation.
	wp_enqueue_style( 'wte-variables',  $uri . '/variables.css',  [ 'wte-google-fonts' ], $ver );
	wp_enqueue_style( 'wte-reset',      $uri . '/reset.css',      [ 'wte-variables' ],    $ver );
	wp_enqueue_style( 'wte-typography', $uri . '/typography.css', [ 'wte-reset' ],         $ver );
	wp_enqueue_style( 'wte-layout',     $uri . '/layout.css',     [ 'wte-typography' ],    $ver );

	// Components.
	wp_enqueue_style( 'wte-buttons',    $uri . '/buttons.css',    [ 'wte-layout' ],    $ver );
	wp_enqueue_style( 'wte-forms',      $uri . '/forms.css',      [ 'wte-layout' ],    $ver );
	wp_enqueue_style( 'wte-animations', $uri . '/animations.css', [ 'wte-layout' ],    $ver );

	// Layout parts.
	wp_enqueue_style( 'wte-header-css', $uri . '/header.css', [ 'wte-buttons' ], $ver );
	wp_enqueue_style( 'wte-footer-css', $uri . '/footer.css', [ 'wte-layout' ],  $ver );

	// Sections.
	wp_enqueue_style( 'wte-hero-css',             $uri . '/hero.css',             [ 'wte-buttons' ], $ver );
	wp_enqueue_style( 'wte-services-css',         $uri . '/services.css',         [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-appeal-css',           $uri . '/appeal.css',           [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-profile-css',          $uri . '/profile.css',          [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-greeting-css',         $uri . '/greeting.css',         [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-business-details-css', $uri . '/business-details.css', [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-faq-css',              $uri . '/faq.css',              [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-sns-css',              $uri . '/sns.css',              [ 'wte-layout' ],  $ver );
	wp_enqueue_style( 'wte-contact-css',          $uri . '/contact.css',          [ 'wte-layout' ],  $ver );

	// Utilities.
	wp_enqueue_style( 'wte-utilities', $uri . '/utilities.css', [ 'wte-layout' ], $ver );
	wp_enqueue_style( 'wte-print',     $uri . '/print.css',     [ 'wte-layout' ], $ver );

	// Theme style.css (header only, required by WP).
	wp_enqueue_style( 'wte-style', get_stylesheet_uri(), [ 'wte-utilities' ], $ver );

	// ── JS ──
	wp_enqueue_script( 'wte-main-js',       WTE_THEME_URI . '/assets/js/main.js',       [], $ver, true );
	wp_enqueue_script( 'wte-header-js',      WTE_THEME_URI . '/assets/js/header.js',      [], $ver, true );
	wp_enqueue_script( 'wte-smooth-scroll',  WTE_THEME_URI . '/assets/js/smooth-scroll.js',  [], $ver, true );

	// Scroll animation & FAQ (front page only).
	if ( is_front_page() ) {
		wp_enqueue_script( 'wte-scroll-animation', WTE_THEME_URI . '/assets/js/scroll-animation.js', [], $ver, true );
		wp_enqueue_script( 'wte-faq-accordion',    WTE_THEME_URI . '/assets/js/faq-accordion.js',    [], $ver, true );
	}

	// Email protection JS (contact page only).
	if ( is_page( 'contact' ) ) {
		wp_enqueue_script( 'wte-email-protect', WTE_THEME_URI . '/assets/js/email-protect.js', [], $ver, true );
	}

	// Dequeue jQuery if not needed by plugins.
	if ( ! is_admin() && ! is_customize_preview() ) {
		wp_deregister_script( 'jquery' );
	}
}
add_action( 'wp_enqueue_scripts', 'wte_enqueue_assets', 20 );

// ── Google Fonts Preconnect ────────────────────────────────
function wte_preconnect_google_fonts( array $urls, string $relation_type ): array {
	if ( 'preconnect' === $relation_type ) {
		$urls[] = [
			'href'        => 'https://fonts.googleapis.com',
			'crossorigin' => false,
		];
		$urls[] = [
			'href'        => 'https://fonts.gstatic.com',
			'crossorigin' => 'anonymous',
		];
	}
	return $urls;
}
add_filter( 'wp_resource_hints', 'wte_preconnect_google_fonts', 10, 2 );

// ── Customizer Preview JS ──────────────────────────────────
function wte_enqueue_customizer_preview(): void {
	wp_enqueue_script(
		'wte-customizer-preview',
		WTE_THEME_URI . '/assets/js/customizer-preview.js',
		[ 'customize-preview' ],
		WTE_THEME_VERSION,
		true
	);
}
add_action( 'customize_preview_init', 'wte_enqueue_customizer_preview', 20 );

// ── Customizer Controls CSS ────────────────────────────────
function wte_enqueue_customizer_controls(): void {
	wp_enqueue_style(
		'wte-customizer-controls',
		WTE_THEME_URI . '/assets/css/admin/customizer-controls.css',
		[],
		WTE_THEME_VERSION
	);
}
add_action( 'customize_controls_enqueue_scripts', 'wte_enqueue_customizer_controls', 20 );

// ── Admin Assets (Meta Boxes) ──────────────────────────────
function wte_enqueue_admin_assets( string $hook ): void {
	if ( ! in_array( $hook, [ 'post.php', 'post-new.php' ], true ) ) {
		return;
	}

	$screen = get_current_screen();
	if ( ! $screen || 'page' !== $screen->post_type ) {
		return;
	}

	wp_enqueue_style(
		'wte-admin-meta-boxes',
		WTE_THEME_URI . '/assets/css/admin/meta-boxes.css',
		[],
		WTE_THEME_VERSION
	);

	wp_enqueue_media();

	wp_enqueue_script(
		'wte-admin-repeater',
		WTE_THEME_URI . '/assets/js/admin/admin-repeater.js',
		[],
		WTE_THEME_VERSION,
		true
	);

	wp_enqueue_script(
		'wte-admin-media-upload',
		WTE_THEME_URI . '/assets/js/admin/admin-media-upload.js',
		[ 'wte-admin-repeater' ],
		WTE_THEME_VERSION,
		true
	);
}
add_action( 'admin_enqueue_scripts', 'wte_enqueue_admin_assets', 20 );

// ── reCAPTCHA (Contact Page Only) ──────────────────────────
function wte_enqueue_recaptcha(): void {
	if ( ! is_page( 'contact' ) ) {
		return;
	}
	if ( is_customize_preview() ) {
		return;
	}

	$site_key = get_theme_mod( 'wte_recaptcha_site_key', '' );
	if ( empty( $site_key ) ) {
		return;
	}

	wp_enqueue_script(
		'wte-recaptcha-api',
		'https://www.google.com/recaptcha/api.js?render=' . esc_attr( $site_key ),
		[],
		null,
		true
	);

	wp_enqueue_script(
		'wte-recaptcha-contact',
		WTE_THEME_URI . '/assets/js/recaptcha-contact.js',
		[ 'wte-recaptcha-api' ],
		WTE_THEME_VERSION,
		true
	);

	wp_localize_script( 'wte-recaptcha-contact', 'wteRecaptcha', [
		'siteKey'   => $site_key,
		'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
		'nonce'     => wp_create_nonce( 'wte_recaptcha_nonce' ),
		'threshold' => (float) get_theme_mod( 'wte_recaptcha_score_threshold', 0.5 ),
	] );
}
add_action( 'wp_enqueue_scripts', 'wte_enqueue_recaptcha', 30 );

// ── Google Analytics ───────────────────────────────────────
function wte_output_google_analytics(): void {
	if ( is_customize_preview() ) {
		return;
	}

	$ga_id = get_theme_mod( 'wte_google_analytics_id', '' );
	if ( empty( $ga_id ) ) {
		return;
	}
	?>
	<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $ga_id ); ?>"></script>
	<script>
		window.dataLayer = window.dataLayer || [];
		function gtag(){dataLayer.push(arguments);}
		gtag('js', new Date());
		gtag('config', '<?php echo esc_js( $ga_id ); ?>');
	</script>
	<?php
}
add_action( 'wp_head', 'wte_output_google_analytics', 98 );
