<?php
/**
 * Nexora VE Networks - Countdown / Realm Status v2
 *
 * Este archivo define un renderer reutilizable por slots. Index.php lo carga
 * una sola vez y llama nexoraCountdownRender('hero'|'after-hero'|'floating').
 */

if (!defined('access') || !access) {
	die();
}

if (!function_exists('nexoraCountdownDefaults')) {
	function nexoraCountdownDefaults($realm) {
		$isSeasonal = ($realm === 'seasonal');
		return array(
			'active' => '1',
			'mode' => $isSeasonal ? 'countdown' : 'status',
			'timezone' => 'America/Caracas',
			'target_date' => '2026-08-17 18:00:00',
			'label' => $isSeasonal ? 'Apertura Temporada II' : 'Legado operativo',
			'message' => '',
			'display_days' => '1',
			'display_hours' => '1',
			'display_minutes' => '1',
			'display_seconds' => '1',
			'placement' => $isSeasonal ? 'hero-right' : 'hero-left',
			'offset_x' => '0',
			'offset_y' => '18',
			'size' => 'standard',
			'background_opacity' => '72',
			'blur' => '14',
			'glow' => 'medium',
			'status_type' => 'online',
			'cta_label' => '',
			'cta_url' => '',
			'after_action' => 'status',
			'after_status_type' => 'online',
			'after_label' => $isSeasonal ? 'Seasonal operativo' : 'Legado operativo',
			'after_message' => '',
			'after_cta_label' => '',
			'after_cta_url' => '',
		);
	}
}

if (!function_exists('nexoraCountdownGlobalConfig')) {
	function nexoraCountdownGlobalConfig() {
		$defaults = array('active' => '1', 'mobile_layout' => 'swipe');
		if (!function_exists('loadConfigurations')) return $defaults;
		$data = loadConfigurations('countdown');
		return is_array($data) ? array_merge($defaults, $data) : $defaults;
	}
}

if (!function_exists('nexoraCountdownRealmConfig')) {
	function nexoraCountdownRealmConfig($realm) {
		$defaults = nexoraCountdownDefaults($realm);
		if (!function_exists('loadConfigurations')) return $defaults;
		$data = loadConfigurations('countdown.' . $realm);
		return is_array($data) ? array_merge($defaults, $data) : $defaults;
	}
}

if (!function_exists('nexoraCountdownEscape')) {
	function nexoraCountdownEscape($value) {
		return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
	}
}

if (!function_exists('nexoraCountdownInt')) {
	function nexoraCountdownInt($value, $min, $max, $fallback) {
		if (!is_numeric($value)) return $fallback;
		$value = (int)$value;
		if ($value < $min) $value = $min;
		if ($value > $max) $value = $max;
		return $value;
	}
}

if (!function_exists('nexoraCountdownStatusLabel')) {
	function nexoraCountdownStatusLabel($status) {
		$labels = array(
			'online' => 'Servidor ON',
			'maintenance' => 'Mantenimiento',
			'offline' => 'Offline',
			'event' => 'Evento especial',
			'notice' => 'Aviso',
		);
		return isset($labels[$status]) ? $labels[$status] : $labels['notice'];
	}
}

if (!function_exists('nexoraCountdownSafeUrl')) {
	function nexoraCountdownSafeUrl($value) {
		$value = trim((string)$value);
		if ($value === '') return '';
		if (strpos($value, '/') === 0 && strpos($value, '//') !== 0) return $value;
		$parts = @parse_url($value);
		if (is_array($parts) && isset($parts['scheme']) && in_array(strtolower($parts['scheme']), array('http', 'https'), true)) {
			return $value;
		}
		if (preg_match('~^[a-zA-Z0-9][a-zA-Z0-9/_\-?.=&%#]*$~', $value)) {
			return rtrim(__BASE_URL__, '/') . '/' . ltrim($value, '/');
		}
		return '';
	}
}

