<?php
/**
 * Shortcodes Builder page for Sports Leagues
 *
 * Uses Alpine.js shortcodeBuilder component for reactive form handling.
 *
 * @link       https://anwp.pro
 * @since      0.5.11
 * @since      0.14.1 Refactored to use Alpine.js
 *
 * @package    Sports_Leagues
 * @subpackage Sports_Leagues/admin/views
 */

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

if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sports-leagues' ) );
}

/**
 * Get core shortcode options.
 *
 * Direct method call - no filter timing issues.
 *
 * @since 0.14.1
 */
$available_core_shortcodes = sports_leagues()->get_shortcode_options();

/**
 * Get premium shortcode options.
 *
 * Direct method call if premium plugin is active.
 *
 * @since 0.14.1
 */
$available_premium_shortcodes = [];

if ( function_exists( 'sports_leagues_premium' ) && method_exists( sports_leagues_premium(), 'get_shortcode_options' ) ) {
	$available_premium_shortcodes = sports_leagues_premium()->get_shortcode_options();
}

// Output localized shortcode options for Import feature
?>
<script type="text/javascript">
	window._sl_shortcodes_l10n = window._sl_shortcodes_l10n || {};
	window._sl_shortcodes_l10n.shortcode_options = <?php echo wp_json_encode( $available_core_shortcodes ); ?>;
	window._sl_shortcodes_l10n.shortcode_options_premium = <?php echo wp_json_encode( $available_premium_shortcodes ); ?>;
</script>

