<?php
/**
 * Templates page — split-panel UI with live iframe preview.
 *
 * @package PrivexPasswordProtect
 */

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

$ppmstr_s          = PPMSTR_Settings::get_all();
$ppmstr_saved      = isset( $_GET['ppmstr_saved'] ) && '1' === $_GET['ppmstr_saved']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$ppmstr_active_tpl = isset( $ppmstr_s['active_template'] ) ? $ppmstr_s['active_template'] : 'preset_elegant';

$ppmstr_presets = PPMSTR_Template_Builder::get_presets();
$ppmstr_custom  = PPMSTR_Template_Builder::get_all();

// Build unified list: presets first, then custom.
$ppmstr_all_tpls = array();
foreach ( $ppmstr_presets as $ppmstr_pid => $ppmstr_ptpl ) {
	$ppmstr_accent = '#6C5CE7';
	foreach ( $ppmstr_ptpl['blocks'] ?? array() as $ppmstr_bl ) {
		if ( 'submit_button' === $ppmstr_bl['type'] ) {
			$ppmstr_accent = $ppmstr_bl['settings']['bgcolor'] ?? '#6C5CE7';
			break;
		}
	}
	$ppmstr_pg = $ppmstr_ptpl['global'] ?? array();
	$ppmstr_all_tpls[ $ppmstr_pid ] = array(
		'name'      => $ppmstr_ptpl['name'],
		'is_preset' => true,
		'is_active' => ( $ppmstr_pid === $ppmstr_active_tpl ),
		'bg'        => $ppmstr_pg['bgColor'] ?? '#F0F2F8',
		'bg2'       => ! empty( $ppmstr_pg['bgGradient'] ) ? ( $ppmstr_pg['bgGradTo'] ?? '' ) : '',
		'card_bg'   => $ppmstr_pg['cardBg'] ?? '#FFFFFF',
		'accent'    => $ppmstr_accent,
		'preview_url' => add_query_arg( 'ppmstr_preview', $ppmstr_pid, home_url( '/' ) ),
		'edit_url'    => admin_url( 'admin.php?page=ppmstr-template-builder&preset=' . $ppmstr_pid ),
	);
}
foreach ( $ppmstr_custom as $ppmstr_cid => $ppmstr_ctpl ) {
	$ppmstr_caccent = '#6C5CE7';
	foreach ( $ppmstr_ctpl['blocks'] ?? array() as $ppmstr_cbl ) {
		if ( 'submit_button' === $ppmstr_cbl['type'] ) {
			$ppmstr_caccent = $ppmstr_cbl['settings']['bgcolor'] ?? '#6C5CE7';
			break;
		}
	}
	$ppmstr_cg = $ppmstr_ctpl['global'] ?? array();
	$ppmstr_all_tpls[ $ppmstr_cid ] = array(
		'name'      => $ppmstr_ctpl['name'],
		'is_preset' => false,
		'is_active' => ( $ppmstr_cid === $ppmstr_active_tpl ),
		'bg'        => $ppmstr_cg['bgColor'] ?? '#F0F2F8',
		'bg2'       => ! empty( $ppmstr_cg['bgGradient'] ) ? ( $ppmstr_cg['bgGradTo'] ?? '' ) : '',
		'card_bg'   => $ppmstr_cg['cardBg'] ?? '#FFFFFF',
		'accent'    => $ppmstr_caccent,
		'preview_url' => add_query_arg( 'ppmstr_preview', $ppmstr_cid, home_url( '/' ) ),
		'edit_url'    => admin_url( 'admin.php?page=ppmstr-template-builder&template_id=' . $ppmstr_cid ),
	);
}

// Which template is initially selected for preview?
// Default to the active template so coming back from the builder shows the right one.
if ( isset( $ppmstr_all_tpls[ $ppmstr_active_tpl ] ) ) {
	$ppmstr_init_id = $ppmstr_active_tpl;
} else {
	$ppmstr_init_id = array_key_first( $ppmstr_all_tpls ) ?? '';
}
$ppmstr_init_tpl = $ppmstr_init_id ? $ppmstr_all_tpls[ $ppmstr_init_id ] : null;
?>

