<?php

add_action( 'wp_enqueue_scripts', 'cascapedia_st_jules_enqueue_assets' );
function cascapedia_st_jules_enqueue_assets(): void {
	$manifest_path = get_theme_file_path( 'assets/dist/.vite/manifest.json' );

	if ( ! file_exists( $manifest_path ) ) {
		return;
	}

	$manifest = json_decode( file_get_contents( $manifest_path ), true );
	$entry = $manifest['assets/src/main.tsx'] ?? null;

	if ( ! is_array( $entry ) ) {
		return;
	}

	if ( ! empty( $entry['css'] ) && is_array( $entry['css'] ) ) {
		foreach ( $entry['css'] as $index => $css_file ) {
			$css_path = get_theme_file_path( 'assets/dist/' . $css_file );
			wp_enqueue_style(
				'cascapedia-st-jules-' . $index,
				get_theme_file_uri( 'assets/dist/' . $css_file ),
				[],
				file_exists( $css_path ) ? (string) filemtime( $css_path ) : wp_get_theme()->get( 'Version' )
			);
		}
	}

	if ( ! empty( $entry['file'] ) ) {
		$js_path = get_theme_file_path( 'assets/dist/' . $entry['file'] );
		wp_enqueue_script(
			'cascapedia-st-jules-app',
			get_theme_file_uri( 'assets/dist/' . $entry['file'] ),
			[],
			file_exists( $js_path ) ? (string) filemtime( $js_path ) : wp_get_theme()->get( 'Version' ),
			true
		);

		$page_data = cascapedia_st_jules_current_page_data();
		$site_data = cascapedia_st_jules_site_data();
		wp_add_inline_script(
			'cascapedia-st-jules-app',
			'window.__CASCA_PAGE__ = ' . wp_json_encode( $page_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) . ';' . "\n" .
			'window.__CASCA_SITE__ = ' . wp_json_encode( $site_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) . ';',
			'before'
		);
	}
}
