<?php

	use const VVWebsite\ICONS_DIR;

	require_once VV::root("src/Consts.php");

	$HTMLCodeDemoElement = new class {
		public bool $valid = false;

		public readonly array $files;
		private readonly string $dir;
		private readonly string $namespace;

		public function __construct() {
			$this->namespace = array_key_exists("id", $_GET) ? $_GET["id"] : null;

			if ($this->namespace) {
				$this->dir = "snippets/HTMLCodeDemoElement/{$this->namespace}/";

				if (is_dir(VV::root($this->dir))) {
					// Strip "." and ".."
					$this->files = array_filter(scandir(VV::root($this->dir), SCANDIR_SORT_DESCENDING), function (string $item) {
						return substr($item, 0, 1) !== ".";
					});

					$this->valid = true;
				}
			}
		}

		public static function name(string $file): string {
			return substr($file, 0, strlen($file) - 4);
		}

		public static function language(string $file): string {
			return explode(".", $file, 3)[1];
		}

		public function file_path(string $file): string {
			return $this->dir . $file;
		}
	}

?>
<code-demo>
	<?php if ($HTMLCodeDemoElement->valid): ?>
		<div class="header">

			<?php foreach ($HTMLCodeDemoElement->files as $file): ?>
				<button class="inline" data-lang="<?= $HTMLCodeDemoElement::language($file) ?>" data-file="<?= $HTMLCodeDemoElement::name($file) ?>">
					<?= VV::embed(ICONS_DIR . "languages/{$HTMLCodeDemoElement::language($file)}.svg") ?>
					<p><?= substr($file, 0, strlen($file) - 4) ?></p>
				</button>
			<?php endforeach; ?>

		</div>
		<div class="body">
			
			<?php foreach ($HTMLCodeDemoElement->files as $file): ?>
				<div data-file="<?= $HTMLCodeDemoElement::name($file) ?>">
					<?= VV::include($HTMLCodeDemoElement->file_path($file)) ?>
				</div>
			<?php endforeach; ?>

		</div>
	<?php else: ?>
		<div class="header">
			<button>
				<p>Not Found</p>
			</button>
		</div>
		<div class="body"><p>404</p></div>
	<?php endif; ?>

</code-demo>
<script type="module" src="/assets/js/elements/HTMLCodeDemoElement.mjs"></script>