<div class="anwp-b-wrap">
	<div class="anwp-mb-2 anwp-pb-1">
		<h1 class="anwp-mb-0 anwp-d-flex anwp-items-center">
			<?php echo esc_html__( 'Shortcode Builder', 'sports-leagues' ); ?>
			<a
				href="https://anwp.pro/docs/sports-leagues/3-display-shortcodes/shortcode-builder/"
				target="_blank"
				title="<?php echo esc_attr__( 'Click to view documentation', 'sports-leagues' ); ?>"
				class="anwp-sl-help-header-link anwp-ml-2">?</a>
		</h1>
	</div>

	<hr class="anwp-mb-3">

	<div sl-x-data="shortcodeBuilder()">
		<!-- Shortcode Selector (full width) -->
		<div id="anwp-shortcode-builder__header" class="anwp-d-flex anwp-items-center anwp-mb-3">
			<label for="anwp-shortcode-builder__selector"><?php echo esc_html__( 'Shortcode', 'sports-leagues' ); ?></label>
			<select
				id="anwp-shortcode-builder__selector"
				class="anwp-mx-2"
				sl-x-model="selectedShortcode"
				sl-x-on:change="loadForm()"
			>
				<option value="">- <?php echo esc_html__( 'select', 'sports-leagues' ); ?> -</option>
				<?php foreach ( $available_core_shortcodes as $shortcode_slug => $shortcode_name ) : ?>
					<option value="<?php echo esc_attr( $shortcode_slug ); ?>"><?php echo esc_html( $shortcode_name ); ?></option>
				<?php endforeach; ?>
				<?php foreach ( $available_premium_shortcodes as $shortcode_slug => $shortcode_name ) : ?>
					<option value="<?php echo esc_attr( $shortcode_slug ); ?>"><?php echo esc_html( $shortcode_name ); ?></option>
				<?php endforeach; ?>
				<?php
				/**
				 * Hook: sports-leagues/shortcodes/selector_bottom
				 *
				 * @since 0.5.11
				 */
				do_action( 'sports-leagues/shortcodes/selector_bottom' );
				?>
			</select>
			<span class="spinner" sl-x-bind:class="{ 'is-active': loading }"></span>
		</div>

		<!-- Two-Column Layout -->
		<div class="sl-shortcode-builder">
			<!-- Form Column -->
			<div class="sl-shortcode-builder__form">

				<!-- Generated Shortcode Output -->
				<div id="anwp-shortcode-builder__composed" class="sl-section-card anwp-border anwp-border-gray-500 anwp-mb-4" sl-x-show="shortcodeString" sl-x-cloak>
					<div class="sl-section-card__header anwp-border-bottom anwp-border-gray-500 anwp-bg-white anwp-d-flex anwp-items-center anwp-px-3 anwp-py-2 anwp-text-gray-700">
						<span class="dashicons dashicons-shortcode anwp-dashicons-16 anwp-mr-2"></span>
						<span><?php echo esc_html__( 'Output', 'sports-leagues' ); ?></span>
						<button
							type="button"
							class="button button-small button-link anwp-ml-auto"
							sl-x-on:click="resetForm()"
						><?php echo esc_html__( 'Reset', 'sports-leagues' ); ?></button>
					</div>
					<div class="anwp-p-3">
						<pre
							class="anwp-shortcode-output anwp-bg-gray-100 anwp-border anwp-border-gray-400 anwp-rounded anwp-p-3 anwp-text-sm anwp-m-0"
							sl-x-text="shortcodeString"
						></pre>
					</div>
					<div class="anwp-border-top anwp-border-gray-500 anwp-px-3 anwp-py-2 anwp-d-flex anwp-align-items-center">
						<button
							type="button"
							class="button button-primary anwp-d-inline-flex anwp-items-center"
							sl-x-on:click="copyToClipboard()"
							sl-x-bind:disabled="copiedRecently"
							style="min-width: 120px; justify-content: center;"
						>
							<span class="dashicons dashicons-admin-page anwp-dashicons-16" sl-x-show="!copiedRecently"></span>
							<span class="anwp-ml-1" sl-x-show="!copiedRecently"><?php echo esc_html__( 'Copy Shortcode', 'sports-leagues' ); ?></span>
							<span sl-x-show="copiedRecently" sl-x-cloak><?php echo esc_html__( 'Copied!', 'sports-leagues' ); ?></span>
						</button>

						<!-- Parse Shortcode button -->
						<button
							type="button"
							class="button anwp-ml-auto anwp-d-inline-flex anwp-items-center"
							sl-x-on:click="showParseModal = true"
						>
							<span class="dashicons dashicons-upload anwp-dashicons-16"></span>
							<span class="anwp-ml-1"><?php echo esc_html__( 'Parse Shortcode', 'sports-leagues' ); ?></span>
						</button>
					</div>
				</div>

				<!-- Form Container (REST API loaded) -->
				<div
					id="anwp-shortcode-builder__content"
					class="anwp-py-3"
					sl-x-ref="formWrap"
					sl-x-html="formHtml"
					sl-x-on:input.debounce.150ms="buildShortcode()"
					sl-x-on:change="buildShortcode()"
					sl-x-on:update-x-sl-outer-wrapper.window="buildShortcode()"
				></div>
			</div>

			<!-- Preview Column -->
			<div class="sl-shortcode-builder__preview" sl-x-show="selectedShortcode" sl-x-cloak sl-x-bind:style="'width:' + previewWidth + 'px'">
				<div class="sl-preview-panel anwp-border anwp-border-gray-500 anwp-bg-white">
					<!-- Header -->
					<div class="anwp-border-bottom anwp-border-gray-500 anwp-bg-white anwp-d-flex anwp-items-center anwp-px-3 anwp-py-2 anwp-text-gray-700">
						<span class="dashicons dashicons-visibility anwp-dashicons-16 anwp-mr-2"></span>
						<span><?php echo esc_html__( 'Preview', 'sports-leagues' ); ?></span>

						<!-- Width Toggle -->
						<div class="sl-preview-width-toggle anwp-ml-3" sl-x-show="previewSupported">
							<button
								type="button"
								class="button button-small"
								sl-x-bind:class="{ 'button-primary': previewWidth === 400 }"
								sl-x-on:click="setPreviewWidth(400)"
							>400</button>
							<button
								type="button"
								class="button button-small"
								sl-x-bind:class="{ 'button-primary': previewWidth === 700 }"
								sl-x-on:click="setPreviewWidth(700)"
							>700</button>
						</div>

						<button
							type="button"
							class="button button-small anwp-ml-auto"
							sl-x-on:click="refreshPreview()"
							sl-x-bind:disabled="previewLoading"
							sl-x-show="previewSupported"
						>
							<span class="dashicons dashicons-update" sl-x-bind:class="{ 'anwp-spin': previewLoading }"></span>
							<span class="anwp-ml-1"><?php echo esc_html__( 'Refresh', 'sports-leagues' ); ?></span>
						</button>
					</div>

					<!-- Preview Accuracy Notice -->
					<div sl-x-show="previewSupported" class="anwp-px-3 anwp-py-2 anwp-bg-blue-50 anwp-border-bottom anwp-border-gray-300 anwp-text-xs anwp-text-gray-600">
						<span class="dashicons dashicons-info-outline anwp-dashicons-14 anwp-mr-1" style="vertical-align: middle;"></span>
						<?php echo esc_html__( 'Preview may differ from actual output. Some responsive styles and theme styles are not applied.', 'sports-leagues' ); ?>
					</div>

					<!-- Preview Not Supported Message -->
					<div sl-x-show="!previewSupported" class="anwp-p-4 anwp-text-center anwp-text-gray-500">
						<span class="dashicons dashicons-info-outline anwp-text-gray-400" style="font-size: 32px; width: 32px; height: 32px;"></span>
						<p class="anwp-m-0 anwp-mt-2"><?php echo esc_html__( 'Preview is not available for this shortcode.', 'sports-leagues' ); ?></p>
						<p class="anwp-m-0 anwp-mt-1 anwp-text-sm"><?php echo esc_html__( 'Copy the shortcode and paste it into a post or page to see the output.', 'sports-leagues' ); ?></p>
					</div>

					<!-- Loading State (only when preview supported) -->
					<div sl-x-show="previewSupported && previewLoading && !previewUrl" class="anwp-p-4 anwp-text-center anwp-text-gray-500">
						<span class="spinner is-active" style="float: none;"></span>
					</div>

					<!-- Error State -->
					<div sl-x-show="previewSupported && previewError" class="anwp-p-3 anwp-bg-red-50 anwp-text-red-700 anwp-text-sm" sl-x-text="previewError"></div>

					<!-- Iframe Preview -->
					<div sl-x-show="previewSupported && previewUrl" class="sl-preview-iframe-wrap" style="position: relative;">
						<div sl-x-show="previewLoading" class="sl-preview-loading-overlay">
							<span class="spinner is-active" style="float: none;"></span>
						</div>
						<iframe
							sl-x-ref="previewFrame"
							sl-x-bind:src="previewUrl"
							sl-x-on:load="onPreviewLoad()"
							sl-x-on:error="onPreviewError()"
							style="width: 100%; min-height: 300px; border: none; display: block;"
							sandbox="allow-same-origin allow-scripts"
						></iframe>
					</div>

					<!-- Empty State (only when preview supported) -->
					<div sl-x-show="previewSupported && !previewUrl && !previewLoading && !previewError" class="anwp-p-3 anwp-text-gray-500 anwp-text-sm">
						<p class="anwp-m-0"><?php echo esc_html__( 'Fill in the form fields to see a live preview.', 'sports-leagues' ); ?></p>
					</div>
				</div>
			</div>
		</div>

		<!-- Parse Shortcode Modal -->
		<template sl-x-teleport="body">
			<div
				sl-x-show="showParseModal"
				sl-x-cloak
				class="sl-import-modal-overlay"
				sl-x-on:click.self="showParseModal = false"
				sl-x-on:keydown.escape.window="showParseModal = false"
			>
				<div class="sl-import-modal" sl-x-on:click.stop>
					<div class="sl-import-modal__header">
						<h3 class="anwp-m-0"><?php echo esc_html__( 'Parse Shortcode', 'sports-leagues' ); ?></h3>
						<button type="button" class="sl-import-modal__close" sl-x-on:click="showParseModal = false">
							<span class="dashicons dashicons-no-alt"></span>
						</button>
					</div>
					<div class="sl-import-modal__body">
						<p class="description anwp-m-0 anwp-mb-2"><?php echo esc_html__( 'Paste an existing shortcode to load its attribute values into the form.', 'sports-leagues' ); ?></p>
						<textarea
							sl-x-model="parseText"
							placeholder='[sl-games tournament_id="5" limit="10"]'
							class="large-text code"
							rows="3"
							sl-x-on:keydown.ctrl.enter="parseShortcodeText(parseText)"
							sl-x-on:keydown.meta.enter="parseShortcodeText(parseText)"
						></textarea>
						<p sl-x-show="parseError" sl-x-cloak class="sl-import-error anwp-m-0 anwp-mt-2" sl-x-text="parseError"></p>
						<p sl-x-show="parseWarning" sl-x-cloak class="sl-import-warning anwp-m-0 anwp-mt-2" sl-x-text="parseWarning"></p>
					</div>
					<div class="sl-import-modal__footer">
						<button type="button" class="button" sl-x-on:click="showParseModal = false; parseWarning = ''; parsedAttrs = null;">
							<?php echo esc_html__( 'Cancel', 'sports-leagues' ); ?>
						</button>

						<!-- Parse button (hidden when warning shown) -->
						<button
							sl-x-show="!parseWarning"
							type="button"
							class="button button-primary"
							sl-x-on:click="parseShortcodeText(parseText)"
							sl-x-bind:disabled="!parseText.trim()"
						>
							<?php echo esc_html__( 'Parse Shortcode', 'sports-leagues' ); ?>
						</button>

						<!-- Continue Anyway button (shown when warning) -->
						<button
							sl-x-show="parseWarning"
							sl-x-cloak
							type="button"
							class="button button-primary"
							sl-x-on:click="confirmParse()"
						>
							<?php echo esc_html__( 'Continue Anyway', 'sports-leagues' ); ?>
						</button>
					</div>
				</div>
			</div>
		</template>
	</div>
</div>