if (!function_exists('nexoraCountdownTargetTimestamp')) {
	function nexoraCountdownTargetTimestamp($dateString, $timezone) {
		try {
			$tz = new DateTimeZone((string)$timezone);
			$date = DateTime::createFromFormat('Y-m-d H:i:s', (string)$dateString, $tz);
			if (!$date || $date->format('Y-m-d H:i:s') !== (string)$dateString) return false;
			return $date->getTimestamp();
		} catch (Exception $e) {
			return false;
		}
	}
}

if (!function_exists('nexoraCountdownSlotForPlacement')) {
	function nexoraCountdownSlotForPlacement($placement) {
		if (strpos((string)$placement, 'hero-') === 0) return 'hero';
		if ($placement === 'after-hero') return 'after-hero';
		if (strpos((string)$placement, 'floating-') === 0) return 'floating';
		return 'hero';
	}
}

if (!function_exists('nexoraCountdownRealmMeta')) {
	function nexoraCountdownRealmMeta($realm) {
		$defaults = array(
			'legacy' => array('label' => 'Legado', 'short_label' => 'Reino permanente'),
			'seasonal' => array('label' => 'Seasonal', 'short_label' => 'Reino por temporadas'),
		);
		if (class_exists('NexoraRealm')) {
			$list = NexoraRealm::publicList();
			if (isset($list[$realm])) {
				return array(
					'label' => isset($list[$realm]['label']) ? $list[$realm]['label'] : $defaults[$realm]['label'],
					'short_label' => isset($list[$realm]['short_label']) ? $list[$realm]['short_label'] : $defaults[$realm]['short_label'],
				);
			}
		}
		return isset($defaults[$realm]) ? $defaults[$realm] : array('label' => ucfirst($realm), 'short_label' => 'Reino');
	}
}

if (!function_exists('nexoraCountdownRenderStatusBody')) {
	function nexoraCountdownRenderStatusBody($status, $title, $message, $ctaLabel, $ctaUrl, $hidden, $postState) {
		$statusAllowed = array('online', 'maintenance', 'offline', 'event', 'notice');
		if (!in_array($status, $statusAllowed, true)) $status = 'notice';
		$url = nexoraCountdownSafeUrl($ctaUrl);
		$attrs = $hidden ? ' hidden aria-hidden="true"' : '';
		$postAttr = $postState ? ' data-nex-post-state="1"' : '';
		?>
		<div class="nex-realm-module__state nex-realm-module__state--<?php echo nexoraCountdownEscape($status); ?>"<?php echo $attrs . $postAttr; ?>>
			<div class="nex-realm-module__state-line">
				<span class="nex-realm-module__status-dot" aria-hidden="true"></span>
				<span class="nex-realm-module__status-label"><?php echo nexoraCountdownEscape(nexoraCountdownStatusLabel($status)); ?></span>
			</div>
			<?php if (trim((string)$title) !== '') { ?>
				<strong class="nex-realm-module__state-title"><?php echo nexoraCountdownEscape($title); ?></strong>
			<?php } ?>
			<?php if (trim((string)$message) !== '') { ?>
				<p class="nex-realm-module__message"><?php echo nexoraCountdownEscape($message); ?></p>
			<?php } ?>
			<?php if (trim((string)$ctaLabel) !== '' && $url !== '') { ?>
				<a class="nex-realm-module__cta" href="<?php echo nexoraCountdownEscape($url); ?>"><?php echo nexoraCountdownEscape($ctaLabel); ?></a>
			<?php } ?>
		</div>
		<?php
	}
}

