<?php echo message_box('success'); ?>
<?php echo message_box('error'); ?>

<?php
$modules = !empty($modules) && is_array($modules) ? $modules : array();
$module_summary = !empty($module_summary) && is_array($module_summary) ? $module_summary : array(
	'total' => 0,
	'active' => 0,
	'inactive' => 0,
	'upgrade_required' => 0,
);
?>

<div class="space-y-6" data-module-dashboard>
	<div class="rounded-3xl border border-border bg-card shadow-sm">
		<div class="border-b border-border bg-gradient-to-r from-slate-50 via-background to-slate-50 px-6 py-6 dark:from-slate-950 dark:via-slate-900/70 dark:to-slate-950">
			<div class="flex flex-col gap-6 xl:flex-row xl:items-start xl:justify-between">
				<div class="min-w-0 flex-1">
					<div class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground shadow-sm">
						<i data-lucide="blocks" class="h-3.5 w-3.5"></i>
						<?= lang('my_modules') ?>
					</div>
					<div class="mt-4 max-w-3xl">
						<h1 class="text-3xl font-semibold tracking-tight text-foreground md:text-4xl"><?= lang('modules') ?></h1>
						<p class="mt-3 text-sm leading-6 text-muted-foreground">
							Manage installed packages, review version readiness, and keep your module workspace tidy from one focused screen.
						</p>
					</div>
					<div class="mt-5 flex flex-wrap gap-3">
						<div class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-4 py-2 text-sm text-muted-foreground shadow-sm">
							<span class="font-semibold text-foreground"><?= (int) $module_summary['total'] ?></span>
							<span>Total modules</span>
						</div>
						<div class="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm text-emerald-700 shadow-sm dark:border-emerald-900/40 dark:bg-emerald-950/30 dark:text-emerald-300">
							<span class="font-semibold"><?= (int) $module_summary['active'] ?></span>
							<span>Active</span>
						</div>
						<div class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-4 py-2 text-sm text-muted-foreground shadow-sm">
							<span class="font-semibold text-foreground"><?= (int) $module_summary['inactive'] ?></span>
							<span>Inactive</span>
						</div>
						<div class="inline-flex items-center gap-2 rounded-full border border-amber-200 bg-amber-50 px-4 py-2 text-sm text-amber-700 shadow-sm dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-300">
							<span class="font-semibold"><?= (int) $module_summary['upgrade_required'] ?></span>
							<span>Need upgrade</span>
						</div>
					</div>
				</div>

				<div class="w-full xl:max-w-md">
					<div class="rounded-2xl border border-border bg-background p-5 shadow-sm">
						<div class="flex items-start justify-between gap-3">
							<div>
								<p class="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">Install new package</p>
								<h2 class="mt-1 text-base font-semibold text-foreground">Upload Module</h2>
								<p class="mt-2 text-sm leading-6 text-muted-foreground">Add a new ZIP package and complete the verification step from this panel.</p>
							</div>
							<div class="flex flex-col items-end gap-2">
								<a href="<?= base_url('admin/my_module/available_modules') ?>" class="inline-flex items-center gap-2 rounded-xl border border-border bg-background px-3 py-2 text-xs font-semibold text-foreground transition hover:bg-muted">
									<i data-lucide="store" class="h-4 w-4"></i>
									Catalog
								</a>
								<button type="button" data-upload-toggle aria-expanded="false" class="inline-flex items-center gap-2 rounded-xl border border-border bg-background px-3 py-2 text-xs font-semibold text-foreground transition hover:bg-muted">
									<i data-lucide="chevron-down" class="h-4 w-4 transition-transform duration-200" data-upload-toggle-icon></i>
									<span data-upload-toggle-label>Show form</span>
								</button>
							</div>
						</div>
						<div class="hidden mt-5 space-y-4" data-upload-panel>
							<form method="post" enctype="multipart/form-data" action="<?= base_url('admin/my_module/upload') ?>" class="space-y-4">
								<div class="grid gap-4">
									<?= form_input_group('envato_username', 'Envato Username', '', 'text', true, array('placeholder' => 'Enter buyer username')) ?>
									<?= form_input_group('purchase_key', 'Purchase Code', '', 'text', true, array('placeholder' => 'Enter valid purchase code')) ?>
								</div>
								<div class="rounded-2xl border border-dashed border-border bg-muted/20 p-4">
									<label class="mb-2 block text-sm font-medium text-foreground">Module Zip</label>
									<input type="file" name="module" accept=".zip" class="block w-full rounded-xl border border-border bg-background px-3 py-3 text-sm text-foreground file:mr-4 file:rounded-lg file:border-0 file:bg-slate-900 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-white hover:file:bg-slate-800 dark:file:bg-slate-100 dark:file:text-slate-900 dark:hover:file:bg-white">
									<p class="mt-2 text-xs text-muted-foreground">Upload the module zip, then validation and extraction will run automatically.</p>
								</div>
								<button type="submit" class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-slate-900 px-4 py-3 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white">
									<i data-lucide="package-plus" class="h-4 w-4"></i>
									Install Module
								</button>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="rounded-3xl border border-border bg-card shadow-sm">
		<div class="flex flex-col gap-4 border-b border-border px-6 py-4 lg:flex-row lg:items-center lg:justify-between">
			<div class="max-w-2xl">
				<h2 class="text-lg font-semibold text-foreground">Installed Modules</h2>
				<p class="mt-1 text-sm text-muted-foreground">Review what is installed, search quickly, and activate or deactivate modules without extra clutter.</p>
			</div>
			<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
				<div class="inline-flex items-center rounded-2xl border border-border bg-background p-1 shadow-sm">
					<button type="button" data-module-filter="all" class="module-filter-btn rounded-xl px-3 py-2 text-xs font-semibold text-foreground transition hover:bg-muted">All</button>
					<button type="button" data-module-filter="active" class="module-filter-btn rounded-xl px-3 py-2 text-xs font-semibold text-muted-foreground transition hover:bg-muted">Active</button>
					<button type="button" data-module-filter="inactive" class="module-filter-btn rounded-xl px-3 py-2 text-xs font-semibold text-muted-foreground transition hover:bg-muted">Inactive</button>
					<button type="button" data-module-filter="upgrade" class="module-filter-btn rounded-xl px-3 py-2 text-xs font-semibold text-muted-foreground transition hover:bg-muted">Needs Upgrade</button>
				</div>
				<div class="relative">
					<i data-lucide="search" class="pointer-events-none absolute left-3 top-3.5 h-4 w-4 text-muted-foreground"></i>
					<input type="search" placeholder="<?= lang('search_modules') ?>" data-module-search class="w-full rounded-xl border border-border bg-background py-2.5 pl-10 pr-4 text-sm text-foreground outline-none transition focus:border-slate-300 focus:ring-2 focus:ring-slate-500/10 sm:w-72">
				</div>
			</div>
		</div>

		<div class="p-6">
			<?php if (empty($modules)) : ?>
				<div class="flex min-h-[220px] flex-col items-center justify-center rounded-3xl border border-dashed border-border bg-background px-6 py-10 text-center">
					<div class="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
						<i data-lucide="package-search" class="h-7 w-7"></i>
					</div>
					<h3 class="mt-4 text-lg font-semibold text-foreground">No modules found</h3>
					<p class="mt-2 max-w-md text-sm text-muted-foreground">Installed modules will appear here automatically once they are available in your `modules/` directory.</p>
				</div>
			<?php else : ?>
				<div class="grid gap-4 xl:grid-cols-2 2xl:grid-cols-3" data-module-grid>
					<?php foreach ($modules as $module) : ?>
						<?php
						$headers = $module['headers'];
						$version = !empty($headers['version']) ? $headers['version'] : '0.0.0';
						$installedVersion = !empty($module['installed_version']) ? $module['installed_version'] : 'Pending install';
						$statusClass = !empty($module['activated'])
							? 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/40 dark:bg-emerald-950/30 dark:text-emerald-300'
							: 'border-slate-200 bg-slate-100 text-slate-700 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-300';
						?>
						<div class="rounded-2xl border border-border bg-background p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md" data-module-card data-module-state="<?= !empty($module['activated']) ? 'active' : 'inactive' ?>" data-module-upgrade="<?= !empty($module['database_upgrade_required']) ? '1' : '0' ?>" data-module-name="<?= html_escape(strtolower($module['display_name'] . ' ' . $module['system_name'])) ?>">
							<div class="flex h-full flex-col gap-4">
								<div class="flex items-start justify-between gap-4">
									<div class="min-w-0">
										<div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-slate-900 text-white shadow-sm dark:bg-slate-100 dark:text-slate-900">
											<i data-lucide="package" class="h-5 w-5"></i>
										</div>
										<div class="mt-3 flex flex-wrap items-center gap-2">
											<h3 class="text-base font-semibold text-foreground"><?= html_escape($module['display_name']) ?></h3>
											<span class="inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] <?= $statusClass ?>">
												<?= !empty($module['activated']) ? 'Active' : 'Inactive' ?>
											</span>
											<?php if (!empty($module['database_upgrade_required'])) : ?>
												<span class="inline-flex items-center rounded-full border border-amber-200 bg-amber-50 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-300">
													DB Upgrade
												</span>
											<?php endif; ?>
										</div>
									</div>
									<div class="rounded-2xl border border-border bg-card px-3 py-2 text-right">
										<p class="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">Version</p>
										<p class="mt-1 text-sm font-semibold text-foreground"><?= html_escape($version) ?></p>
									</div>
								</div>

								<p class="text-sm leading-6 text-muted-foreground"><?= html_escape($module['description_text']) ?></p>

								<div class="grid gap-3 sm:grid-cols-3">
									<div class="rounded-2xl border border-border bg-card px-4 py-3">
										<p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">Installed</p>
										<p class="mt-2 text-sm font-semibold text-foreground"><?= html_escape($installedVersion) ?></p>
									</div>
									<div class="rounded-2xl border border-border bg-card px-4 py-3">
										<p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">Publisher</p>
										<p class="mt-2 text-sm font-semibold text-foreground"><?= html_escape(!empty($headers['author']) ? $headers['author'] : 'Unknown author') ?></p>
									</div>
									<div class="rounded-2xl border border-border bg-card px-4 py-3">
										<p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">Requires</p>
										<p class="mt-2 text-sm font-semibold <?= !empty($module['minimum_version_met']) ? 'text-foreground' : 'text-rose-600 dark:text-rose-300' ?>">
											<?= html_escape(!empty($headers['requires_at_least']) ? $headers['requires_at_least'] : 'Core compatible') ?>
										</p>
									</div>
								</div>

								<div class="mt-auto flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4">
									<div class="flex flex-wrap gap-2">
										<?php if (empty($module['activated'])) : ?>
											<a href="<?= base_url('admin/my_module/activate/' . $module['system_name']) ?>" class="inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-3.5 py-2 text-xs font-semibold text-white transition hover:bg-emerald-500 <?= empty($module['minimum_version_met']) ? 'pointer-events-none opacity-50' : '' ?>">
												<i data-lucide="power" class="h-4 w-4"></i>
												Activate
											</a>
										<?php else : ?>
											<a href="<?= base_url('admin/my_module/deactivate/' . $module['system_name']) ?>" class="inline-flex items-center gap-2 rounded-xl border border-border bg-background px-3.5 py-2 text-xs font-semibold text-foreground transition hover:bg-muted">
												<i data-lucide="power-off" class="h-4 w-4"></i>
												Deactivate
											</a>
										<?php endif; ?>

										<?php if (!empty($module['database_upgrade_required'])) : ?>
											<form method="post" action="<?= base_url('admin/my_module/upgrade_database/' . $module['system_name']) ?>">
												<input type="hidden" name="latest_version" value="<?= html_escape($version) ?>">
												<button type="submit" class="inline-flex items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3.5 py-2 text-xs font-semibold text-amber-700 transition hover:bg-amber-100 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-300">
													<i data-lucide="database-zap" class="h-4 w-4"></i>
													Upgrade DB
												</button>
											</form>
										<?php endif; ?>

										<?php if (empty($module['activated'])) : ?>
											<a href="<?= base_url('admin/my_module/uninstall/' . $module['system_name']) ?>" onclick="return confirm(<?= json_encode(lang('uninstall_module_confirm')) ?>);" class="inline-flex items-center gap-2 rounded-xl border border-rose-200 bg-rose-50 px-3.5 py-2 text-xs font-semibold text-rose-700 transition hover:bg-rose-100 dark:border-rose-900/40 dark:bg-rose-950/30 dark:text-rose-300">
												<i data-lucide="trash-2" class="h-4 w-4"></i>
												Remove
											</a>
										<?php endif; ?>
									</div>
									<?php if (!empty($headers['uri'])) : ?>
										<a href="<?= html_escape($headers['uri']) ?>" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-2 rounded-xl border border-border bg-background px-3.5 py-2 text-xs font-semibold text-foreground transition hover:bg-muted">
											Documentation
											<i data-lucide="arrow-up-right" class="h-4 w-4"></i>
										</a>
									<?php endif; ?>
								</div>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</div>
	</div>
