<?php
/**
 * Admin templates page view.
 *
 * @package    100Prints
 */

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

$conn_service = new Hundred_Prints_Connection_Service();
$template_service = new Hundred_Prints_Template_Service();

$is_connected = $conn_service->is_connected();
$bundled_templates = $template_service->get_bundled_templates();
$cloud_templates = $template_service->get_cloud_templates();
$workspace_info = $conn_service->get_workspace_info();
$last_sync = get_option( '100p_last_sync_time' );
$sync_time_str = $last_sync ? human_time_diff( $last_sync, current_time( 'timestamp' ) ) . ' ago' : 'Never';

// Determine connection / state flow
if ( ! $is_connected ) {
	$page_state = 'NOT_CONNECTED';
} elseif ( empty( $cloud_templates ) ) {
	$page_state = 'CONNECTED_EMPTY';
} else {
	$page_state = 'CONNECTED_READY';
}

// Extract categories for filter
$categories = [];
if ( ! empty( $cloud_templates ) ) {
	foreach ( $cloud_templates as $t ) {
		if ( ! empty( $t['category'] ) ) {
			$categories[] = $t['category'];
		}
	}
}
$categories = array_unique( $categories );
?>

<div class="wrap hundredp-wrap" style="position: relative;">
	
	<?php
	$args = [
		'title'   => 'Template Library',
		'actions' => $section_actions ?? [], // Added fallback in case actions array is missing
	];
	require HUNDRED_PRINTS_PATH . 'admin/partials/header.php';
	?>

	<?php
	// 1. CAPTURE BUNDLED TEMPLATES HTML 
	// We save this into a variable so we can print it ABOVE or BELOW depending on the state
	ob_start();
	?>
	<div class="hundredp-section-header">
		<h2>Default Templates <span class="hundredp-badge hundredp-badge-neutral"><?php echo count( $bundled_templates ); ?></span></h2>
		<p>These templates are shipped inside the plugin and work instantly without a connection.</p>
	</div>
	
	<section class="hundredp-template-grid">
		<?php foreach ( $bundled_templates as $template ) : ?>
			<div class="hundredp-template-card">
				<div class="hundredp-template-thumbnail">
					<?php if ( ! empty( $template['thumbnail'] ) ) : ?>
						<img src="<?php echo esc_url( $template['thumbnail'] ); ?>" alt="Template Preview" />
					<?php else : ?>
						<i class="ph-bold ph-image" style="font-size: 40px; color: #CBD5E1;"></i>
					<?php endif; ?>
				</div>
				<div class="hundredp-template-content">
					<h4><?php echo esc_html( $template['name'] ); ?></h4>
					<div class="hundredp-template-badges">
						<span class="hundredp-badge hundredp-badge-bundled">Bundled</span>
						<span class="hundredp-badge hundredp-badge-output">PDF / PNG</span>
					</div>
					<div class="hundredp-template-vars">
						<?php 
						if ( ! empty( $template['category'] ) ) {
							echo '<span class="hundredp-var-chip">' . esc_html( $template['category'] ) . '</span>';
						}
						?>
					</div>
					<div class="hundredp-template-actions">
						<button type="button" class="hundredp-btn hundredp-btn-ghost hundredp-btn-preview" style="flex:1;" data-id="<?php echo esc_attr( $template['id'] ); ?>" data-name="<?php echo esc_attr( $template['name'] ); ?>" data-source="bundled">
							<i class="ph-bold ph-eye"></i> Preview
						</button>
						<a href="<?php echo esc_url( admin_url( 'post-new.php' ) ); ?>" class="hundredp-btn hundredp-btn-primary" style="flex:1;" title="Use in Gutenberg">
							<i class="ph-bold ph-plus"></i> Use
						</a>
					</div>
				</div>
			</div>
		<?php endforeach; ?>
	</section>
	<?php 
	$bundled_templates_html = ob_get_clean(); 
	?>


	<?php
	// 2. DISPLAY LOGIC BASED ON CONNECTION STATE
	if ( $page_state === 'NOT_CONNECTED' ) : 
	?>
		<?php echo $bundled_templates_html; ?>
		
		<hr class="hundredp-divider" />
		
		<div class="hundredp-section-header">
			<h2>Cloud Templates</h2>
		</div>
		
		<div class="hundredp-premium-empty-state">
			<div class="hundredp-empty-state-content">
				<div class="hundredp-empty-state-icon">
					<i class="ph-bold ph-cloud"></i>
				</div>
				<h2>Cloud Templates</h2>
				<p>Connect your 100Prints account to unlock your cloud template library.</p>
				<ul class="hundredp-feature-list">
					<li><i class="ph-bold ph-check"></i> Unlimited templates</li>
					<li><i class="ph-bold ph-check"></i> Team workspace</li>
					<li><i class="ph-bold ph-check"></i> Browser SDK</li>
					<li><i class="ph-bold ph-check"></i> Automatic synchronization</li>
					<li><i class="ph-bold ph-check"></i> Premium template library</li>
					<li><i class="ph-bold ph-check"></i> Future template updates</li>
				</ul>
				<button type="button" class="hundredp-btn hundredp-btn-primary" id="hundredp-btn-open-connect-modal">
					Connect Account
				</button>
			</div>
		</div>

	<?php 
	else : 
		// B) CONNECTED STATES: Cloud Templates first, then Bundled
		if ( $page_state === 'CONNECTED_EMPTY' ) : 
	?>
			<div class="hundredp-workspace-header-card">
				<div class="hundredp-workspace-info-row">
					<div class="hundredp-workspace-title">
						<h2>Cloud Templates</h2>
					</div>
					<div class="hundredp-workspace-actions">
						<button type="button" class="hundredp-btn hundredp-btn-ghost hundredp-btn-sync">
							<i class="ph-bold ph-arrows-clockwise"></i> Sync Now
						</button>
					</div>
				</div>
				<div class="hundredp-workspace-stats">
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Workspace</span>
						<span class="hundredp-header-stat-value"><?php echo esc_html( $workspace_info['workspace_name'] ?? 'My Workspace' ); ?></span>
					</div>
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Plan</span>
						<span class="hundredp-header-stat-value hundredp-capitalize"><?php echo esc_html( $workspace_info['plan_tier'] ?? 'Free' ); ?></span>
					</div>
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Templates</span>
						<span class="hundredp-header-stat-value">0</span>
					</div>
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Last Sync</span>
						<span class="hundredp-header-stat-value"><?php echo esc_html( $sync_time_str ); ?></span>
					</div>
				</div>
			</div>

			<div class="hundredp-premium-empty-state">
				<div class="hundredp-empty-state-content">
					<div class="hundredp-empty-state-icon" style="background: var(--hundredp-muted);">
						<i class="ph-bold ph-cloud-slash"></i>
					</div>
					<h2>No Cloud Templates Yet</h2>
					<p>Templates are created inside 100PrintsWithMe. Create your first template in the dashboard, then press Sync.</p>
					<div style="display: flex; gap: 12px; justify-content: center; margin-top: 16px;">
						<a href="https://100printswith.me/dashboard" target="_blank" class="hundredp-btn hundredp-btn-primary">
							Open Dashboard <i class="ph-bold ph-arrow-square-out" style="margin-left: 4px;"></i>
						</a>
					</div>
				</div>
			</div>

		<?php elseif ( $page_state === 'CONNECTED_READY' ) : ?>
			
			<div class="hundredp-workspace-header-card">
				<div class="hundredp-workspace-info-row">
					<div class="hundredp-workspace-title">
						<h2>Cloud Templates <span class="hundredp-badge hundredp-badge-cloud"><?php echo count( $cloud_templates ); ?></span></h2>
					</div>
					<div class="hundredp-workspace-actions">
						<input type="text" class="hundredp-search-input" placeholder="Search templates..." id="hundredp-template-search" />
						<select id="hundredp-category-filter" class="hundredp-filter-select">
							<option value="">All Categories</option>
							<?php foreach ( $categories as $cat ) : ?>
								<option value="<?php echo esc_attr( $cat ); ?>"><?php echo esc_html( ucfirst( $cat ) ); ?></option>
							<?php endforeach; ?>
						</select>
						<button type="button" class="hundredp-btn hundredp-btn-ghost hundredp-btn-sync">
							<i class="ph-bold ph-arrows-clockwise"></i> Sync Now
						</button>
					</div>
				</div>
				<div class="hundredp-workspace-stats">
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Workspace</span>
						<span class="hundredp-header-stat-value"><?php echo esc_html( $workspace_info['workspace_name'] ?? 'My Workspace' ); ?></span>
					</div>
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Plan</span>
						<span class="hundredp-header-stat-value hundredp-capitalize"><?php echo esc_html( $workspace_info['plan_tier'] ?? 'Free' ); ?></span>
					</div>
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Templates</span>
						<span class="hundredp-header-stat-value"><?php echo count( $cloud_templates ); ?></span>
					</div>
					<div class="hundredp-header-stat-item">
						<span class="hundredp-header-stat-label">Last Sync</span>
						<span class="hundredp-header-stat-value"><?php echo esc_html( $sync_time_str ); ?></span>
					</div>
				</div>
			</div>

			<section class="hundredp-template-grid" id="hundredp-cloud-grid">
				<?php foreach ( $cloud_templates as $template ) : ?>
					<div class="hundredp-template-card" data-id="<?php echo esc_attr( $template['id'] ); ?>">
						<div class="hundredp-template-thumbnail" data-id="<?php echo esc_attr( $template['id'] ); ?>">
							<div class="ph-bold ph-spinner spinner" style="font-size: 24px; color: #94A3B8; animation: hundredp-spin 1s linear infinite;"></div>
						</div>
						<div class="hundredp-template-content">
							<h4><?php echo esc_html( $template['name'] ); ?></h4>
							
							<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 12px;">
								<span class="hundredp-badge hundredp-badge-cloud" style="font-size: 9px; padding: 2px 6px;">Cloud</span>
								<span class="hundredp-badge hundredp-badge-success" style="font-size: 9px; padding: 2px 6px;">Synced</span>
							</div>
							
							<div class="hundredp-template-vars" style="margin-bottom: 16px;">
								<?php 
								$category_name = $template['category'] ?? 'Document';
								if ( $category_name === 'id-card' ) {
									$category_name = 'ID Badge';
								} else {
									$category_name = ucfirst( $category_name );
								}
								?>
								<span class="hundredp-var-chip" style="font-size: 11px; padding: 2px 6px; border-radius: 4px;">
									<?php echo esc_html( $category_name ); ?> Template
								</span>
							</div>
							
							<div class="hundredp-template-actions">
								<button type="button" class="hundredp-btn hundredp-btn-ghost hundredp-btn-preview" style="flex:1;" data-id="<?php echo esc_attr( $template['id'] ); ?>" data-name="<?php echo esc_attr( $template['name'] ); ?>" data-source="cloud">
									<i class="ph-bold ph-eye"></i> Preview
								</button>
								<a href="<?php echo esc_url( admin_url( 'post-new.php' ) ); ?>" class="hundredp-btn hundredp-btn-primary" style="flex:1;" title="Use in Gutenberg">
									<i class="ph-bold ph-plus"></i> Use
								</a>
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</section>
		<?php endif; ?>

		<hr class="hundredp-divider" />
		<?php echo $bundled_templates_html; ?>
		
	<?php endif; ?>


	<div class="hundredp-drawer">
		<div class="hundredp-drawer-header">
			<h3 class="hundredp-drawer-title">Template Preview</h3>
			<button class="hundredp-drawer-close" aria-label="Close">
				<i class="ph-bold ph-x"></i>
			</button>
		</div>
		<div class="hundredp-drawer-body">
			<div class="hundredp-drawer-preview" style="display:flex; justify-content:center; align-items:flex-start; overflow:auto; padding:24px;"></div>
			
			<div style="font-size: 13px; color: var(--hundredp-muted); line-height: 1.5;">
				<p>To use this template, open any page or post in the block editor, insert the <strong>100Prints Document</strong> block, and select this template.</p>
				<div id="hundredp-drawer-variables" style="margin-top: 16px;"></div>
			</div>
		</div>
	</div>

	<div class="hundredp-modal-overlay" id="hundredp-connect-modal">
		<div class="hundredp-modal">
			<div class="hundredp-modal-header">
				<h3>Connect 100Prints Account</h3>
				<button class="hundredp-modal-close" aria-label="Close">
					<i class="ph-bold ph-x"></i>
				</button>
			</div>
			<div class="hundredp-modal-body" id="hundredp-modal-step-connect">
				<form id="hundredp-modal-connect-form">
					<div class="hundredp-form-group">
						<label for="hundredp-modal-api-key">API Key</label>
						<input type="password" id="hundredp-modal-api-key" placeholder="pk_live_..." required />
						<p class="hundredp-form-desc">Paste your Developer API Key from your 100Prints Dashboard.</p>
					</div>
					<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 24px;">
						<a href="https://100printswith.me/dashboard" target="_blank" class="hundredp-btn hundredp-btn-ghost">
							Open Dashboard <i class="ph-bold ph-arrow-square-out" style="margin-left: 4px;"></i>
						</a>
						<button type="submit" class="hundredp-btn hundredp-btn-primary">Connect</button>
					</div>
				</form>
			</div>
			<div class="hundredp-modal-body" id="hundredp-modal-step-success" style="display: none; text-align: center;">
				<i class="ph-fill ph-check-circle" style="font-size: 48px; color: var(--hundredp-success); margin-bottom: 16px;"></i>
				<h3 style="margin: 0 0 8px 0; font-size: 18px;">Connected!</h3>
				<div class="hundredp-workspace-summary" style="margin: 20px 0; border: 1px solid var(--hundredp-border); padding: 16px; border-radius: var(--hundredp-radius); text-align: left;">
					<div class="hundredp-summary-item">
						<span class="hundredp-summary-label">Workspace</span>
						<span class="hundredp-summary-value" id="hundredp-modal-ws-name">-</span>
					</div>
					<div class="hundredp-summary-item">
						<span class="hundredp-summary-label">Plan</span>
						<span class="hundredp-summary-value hundredp-capitalize" id="hundredp-modal-ws-plan">-</span>
					</div>
					<div class="hundredp-summary-item">
						<span class="hundredp-summary-label">Templates</span>
						<span class="hundredp-summary-value" id="hundredp-modal-ws-count">-</span>
					</div>
				</div>
				<button type="button" class="hundredp-btn hundredp-btn-primary hundredp-btn-full" id="hundredp-modal-continue">
					Continue
				</button>
			</div>
		</div>
	</div>

</div>