if (!function_exists('nexoraCountdownRenderCard')) {
	function nexoraCountdownRenderCard($realm, $cfg) {
		$meta = nexoraCountdownRealmMeta($realm);
		$placementAllowed = array(
			'hero-left', 'hero-center', 'hero-right',
			'hero-bottom-left', 'hero-bottom-center', 'hero-bottom-right',
			'after-hero', 'floating-left', 'floating-right'
		);
		$sizeAllowed = array('compact', 'standard', 'wide');
		$glowAllowed = array('off', 'low', 'medium', 'high');
		$statusAllowed = array('online', 'maintenance', 'offline', 'event', 'notice');

		$placement = in_array($cfg['placement'], $placementAllowed, true) ? $cfg['placement'] : ($realm === 'seasonal' ? 'hero-right' : 'hero-left');
		$size = in_array($cfg['size'], $sizeAllowed, true) ? $cfg['size'] : 'standard';
		$glow = in_array($cfg['glow'], $glowAllowed, true) ? $cfg['glow'] : 'medium';
		$status = in_array($cfg['status_type'], $statusAllowed, true) ? $cfg['status_type'] : 'notice';
		$afterStatus = in_array($cfg['after_status_type'], $statusAllowed, true) ? $cfg['after_status_type'] : 'online';
		$mode = $cfg['mode'] === 'countdown' ? 'countdown' : 'status';
		$afterAction = $cfg['after_action'] === 'hide' ? 'hide' : 'status';

		$opacity = nexoraCountdownInt($cfg['background_opacity'], 20, 100, 72) / 100;
		$blur = nexoraCountdownInt($cfg['blur'], 0, 30, 14);
		$offsetX = nexoraCountdownInt($cfg['offset_x'], -300, 300, 0);
		$offsetY = nexoraCountdownInt($cfg['offset_y'], -300, 300, 18);
		$style = '--nex-module-alpha:' . number_format($opacity, 2, '.', '') . ';--nex-module-blur:' . $blur . 'px;--nex-module-x:' . $offsetX . 'px;--nex-module-y:' . $offsetY . 'px;';

		$targetTs = false;
		$timeLeft = 0;
		$finished = false;
		if ($mode === 'countdown') {
			$targetTs = nexoraCountdownTargetTimestamp($cfg['target_date'], $cfg['timezone']);
			if ($targetTs === false) $targetTs = time();
			$timeLeft = max(0, $targetTs - time());
			$finished = ($timeLeft <= 0);
			if ($finished && $afterAction === 'hide') return;
		}

		$showDays = ((string)$cfg['display_days'] === '1');
		$showHours = ((string)$cfg['display_hours'] === '1');
		$showMinutes = ((string)$cfg['display_minutes'] === '1');
		$showSeconds = ((string)$cfg['display_seconds'] === '1');
		if (!$showDays && !$showHours && !$showMinutes && !$showSeconds) $showSeconds = true;

		$days = floor($timeLeft / 86400);
		$hours = floor(($timeLeft % 86400) / 3600);
		$minutes = floor(($timeLeft % 3600) / 60);
		$seconds = $timeLeft % 60;
		?>
		<article class="nex-realm-module nex-realm-module--<?php echo nexoraCountdownEscape($realm); ?> nex-realm-module--<?php echo nexoraCountdownEscape($size); ?> nex-realm-module--glow-<?php echo nexoraCountdownEscape($glow); ?>"
			data-nex-realm-card="<?php echo nexoraCountdownEscape($realm); ?>"
			data-placement="<?php echo nexoraCountdownEscape($placement); ?>"
			style="<?php echo nexoraCountdownEscape($style); ?>">
			<div class="nex-realm-module__accent" aria-hidden="true"></div>
			<header class="nex-realm-module__head">
				<div>
					<span class="nex-realm-module__realm"><?php echo nexoraCountdownEscape($meta['label']); ?></span>
					<small><?php echo nexoraCountdownEscape($meta['short_label']); ?></small>
				</div>
				<span class="nex-realm-module__sigil" aria-hidden="true"></span>
			</header>

			<?php if ($mode === 'countdown' && !$finished) { ?>
				<div class="nex-realm-module__countdown"
					role="timer"
					aria-live="polite"
					data-nex-countdown="<?php echo nexoraCountdownEscape($realm); ?>"
					data-target="<?php echo (int)$targetTs; ?>"
					data-d="<?php echo $showDays ? '1' : '0'; ?>"
					data-h="<?php echo $showHours ? '1' : '0'; ?>"
					data-m="<?php echo $showMinutes ? '1' : '0'; ?>"
					data-s="<?php echo $showSeconds ? '1' : '0'; ?>"
					data-after-action="<?php echo nexoraCountdownEscape($afterAction); ?>">
					<strong class="nex-realm-module__title"><?php echo nexoraCountdownEscape($cfg['label']); ?></strong>
					<?php if (trim((string)$cfg['message']) !== '') { ?>
						<p class="nex-realm-module__message nex-realm-module__message--countdown"><?php echo nexoraCountdownEscape($cfg['message']); ?></p>
					<?php } ?>
					<div class="nex-realm-module__grid">
						<?php if ($showDays) { ?>
							<div class="nex-realm-module__cell"><span>Dias</span><strong data-unit="days"><?php echo (int)$days; ?></strong></div>
						<?php } ?>
						<?php if ($showHours) { ?>
							<div class="nex-realm-module__cell"><span>Horas</span><strong data-unit="hours"><?php echo str_pad((string)$hours, 2, '0', STR_PAD_LEFT); ?></strong></div>
						<?php } ?>
						<?php if ($showMinutes) { ?>
							<div class="nex-realm-module__cell"><span>Min</span><strong data-unit="minutes"><?php echo str_pad((string)$minutes, 2, '0', STR_PAD_LEFT); ?></strong></div>
						<?php } ?>
						<?php if ($showSeconds) { ?>
							<div class="nex-realm-module__cell"><span>Seg</span><strong data-unit="seconds"><?php echo str_pad((string)$seconds, 2, '0', STR_PAD_LEFT); ?></strong></div>
						<?php } ?>
					</div>
					<div class="nex-realm-module__foot">
						<span class="nex-realm-module__timezone">
							<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3.5 2"></path></svg>
							<?php echo nexoraCountdownEscape($cfg['timezone']); ?>
						</span>
						<?php $ctaUrl = nexoraCountdownSafeUrl($cfg['cta_url']); if (trim((string)$cfg['cta_label']) !== '' && $ctaUrl !== '') { ?>
							<a class="nex-realm-module__cta nex-realm-module__cta--small" href="<?php echo nexoraCountdownEscape($ctaUrl); ?>"><?php echo nexoraCountdownEscape($cfg['cta_label']); ?></a>
						<?php } ?>
					</div>
				</div>
				<?php nexoraCountdownRenderStatusBody($afterStatus, $cfg['after_label'], $cfg['after_message'], $cfg['after_cta_label'], $cfg['after_cta_url'], true, true); ?>
			<?php } elseif ($mode === 'countdown' && $finished) { ?>
				<?php nexoraCountdownRenderStatusBody($afterStatus, $cfg['after_label'], $cfg['after_message'], $cfg['after_cta_label'], $cfg['after_cta_url'], false, true); ?>
			<?php } else { ?>
				<?php nexoraCountdownRenderStatusBody($status, $cfg['label'], $cfg['message'], $cfg['cta_label'], $cfg['cta_url'], false, false); ?>
			<?php } ?>
		</article>
		<?php
	}
}