<style>
.ppmstr-tpl-studio{display:grid;grid-template-columns:280px 1fr;gap:0;height:calc(100vh - 180px);min-height:540px;border-radius:16px;overflow:hidden;box-shadow:0 4px 32px rgba(0,0,0,.1);border:1px solid #E4E6EF;}
.ppmstr-tpl-sidebar{background:#fff;border-right:1px solid #E4E6EF;display:flex;flex-direction:column;overflow:hidden;}
.ppmstr-tpl-sidebar-head{padding:18px 20px 14px;border-bottom:1px solid #F0F2F8;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-shrink:0;}
.ppmstr-tpl-sidebar-head h3{margin:0;font-size:13px;font-weight:700;color:#1A1A2E;text-transform:uppercase;letter-spacing:.6px;}
.ppmstr-tpl-list{overflow-y:auto;flex:1;padding:8px;}
.ppmstr-tpl-list::-webkit-scrollbar{width:4px;}
.ppmstr-tpl-list::-webkit-scrollbar-track{background:transparent;}
.ppmstr-tpl-list::-webkit-scrollbar-thumb{background:#E4E6EF;border-radius:4px;}
.ppmstr-tpl-section-label{font-size:10px;font-weight:700;color:#A0A3B1;text-transform:uppercase;letter-spacing:.8px;padding:10px 10px 4px;margin:0;}
.ppmstr-tpl-row{display:flex;align-items:center;gap:10px;padding:9px 10px;border-radius:10px;cursor:pointer;border:1.5px solid transparent;transition:background .15s,border-color .15s;position:relative;margin-bottom:2px;}
.ppmstr-tpl-row:hover{background:#F7F8FD;}
.ppmstr-tpl-row.is-selected{background:#F0EDFF;border-color:#6C5CE7;}
.ppmstr-tpl-row.is-active-tpl{border-left:3px solid #00B894;padding-left:7px;}
.ppmstr-tpl-row.is-active-tpl .ppmstr-tpl-row-name::after{content:"Active";font-size:9px;font-weight:700;color:#fff;background:#00B894;border-radius:6px;padding:1px 7px;margin-left:7px;vertical-align:middle;letter-spacing:.3px;}
.ppmstr-tpl-swatch{width:32px;height:32px;border-radius:8px;flex-shrink:0;box-shadow:inset 0 0 0 1px rgba(0,0,0,.08);}
.ppmstr-tpl-row-name{font-size:13px;font-weight:500;color:#2D2D4D;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.ppmstr-tpl-row-badge{font-size:10px;font-weight:700;color:#6C5CE7;background:#F0EDFF;border-radius:6px;padding:2px 6px;letter-spacing:.2px;flex-shrink:0;}
.ppmstr-tpl-sidebar-foot{padding:14px 16px;border-top:1px solid #F0F2F8;flex-shrink:0;}
.ppmstr-tpl-sidebar-foot a{display:flex;align-items:center;justify-content:center;gap:7px;width:100%;padding:9px;background:#6C5CE7;color:#fff;border-radius:10px;font-size:13px;font-weight:600;text-decoration:none;transition:background .15s;}
.ppmstr-tpl-sidebar-foot a:hover{background:#5A4BD1;color:#fff;}

.ppmstr-tpl-stage{background:#F0F2F8;display:flex;flex-direction:column;overflow:hidden;}
.ppmstr-tpl-stage-bar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 18px;background:#fff;border-bottom:1px solid #E4E6EF;flex-shrink:0;}
.ppmstr-tpl-stage-title{font-size:14px;font-weight:700;color:#1A1A2E;}
.ppmstr-tpl-stage-actions{display:flex;align-items:center;gap:8px;}
.ppmstr-tpl-stage-actions .ppmstr-btn{font-size:12px;padding:6px 14px;border-radius:8px;}
.ppmstr-tpl-iframe-wrap{flex:1;overflow:hidden;position:relative;}
.ppmstr-tpl-iframe-wrap iframe{width:100%;height:100%;border:none;display:block;}
.ppmstr-tpl-iframe-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#F0F2F8;z-index:2;transition:opacity .3s;}
.ppmstr-tpl-iframe-loading.hidden{opacity:0;pointer-events:none;}
.ppmstr-tpl-iframe-spinner{width:32px;height:32px;border:3px solid #E4E6EF;border-top-color:#6C5CE7;border-radius:50%;animation:ppmstr-spin .7s linear infinite;}
@keyframes ppmstr-spin{to{transform:rotate(360deg)}}
.ppmstr-tpl-empty-state{flex:1;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:10px;color:#A0A3B1;font-size:14px;}
</style>

<div class="ppmstr-page-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:20px;">
	<div>
		<h2><?php esc_html_e( 'Templates', 'privex-password-protect' ); ?></h2>
		<p class="ppmstr-page-desc"><?php esc_html_e( 'Choose a ready-made template or create your own.', 'privex-password-protect' ); ?></p>
	</div>
</div>

<?php if ( $ppmstr_saved ) : ?>
	<div class="ppmstr-notice ppmstr-notice--success" style="margin-bottom:16px;">
		<?php esc_html_e( 'Template settings saved!', 'privex-password-protect' ); ?>
	</div>
<?php endif; ?>

<div id="ppmstr-tpl-notice" class="ppmstr-notice ppmstr-notice--success" style="display:none;margin-bottom:16px;"></div>

<div class="ppmstr-tpl-studio">

	<!-- LEFT: Template list -->
	<div class="ppmstr-tpl-sidebar">
		<div class="ppmstr-tpl-sidebar-head">
			<h3><?php esc_html_e( 'Templates', 'privex-password-protect' ); ?></h3>
			<span style="font-size:11px;color:#A0A3B1;font-weight:500;"><?php echo count( $ppmstr_all_tpls ); ?> total</span>
		</div>

		<div class="ppmstr-tpl-list" id="ppmstr-tpl-list">

			<!-- Presets -->
			<p class="ppmstr-tpl-section-label"><?php esc_html_e( 'Ready-Made', 'privex-password-protect' ); ?></p>
			<?php foreach ( $ppmstr_presets as $ppmstr_pid => $ppmstr_ptpl ) :
				$ppmstr_info = $ppmstr_all_tpls[ $ppmstr_pid ] ?? null;
				if ( ! $ppmstr_info ) continue;
				$ppmstr_is_anim = ! empty( $ppmstr_ptpl['global']['animation'] ) && 'none' !== $ppmstr_ptpl['global']['animation'];
				$ppmstr_swatch_bg = $ppmstr_info['bg2']
					? 'linear-gradient(135deg,' . esc_attr( $ppmstr_info['bg'] ) . ' 40%,' . esc_attr( $ppmstr_info['bg2'] ) . ')'
					: esc_attr( $ppmstr_info['bg'] );
			?>
				<div class="ppmstr-tpl-row <?php echo $ppmstr_info['is_active'] ? 'is-active-tpl' : ''; ?>"
					data-id="<?php echo esc_attr( $ppmstr_pid ); ?>"
					data-preview="<?php echo esc_url( $ppmstr_info['preview_url'] ); ?>"
					data-name="<?php echo esc_attr( $ppmstr_info['name'] ); ?>"
					data-edit="<?php echo esc_url( $ppmstr_info['edit_url'] ); ?>"
					data-active="<?php echo $ppmstr_info['is_active'] ? '1' : '0'; ?>"
					data-custom="0">
					<div class="ppmstr-tpl-swatch" style="background:<?php echo $ppmstr_swatch_bg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;"></div>
					<span class="ppmstr-tpl-row-name"><?php echo esc_html( $ppmstr_ptpl['name'] ); ?></span>
					<?php if ( ! empty( $ppmstr_ptpl['pro'] ) ) : ?>
						<span class="ppmstr-pro-badge" style="margin-left:auto; margin-right:4px;">PRO</span>
					<?php endif; ?>
				</div>
			<?php endforeach; ?>

			<!-- Custom -->
			<?php if ( ! empty( $ppmstr_custom ) ) : ?>
				<p class="ppmstr-tpl-section-label" style="margin-top:8px;"><?php esc_html_e( 'My Custom', 'privex-password-protect' ); ?></p>
				<?php foreach ( $ppmstr_custom as $ppmstr_cid => $ppmstr_ctpl ) :
					$ppmstr_cinfo = $ppmstr_all_tpls[ $ppmstr_cid ] ?? null;
					if ( ! $ppmstr_cinfo ) continue;
					$ppmstr_cswatch = $ppmstr_cinfo['bg2']
						? 'linear-gradient(135deg,' . esc_attr( $ppmstr_cinfo['bg'] ) . ' 40%,' . esc_attr( $ppmstr_cinfo['bg2'] ) . ')'
						: esc_attr( $ppmstr_cinfo['bg'] );
				?>
					<div class="ppmstr-tpl-row <?php echo $ppmstr_cinfo['is_active'] ? 'is-active-tpl' : ''; ?>"
						data-id="<?php echo esc_attr( $ppmstr_cid ); ?>"
						data-preview="<?php echo esc_url( $ppmstr_cinfo['preview_url'] ); ?>"
						data-name="<?php echo esc_attr( $ppmstr_cinfo['name'] ); ?>"
						data-edit="<?php echo esc_url( $ppmstr_cinfo['edit_url'] ); ?>"
						data-active="<?php echo $ppmstr_cinfo['is_active'] ? '1' : '0'; ?>"
						data-custom="1">
						<div class="ppmstr-tpl-swatch" style="background:<?php echo $ppmstr_cswatch; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;"></div>
						<span class="ppmstr-tpl-row-name"><?php echo esc_html( $ppmstr_ctpl['name'] ); ?></span>
					</div>
				<?php endforeach; ?>
			<?php endif; ?>

		</div>

		<div class="ppmstr-tpl-sidebar-foot">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=ppmstr-template-builder' ) ); ?>">
				<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
				<?php esc_html_e( 'Create New Template', 'privex-password-protect' ); ?> <span class="ppmstr-pro-badge" style="background:#fff; color:#6C5CE7; box-shadow:none;">PRO</span>
			</a>
		</div>
	</div>

	<!-- RIGHT: Stage / preview -->
	<div class="ppmstr-tpl-stage">
		<div class="ppmstr-tpl-stage-bar">
			<span class="ppmstr-tpl-stage-title" id="ppmstr-stage-name">
				<?php echo $ppmstr_init_tpl ? esc_html( $ppmstr_init_tpl['name'] ) : esc_html__( 'Select a template', 'privex-password-protect' ); ?>
			</span>
			<div class="ppmstr-tpl-stage-actions" id="ppmstr-stage-actions" style="<?php echo ! $ppmstr_init_tpl ? 'display:none' : ''; ?>">
				<a href="<?php echo $ppmstr_init_tpl ? esc_url( $ppmstr_init_tpl['preview_url'] ) : '#'; ?>" target="_blank" rel="noopener" id="ppmstr-stage-open-btn" class="ppmstr-btn ppmstr-btn--secondary">
					<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="margin-right:4px;vertical-align:-1px;"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
					<?php esc_html_e( 'Open Full', 'privex-password-protect' ); ?>
				</a>
				<a href="<?php echo $ppmstr_init_tpl ? esc_url( $ppmstr_init_tpl['edit_url'] ) : '#'; ?>" id="ppmstr-stage-edit-btn" class="ppmstr-btn ppmstr-btn--secondary">
					<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="margin-right:4px;vertical-align:-1px;"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
					<?php esc_html_e( 'Edit', 'privex-password-protect' ); ?>
				</a>
				<button type="button" id="ppmstr-stage-activate-btn" class="ppmstr-btn ppmstr-btn--primary ppmstr-activate-tpl"
					data-id="<?php echo esc_attr( $ppmstr_init_id ); ?>"
					style="<?php echo ( $ppmstr_init_tpl && $ppmstr_init_tpl['is_active'] ) ? 'display:none' : ''; ?>">
					<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="margin-right:4px;vertical-align:-1px;"><polyline points="20 6 9 17 4 12"/></svg>
					<?php esc_html_e( 'Activate', 'privex-password-protect' ); ?>
				</button>
				<span id="ppmstr-stage-active-badge"
					style="font-size:12px;font-weight:700;color:#2E7D32;background:#E8F5E9;border-radius:8px;padding:6px 12px;<?php echo ( $ppmstr_init_tpl && $ppmstr_init_tpl['is_active'] ) ? '' : 'display:none'; ?>">
					✓ <?php esc_html_e( 'Active', 'privex-password-protect' ); ?>
				</span>
				<button type="button" id="ppmstr-stage-delete-btn" class="ppmstr-btn ppmstr-btn--xs"
					style="background:rgba(225,112,85,0.1);color:#E17055;border:none;display:none;">
					<?php esc_html_e( 'Delete', 'privex-password-protect' ); ?>
				</button>
			</div>
		</div>

		<div class="ppmstr-tpl-iframe-wrap">
			<div class="ppmstr-tpl-iframe-loading" id="ppmstr-iframe-loading">
				<div class="ppmstr-tpl-iframe-spinner"></div>
			</div>
			<?php if ( $ppmstr_init_tpl ) : ?>
				<iframe id="ppmstr-preview-iframe"
					src="<?php echo esc_url( $ppmstr_init_tpl['preview_url'] ); ?>"
					title="<?php esc_attr_e( 'Template Preview', 'privex-password-protect' ); ?>">
				</iframe>
			<?php else : ?>
				<div class="ppmstr-tpl-empty-state">
					<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#D0D2DF" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M3 9h18M9 21V9"/></svg>
					<span><?php esc_html_e( 'Select a template to preview', 'privex-password-protect' ); ?></span>
				</div>
			<?php endif; ?>
		</div>
	</div>

</div>

<script>
(function(){
	var rows     = document.querySelectorAll('.ppmstr-tpl-row');
	var iframe   = document.getElementById('ppmstr-preview-iframe');
	var loading  = document.getElementById('ppmstr-iframe-loading');
	var stageName    = document.getElementById('ppmstr-stage-name');
	var stageActions = document.getElementById('ppmstr-stage-actions');
	var openBtn      = document.getElementById('ppmstr-stage-open-btn');
	var editBtn      = document.getElementById('ppmstr-stage-edit-btn');
	var activateBtn  = document.getElementById('ppmstr-stage-activate-btn');
	var activeBadge  = document.getElementById('ppmstr-stage-active-badge');
	var deleteBtn    = document.getElementById('ppmstr-stage-delete-btn');
	var notice       = document.getElementById('ppmstr-tpl-notice');
	var currentId    = '';

	// Select the active template by default (fallback: first row).
	var initRow = document.querySelector('.ppmstr-tpl-row[data-active="1"]') || rows[0];
	if ( initRow ) select( initRow );

	rows.forEach(function(row){
		row.addEventListener('click', function(){ select(row); });
	});

	function select(row) {
		rows.forEach(function(r){ r.classList.remove('is-selected'); });
		row.classList.add('is-selected');

		var id         = row.dataset.id;
		var previewUrl = row.dataset.preview;
		var name       = row.dataset.name;
		var editUrl    = row.dataset.edit;
		var isActive   = row.dataset.active === '1';
		var isCustom   = row.dataset.custom === '1';
		currentId = id;

		stageName.textContent = name;
		stageActions.style.display = '';
		openBtn.href = previewUrl;
		editBtn.href = editUrl;
		activateBtn.dataset.id = id;

		if ( isActive ) {
			activateBtn.style.display = 'none';
			activeBadge.style.display = '';
		} else {
			activateBtn.style.display = '';
			activeBadge.style.display = 'none';
		}

		deleteBtn.style.display = isCustom ? '' : 'none';
		deleteBtn.dataset.id = id;

		if ( iframe ) {
			loading.classList.remove('hidden');
			iframe.src = previewUrl;
		}
	}

	// Hide loading spinner when iframe loads.
	if ( iframe ) {
		iframe.addEventListener('load', function(){
			loading.classList.add('hidden');
		});
	}

	// Activate via AJAX (same as existing system).
	document.addEventListener('click', function(e){
		if ( e.target.closest('.ppmstr-activate-tpl') ) {
			var btn = e.target.closest('.ppmstr-activate-tpl');
			var tid = btn.dataset.id;
			btn.disabled = true;
			btn.textContent = '...';
			jQuery.post(ppmstrAdmin.ajaxUrl, {
				action:'ppmstr_activate_template',
				nonce: ppmstrAdmin.nonce,
				template_id: tid
			}, function(res){
				if ( res.success ) {
					// Update active state across all rows.
					document.querySelectorAll('.ppmstr-tpl-row').forEach(function(r){
						var isNowActive = ( r.dataset.id === tid );
						r.dataset.active = isNowActive ? '1' : '0';
						r.classList.toggle('is-active-tpl', isNowActive );
					});
					activateBtn.style.display = 'none';
					activeBadge.style.display = '';
					btn.disabled = false;
					showNotice( '✓ Template activated and live on your site!', 'success' );
				} else {
					btn.disabled = false;
					showNotice( res.data || 'Error', 'error' );
				}
			});
		}
	});

	// Delete custom template.
	if ( deleteBtn ) {
		deleteBtn.addEventListener('click', function(){
			var tid = deleteBtn.dataset.id;
			if ( !confirm('Delete this template?') ) return;
			jQuery.post(ppmstrAdmin.ajaxUrl, {
				action:'ppmstr_delete_template',
				nonce: ppmstrAdmin.nonce,
				template_id: tid
			}, function(res){
				console.log("Delete response:", res);
				if ( res.success ) {
					var row = document.querySelector('.ppmstr-tpl-row[data-id="' + tid + '"]');
					if ( row ) {
						row.remove();
						var remaining = document.querySelector('.ppmstr-tpl-row');
						if ( remaining ) select(remaining);
					}
					showNotice('Template deleted.', 'success');
				} else {
					alert(res.data || 'Failed to delete template');
				}
			}).fail(function(xhr) {
				console.log("Delete failed:", xhr);
				alert('AJAX error during deletion.');
			});
		});
	}

	function showNotice(msg, type) {
		notice.textContent = msg;
		notice.style.display = '';
		notice.className = 'ppmstr-notice ppmstr-notice--' + ( type || 'success' );
		setTimeout(function(){ notice.style.display = 'none'; }, 3500);
	}
})();
</script>
