<?php
/**
 * Admin: Asset Enqueueing.
 *
 * @package The Studio Player
 */

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

/**
 * Enqueue admin assets for the muxer screen.
 *
 * @param string $hook Current admin hook.
 * @return void
 */
function thespl_enqueue_admin_assets( $hook ) {
	// Allow muxer page.
	if ( false === strpos( $hook, 'thespl-muxer' ) && false === strpos( $hook, 'thespl_muxer' ) ) {
		return;
	}

	$plugin_url   = THESPL_PLUGIN_URL;
	$version      = THESPL_VERSION;
	$muxer_css    = 'assets/css/admin-muxer.css';
	$muxer_js     = 'assets/js/admin-muxer-core.js';
	$muxer_css_v  = $version;
	$muxer_js_v   = $version;
	$muxer_engine = function_exists( 'thespl_get_muxer_engine' ) ? thespl_get_muxer_engine() : null;
	$engine_js    = ( $muxer_engine && method_exists( $muxer_engine, 'get_js_config' ) ) ? $muxer_engine->get_js_config() : array();

	$muxer_css_path  = THESPL_PLUGIN_DIR . $muxer_css;
	$muxer_js_path   = THESPL_PLUGIN_DIR . $muxer_js;
	$muxer_css_mtime = file_exists( $muxer_css_path ) ? filemtime( $muxer_css_path ) : false;
	$muxer_js_mtime  = file_exists( $muxer_js_path ) ? filemtime( $muxer_js_path ) : false;

	if ( false !== $muxer_css_mtime ) {
		$muxer_css_v .= '-' . (string) $muxer_css_mtime;
	}

	if ( false !== $muxer_js_mtime ) {
		$muxer_js_v .= '-' . (string) $muxer_js_mtime;
	}

	wp_enqueue_style( 'thespl-admin-muxer', $plugin_url . $muxer_css, array( 'thespl-admin-ui' ), $muxer_css_v );

	// Enqueue LibFLAC (core audio engine).
	wp_enqueue_script( 'thespl-libflac', $plugin_url . 'assets/libs/libflac/libflac.js', array(), '5.4.0', true );

	wp_add_inline_script(
		'thespl-libflac',
		'window.__thesplConsoleBackup=(function(){var c=window.console||{};return{log:c.log,warn:c.warn,error:c.error,info:c.info,debug:c.debug};})();',
		'before'
	);

	wp_add_inline_script(
		'thespl-libflac',
		'(function(){var b=window.__thesplConsoleBackup;if(!b){return;}if(typeof window.console==="undefined"){window.console={};}if(b.log){window.console.log=b.log;}if(b.warn){window.console.warn=b.warn;}if(b.error){window.console.error=b.error;}if(b.info){window.console.info=b.info;}if(b.debug){window.console.debug=b.debug;}})();',
		'after'
	);

	$deps = array( 'jquery', 'thespl-libflac' );
	wp_enqueue_script( 'thespl-admin-muxer-core', $plugin_url . $muxer_js, $deps, $muxer_js_v, true );

	wp_add_inline_script(
		'thespl-admin-muxer-core',
		'(function(){var restore=function(){var b=window.__thesplConsoleBackup;if(!b){return;}if(typeof window.console==="undefined"){window.console={};}if(b.log){window.console.log=b.log;}if(b.warn){window.console.warn=b.warn;}if(b.error){window.console.error=b.error;}if(b.info){window.console.info=b.info;}if(b.debug){window.console.debug=b.debug;}};if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",restore,{once:true});}else{restore();}})();',
		'after'
	);

	// Localize script for AJAX and paths.
	wp_localize_script(
		'thespl-admin-muxer-core',
		'thespl_muxer_vars',
		array(
			'ajax_url'          => admin_url( 'admin-ajax.php' ),
			'nonce'             => wp_create_nonce( 'thespl_muxer_nonce' ),
			'home_url'          => home_url(),
			'plugin_url'        => $plugin_url,
			'max_upload_size'   => wp_max_upload_size(),
			'build_type'        => thespl_get_build_type(),
			'has_pro_assets'    => thespl_has_pro_assets(),
			'engine'            => $engine_js,
			'admin_post_url'    => admin_url( 'post.php' ),
			'upload_subdir'     => ( function () {
				$muxer = thespl_get_muxer_settings();
				return $muxer['subdir'];
			} )(),
			'upload_chunk_size' => ( function () {
				$muxer = thespl_get_muxer_settings();
				return $muxer['chunk_size'];
			} )(),
		)
	);

	wp_localize_script(
		'thespl-admin-muxer-core',
		'thesplMuxerI18n',
		array(
			'selectPlaylist'                => __( 'Select a playlist…', 'the-studio-player' ),
			'failedLoadPlaylists'           => __( 'Failed to load playlists', 'the-studio-player' ),
			'networkError'                  => __( 'Network error', 'the-studio-player' ),
			'pleaseSelectPlaylist'          => __( 'Please select a playlist', 'the-studio-player' ),
			'sending'                       => __( 'Sending…', 'the-studio-player' ),
			'appendError'                   => __( 'Append error', 'the-studio-player' ),
			'createError'                   => __( 'Create error', 'the-studio-player' ),
			'creatingPlaylist'              => __( 'Creating playlist…', 'the-studio-player' ),
			'saved'                         => __( 'Saved', 'the-studio-player' ),
			'analyzingFile'                 => __( 'Analyzing...', 'the-studio-player' ),
			'slotUnsupportedWav'            => __( 'Unsupported format.', 'the-studio-player' ),
			/* translators: %s: Detected channel count. */
			'slotUnsupportedChannels'       => __( 'Unsupported format: stereo WAV required.', 'the-studio-player' ),
			/* translators: 1: Required sample rate, 2: Required bit depth. */
			'slotUnsupportedFormatFree'     => __( 'Unsupported format: %1$s / %2$s stereo required.', 'the-studio-player' ),
			/* translators: 1: Maximum supported sample rate, 2: Maximum supported bit depth. */
			'slotUnsupportedFormatPro'      => __( 'Unsupported format: max %1$s / %2$s.', 'the-studio-player' ),
			/* translators: 1: Negotiated sample rate, 2: Negotiated bit depth. */
			'slotWarningReduced'            => __( 'Reduced to %1$s / %2$s.', 'the-studio-player' ),
			'slotDuplicate'                 => __( 'Duplicate file.', 'the-studio-player' ),
			'statusAnalyzing'               => __( 'Analyzing loaded files...', 'the-studio-player' ),
			/* translators: 1: Number of loaded files, 2: Channel count of the output FLAC. */
			'statusReady'                   => __( '%1$s files loaded -> %2$s-channel FLAC output ready.', 'the-studio-player' ),
			'statusTipReorder'              => __( 'Tip: Drag & Drop to reorder.', 'the-studio-player' ),
			/* translators: 1: Negotiated sample rate, 2: Negotiated bit depth. */
			'statusReduction'               => __( 'Export target reduced to %1$s / %2$s.', 'the-studio-player' ),
			'statusDuplicate'               => __( 'Duplicate files detected.', 'the-studio-player' ),
			'noteFreeSampleRate'            => __( '44.1 kHz required.', 'the-studio-player' ),
			'noteFreeSampleRateBlocked'     => __( '44.1 kHz required.', 'the-studio-player' ),
			'noteFreeBitDepth'              => __( '16-bit required.', 'the-studio-player' ),
			'noteFreeBitDepthBlocked'       => __( '16-bit required.', 'the-studio-player' ),
			'noteProSampleRateDefault'      => __( 'Max 48 kHz.', 'the-studio-player' ),
			'noteProSampleRateBlocked'      => __( 'Max 48 kHz.', 'the-studio-player' ),
			/* translators: %s: Negotiated sample rate. */
			'noteProSampleRateReduced'      => __( 'Reduced to %s.', 'the-studio-player' ),
			'noteProSampleRateNoUpsampling' => __( '48 kHz unavailable. Source is 44.1 kHz.', 'the-studio-player' ),
			'noteProSampleRateReady'        => __( '48 kHz available.', 'the-studio-player' ),
			'noteProBitDepthDefault'        => __( 'Max 24-bit.', 'the-studio-player' ),
			'noteProBitDepthBlocked'        => __( 'Max 24-bit.', 'the-studio-player' ),
			/* translators: %s: Negotiated bit depth. */
			'noteProBitDepthReduced'        => __( 'Reduced to %s.', 'the-studio-player' ),
			'noteProBitDepthNoUpsampling'   => __( '24-bit unavailable. Source is 16-bit.', 'the-studio-player' ),
			'noteProBitDepthReady'          => __( '24-bit available.', 'the-studio-player' ),
			'runBlockedAnalyzing'           => __( 'Please wait until file analysis is complete.', 'the-studio-player' ),
			'runBlockedNoFiles'             => __( 'Please load at least one compatible stereo WAV file before starting.', 'the-studio-player' ),
			'wfJsonProOnly'                 => __( 'Waveform JSON is available in Pro. Existing files are shown automatically in the player.', 'the-studio-player' ),
			'wfJsonProActive'               => __( 'Waveform JSON will be generated automatically.', 'the-studio-player' ),
			'chunkSizeInfo'                 => __( 'Smaller chunks are safer for unstable connections. Larger chunks are faster.', 'the-studio-player' ),
			/* translators: %s: Server upload limit label (for example \"50 MB\") */
			'chunkSizeServerLimit'          => sprintf( __( 'Your server upload limit per request is %s.', 'the-studio-player' ), size_format( wp_max_upload_size() ) ),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'thespl_enqueue_admin_assets' );

/**
 * Enqueue shared admin UI styles on plugin admin screens.
 *
 * @param string $hook Current admin hook.
 * @return void
 */
function thespl_enqueue_admin_ui_assets( $hook ) {
	if ( ! is_string( $hook ) ) {
		return;
	}
	$screen             = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
	$is_playlist_screen = is_object( $screen ) && isset( $screen->post_type ) && 'thespl_playlist' === $screen->post_type;
	$is_plugin_screen   = false !== strpos( $hook, 'the-studio-player' )
		|| false !== strpos( $hook, 'thespl-player-settings' )
		|| false !== strpos( $hook, 'thespl-muxer' )
		|| false !== strpos( $hook, 'thespl-tools' )
		|| false !== strpos( $hook, 'thespl-pro-features' )
		|| false !== strpos( $hook, 'thespl_playlist' )
		|| false !== strpos( $hook, 'thespl-license' )
		|| false !== strpos( $hook, 'thespl-help' );
	if ( ! $is_playlist_screen && ! $is_plugin_screen ) {
		return;
	}
	$rel     = 'assets/css/admin-ui.css';
	$css_url = THESPL_PLUGIN_URL . $rel;
	$css_ver = THESPL_VERSION;

	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		$css_path = THESPL_PLUGIN_DIR . $rel;
		if ( file_exists( $css_path ) ) {
			$mtime = filemtime( $css_path );
			if ( false !== $mtime ) {
				$css_ver = $css_ver . '-' . (string) $mtime;
			}
		}
	}
	wp_enqueue_style( 'thespl-admin-ui', $css_url, array(), $css_ver );

	// Enqueue shared JS for Tools, Dashboard and shared admin interactions.
	if ( $is_playlist_screen || $is_plugin_screen ) {
		wp_enqueue_script( 'thespl-admin-tools', THESPL_PLUGIN_URL . 'assets/js/admin-tools.js', array( 'jquery' ), THESPL_VERSION, true );
		wp_add_inline_script( 'thespl-admin-tools', "document.documentElement.classList.add('thespl-admin-js');", 'before' );
		wp_localize_script(
			'thespl-admin-tools',
			'thespl_tools_vars',
			array(
				'ajax_url'            => admin_url( 'admin-ajax.php' ),
				'nonce'               => wp_create_nonce( 'thespl_muxer_nonce' ),
				'sample_import_nonce' => wp_create_nonce( 'thespl_sample_import' ),
				'zip_import_nonce'    => wp_create_nonce( 'thespl_import_zip' ),
				'i18n'                => array(
					'confirmRecovery'            => __( 'This will scan all files in your entire uploads directory and try to re-associate them with the Media Library. This might take a while on large sites. Are you sure?', 'the-studio-player' ),
					'scanning'                   => __( 'Scanning filesystem', 'the-studio-player' ),
					'filesFound'                 => __( 'matching files found', 'the-studio-player' ),
					'processing'                 => __( 'Processing', 'the-studio-player' ),
					'recoveryComplete'           => __( 'Recovery complete', 'the-studio-player' ),
					'integrityComplete'          => __( 'Integrity check complete', 'the-studio-player' ),
					'verifying'                  => __( 'Verifying', 'the-studio-player' ),
					'valid'                      => __( 'valid', 'the-studio-player' ),
					'invalid'                    => __( 'corrupted/modified', 'the-studio-player' ),
					'unprotected'                => __( 'unprotected (no fingerprint)', 'the-studio-player' ),
					'duplicate'                  => __( 'duplicate attachment path', 'the-studio-player' ),
					'missing'                    => __( 'missing on disk', 'the-studio-player' ),
					'integrityWarning'           => __( 'Integrity issues detected!', 'the-studio-player' ),
					'recovered'                  => __( 'recovered/repaired', 'the-studio-player' ),
					'skipped'                    => __( 'already indexed (skipped)', 'the-studio-player' ),
					'errors'                     => __( 'Errors', 'the-studio-player' ),
					'error'                      => __( 'An error occurred.', 'the-studio-player' ),
					'networkError'               => __( 'Network error. Please try again.', 'the-studio-player' ),
					'waveformConfirm'            => __( 'This will analyze all FLAC audio created with the muxer and generate missing waveform JSON files. This might take a while on large libraries. Are you sure you want to continue?', 'the-studio-player' ),
					'waveformScanning'           => __( 'Scanning FLAC audio library', 'the-studio-player' ),
					'waveformProcessing'         => __( 'Generating waveform data', 'the-studio-player' ),
					'waveformComplete'           => __( 'Waveform rebuild complete', 'the-studio-player' ),
					'waveformNothing'            => __( 'No FLAC files without waveform were found.', 'the-studio-player' ),
					'waveformError'              => __( 'Waveform rebuild failed.', 'the-studio-player' ),
					'webAudioError'              => __( 'Your browser does not support Web Audio decoding for this task.', 'the-studio-player' ),
					'streamingChecking'          => __( 'Checking streaming routes', 'the-studio-player' ),
					'streamingComplete'          => __( 'Streaming route check complete', 'the-studio-player' ),
					'streamingRouteOk'           => __( 'routes OK', 'the-studio-player' ),
					'streamingRouteDomain'       => __( 'domain mismatches', 'the-studio-player' ),
					'streamingRouteHttp'         => __( 'HTTP errors', 'the-studio-player' ),
					'streamingRouteOkSingle'     => __( 'Route OK', 'the-studio-player' ),
					'streamingRouteDomainSingle' => __( 'Domain mismatch', 'the-studio-player' ),
					'streamingRouteHttpSingle'   => __( 'HTTP error', 'the-studio-player' ),
					'streamingRouteRedirect'     => __( 'Redirect', 'the-studio-player' ),
					'streamingHttp403'           => __( 'HTTP 403 – Forbidden (security or token issue).', 'the-studio-player' ),
					'streamingHttp404'           => __( 'HTTP 404 – Media or streaming endpoint not found.', 'the-studio-player' ),
					'streamingHttp429'           => __( 'HTTP 429 – Rate limit exceeded (too many requests).', 'the-studio-player' ),
					'streamingHttp5xx'           => __( 'HTTP 5xx – Server error on streaming endpoint.', 'the-studio-player' ),
					'streamingRouteMeta'         => __( 'No streaming route (meta file)', 'the-studio-player' ),
					'streamingRouteNoUrl'        => __( 'No streaming URL', 'the-studio-player' ),
					'streamingRouteErrorSingle'  => __( 'Route error', 'the-studio-player' ),
					'streamingWarning'           => __( 'Streaming route issues detected! Please check your domain and routing configuration.', 'the-studio-player' ),
					'playlistRouteChecking'      => __( 'Checking playlist REST routes', 'the-studio-player' ),
					'playlistRouteComplete'      => __( 'Playlist REST route check complete', 'the-studio-player' ),
					'playlistRouteWarning'       => __( 'Playlist REST route issues detected! Please check your routing, permissions, and make sure the playlists you want to test are published (not drafts).', 'the-studio-player' ),
					'samplePreparing'            => __( 'Preparing sample import…', 'the-studio-player' ),
					'sampleDownloading'          => __( 'Downloading sample package…', 'the-studio-player' ),
					'sampleVerifying'            => __( 'Verifying sample package…', 'the-studio-player' ),
					'sampleImporting'            => __( 'Importing sample playlists…', 'the-studio-player' ),
					'sampleInstalled'            => __( 'Sample data installed. Draft playlists have been created for review.', 'the-studio-player' ),
					'sampleRemoving'             => __( 'Removing sample data…', 'the-studio-player' ),
					'sampleRemoved'              => __( 'All sample playlists and media were removed.', 'the-studio-player' ),
					'sampleInitFailed'           => __( 'Sample import could not be initialized.', 'the-studio-player' ),
					'sampleFetchFailed'          => __( 'Downloading the sample package failed.', 'the-studio-player' ),
					'sampleFinalizeFailed'       => __( 'Sample package verification failed.', 'the-studio-player' ),
					'sampleStepFailed'           => __( 'Importing a sample playlist failed.', 'the-studio-player' ),
					'sampleRemoveFailed'         => __( 'Removing sample data failed.', 'the-studio-player' ),
					'importNoFileSelected'       => __( 'No file selected.', 'the-studio-player' ),
					'importUploading'            => __( 'Uploading package…', 'the-studio-player' ),
					'importProcessing'           => __( 'Processing package…', 'the-studio-player' ),
					'importImporting'            => __( 'Importing…', 'the-studio-player' ),
					'importFinalizing'           => __( 'Finalizing…', 'the-studio-player' ),
					'importComplete'             => __( 'Import complete.', 'the-studio-player' ),
					'importInitFailed'           => __( 'Initialization failed.', 'the-studio-player' ),
					'importUploadFailed'         => __( 'Upload failed.', 'the-studio-player' ),
					'importFinalizeFailed'       => __( 'Finalize failed.', 'the-studio-player' ),
					'importStepFailed'           => __( 'Import step failed.', 'the-studio-player' ),
					'importZipCompleteHint'      => __( 'Import completed. All imported playlists are saved as drafts. Please review the content and publish the playlists you want to use.', 'the-studio-player' ),
				),
				'onboarding_nonce'    => wp_create_nonce( 'thespl_dismiss_onboarding' ),
				'remote_banner_nonce' => wp_create_nonce( 'thespl_remote_dismiss_banner' ),
			)
		);

		wp_add_inline_script(
			'thespl-admin-tools',
			'(function(){var sync=function(name,warningSelector){var radios=document.querySelectorAll(\'input[name="\'+name+\'"]\');if(!radios.length){return;}var warning=document.querySelector(warningSelector);if(!warning){return;}var update=function(){var active=false;for(var i=0;i<radios.length;i++){if(radios[i].checked&&"yes"===String(radios[i].value||"")){active=true;break;}}warning.style.display=active?"":"none";};for(var i=0;i<radios.length;i++){radios[i].addEventListener("change",update);}update();};var boot=function(){sync("thespl_player_settings[uninstall_remove_uploads]",\'[data-thespl-uninstall-warning="settings"]\');sync("thespl_uninstall_remove_uploads_choice",\'[data-thespl-uninstall-warning="dashboard"]\');};if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",boot,{once:true});}else{boot();}})();',
			'after'
		);
	}

	// Enqueue shared JS for Settings page.
	if ( false !== strpos( $hook, 'thespl-player-settings' ) ) {
		wp_enqueue_script( 'thespl-admin-settings', THESPL_PLUGIN_URL . 'assets/js/admin-settings.js', array( 'jquery' ), THESPL_VERSION, true );
	}
}
add_action( 'admin_enqueue_scripts', 'thespl_enqueue_admin_ui_assets' );