if (!function_exists('nexoraCountdownRender')) {
	function nexoraCountdownRender($slot) {
		$global = nexoraCountdownGlobalConfig();
		if ((string)$global['active'] !== '1') return;

		$slot = in_array($slot, array('hero', 'after-hero', 'floating'), true) ? $slot : 'hero';
		$mobileLayout = ((string)$global['mobile_layout'] === 'stack') ? 'stack' : 'swipe';
		$cards = array();
		foreach (array('legacy', 'seasonal') as $realm) {
			$cfg = nexoraCountdownRealmConfig($realm);
			if ((string)$cfg['active'] !== '1') continue;
			if (nexoraCountdownSlotForPlacement($cfg['placement']) !== $slot) continue;
			$cards[$realm] = $cfg;
		}
		if (!$cards) return;

		$slotClass = str_replace('_', '-', $slot);
		?>
		<section class="nex-realm-modules nex-realm-modules--<?php echo nexoraCountdownEscape($slotClass); ?> nex-realm-modules--mobile-<?php echo nexoraCountdownEscape($mobileLayout); ?>" data-nex-realm-modules="<?php echo nexoraCountdownEscape($slot); ?>" aria-label="Estado de los reinos Nexora">
			<div class="nex-container nex-realm-modules__stage">
				<?php foreach ($cards as $realm => $cfg) { nexoraCountdownRenderCard($realm, $cfg); } ?>
			</div>
		</section>
		<?php
	}
}