</div>

<script>
(() => {
	const searchInput = document.querySelector('[data-module-search]');
	const cards = Array.from(document.querySelectorAll('[data-module-card]'));
	const filterButtons = Array.from(document.querySelectorAll('[data-module-filter]'));
	const uploadToggle = document.querySelector('[data-upload-toggle]');
	const uploadPanel = document.querySelector('[data-upload-panel]');
	const uploadToggleLabel = document.querySelector('[data-upload-toggle-label]');
	const uploadToggleIcon = document.querySelector('[data-upload-toggle-icon]');
	let activeFilter = 'all';
	if (uploadToggle && uploadPanel) {
		uploadToggle.addEventListener('click', () => {
			const isHidden = uploadPanel.classList.contains('hidden');
			uploadPanel.classList.toggle('hidden');
			uploadToggle.setAttribute('aria-expanded', isHidden ? 'true' : 'false');
			if (uploadToggleLabel) {
				uploadToggleLabel.textContent = isHidden ? 'Hide form' : 'Show form';
			}
			if (uploadToggleIcon) {
				uploadToggleIcon.classList.toggle('rotate-180', isHidden);
			}
		});
	}

	if (!searchInput || !cards.length) {
		return;
	}

	const applyFilters = () => {
		const keyword = searchInput.value.trim().toLowerCase();
		cards.forEach((card) => {
			const haystack = card.getAttribute('data-module-name') || '';
			const state = card.getAttribute('data-module-state') || 'inactive';
			const needsUpgrade = card.getAttribute('data-module-upgrade') === '1';
			const matchesSearch = keyword === '' || haystack.includes(keyword);
			const matchesFilter =
				activeFilter === 'all' ||
				(activeFilter === 'active' && state === 'active') ||
				(activeFilter === 'inactive' && state === 'inactive') ||
				(activeFilter === 'upgrade' && needsUpgrade);
			card.classList.toggle('hidden', !(matchesSearch && matchesFilter));
		});
	};

	searchInput.addEventListener('input', applyFilters);
	filterButtons.forEach((button) => {
		button.addEventListener('click', () => {
			activeFilter = button.getAttribute('data-module-filter') || 'all';
			filterButtons.forEach((item) => {
				const selected = item === button;
				item.classList.toggle('bg-slate-900', selected);
				item.classList.toggle('text-white', selected);
				item.classList.toggle('shadow-sm', selected);
				item.classList.toggle('text-foreground', !selected);
				item.classList.toggle('text-muted-foreground', !selected);
			});
			applyFilters();
		});
	});
	if (filterButtons.length) {
		filterButtons[0].click();
	} else {
		applyFilters();
	}
})();
</script>
