<script lang="ts">
	import { Card, Badge, Spinner, Modal } from '$lib/components';
	import { getSkills } from '$lib/api/admin';
	import { BookOpen, Search } from 'lucide-svelte';
	import { onMount } from 'svelte';

	type Skill = {
		dir: string;
		name: string;
		description: string;
		allowedTools: string;
		source: 'base' | 'platform' | 'admin';
		body: string;
	};

	let skills = $state<SkillEntry[]>([]);
	let loading = $state(true);
	let error = $state<string | null>(null);
	let search = $state('');
	let filterSource = $state<string>('all');
	let selectedSkill = $state<SkillEntry | null>(null);

	async function load() {
		try {
			skills = await getSkills() as SkillEntry[];
		} catch (e: any) {
			error = e.message || 'Failed to load skills';
		} finally {
			loading = false;
		}
	}

	onMount(load);

	const sources = ['all', 'base', 'platform', 'admin'];

	let filtered = $derived.by(() => {
		let list = skills;
		if (filterSource !== 'all') list = list.filter(s => s.source === filterSource);
		if (search.trim()) {
			const q = search.toLowerCase();
			list = list.filter(s =>
				s.dir.toLowerCase().includes(q) ||
				s.name.toLowerCase().includes(q) ||
				s.description.toLowerCase().includes(q)
			);
		}
		return list;
	});

	function sourceBadgeColor(source: string): 'accent' | 'amber' | 'rose' | 'dim' {
		if (source === 'admin') return 'rose';
		if (source === 'platform') return 'amber';
		if (source === 'base') return 'accent';
		return 'dim';
	}

	const counts = $derived({
		all: skills.length,
		base: skills.filter(s => s.source === 'base').length,
		platform: skills.filter(s => s.source === 'platform').length,
		admin: skills.filter(s => s.source === 'admin').length,
	});
</script>

<div class="page">
	{#if loading}
		<div class="center"><Spinner /></div>
	{:else if error}
		<p class="error">{error}</p>
	{:else}
		<div class="toolbar">
			<div class="search-wrap">
				<Search size={14} class="search-icon" />
				<input
					class="search"
					type="text"
					placeholder="Search skills..."
					bind:value={search}
				/>
			</div>
			<div class="filter-tabs">
				{#each sources as src}
					<button
						class="filter-tab"
						class:active={filterSource === src}
						onclick={() => filterSource = src}
					>
						{src === 'all' ? 'All' : src}
						<span class="tab-count">{counts[src as keyof typeof counts]}</span>
					</button>
				{/each}
			</div>
		</div>

		{#if filtered.length === 0}
			<div class="empty">
				<BookOpen size={32} strokeWidth={1.5} />
				<p>No skills found</p>
			</div>
		{:else}
			<div class="grid">
				{#each filtered as skill (skill.source + ':' + skill.dir)}
					<!-- svelte-ignore a11y_click_events_have_key_events -->
					<!-- svelte-ignore a11y_no_static_element_interactions -->
					<div class="skill-card" onclick={() => selectedSkill = skill}>
						<div class="skill-header">
							<span class="skill-dir mono">{skill.dir}</span>
							<Badge color={sourceBadgeColor(skill.source)}>{skill.source}</Badge>
						</div>
						{#if skill.name && skill.name !== skill.dir}
							<div class="skill-name">{skill.name}</div>
						{/if}
						{#if skill.description}
							<p class="skill-desc">{skill.description}</p>
						{:else}
							<p class="skill-desc muted">No description</p>
						{/if}
						{#if skill.allowedTools}
							<div class="skill-tools">
								{#each skill.allowedTools.split(',').map(t => t.trim()).filter(Boolean) as tool}
									<span class="tool-tag">{tool}</span>
								{/each}
							</div>
						{/if}
					</div>
				{/each}
			</div>
		{/if}
	{/if}
</div>

<!-- Skill Detail Modal -->
<Modal open={selectedSkill !== null} title={selectedSkill?.name || selectedSkill?.dir || 'Skill'} width="760px" onclose={() => selectedSkill = null}>
	{#if selectedSkill}
		<div class="detail">
			<div class="detail-meta">
				<div class="meta-row">
					<span class="meta-label">ID</span>
					<span class="mono">{selectedSkill.dir}</span>
				</div>
				<div class="meta-row">
					<span class="meta-label">Source</span>
					<Badge color={sourceBadgeColor(selectedSkill.source)}>{selectedSkill.source}</Badge>
				</div>
				{#if selectedSkill.description}
					<div class="meta-row">
						<span class="meta-label">Description</span>
						<span class="desc-text">{selectedSkill.description}</span>
					</div>
				{/if}
				{#if selectedSkill.allowedTools}
					<div class="meta-row">
						<span class="meta-label">Allowed Tools</span>
						<div class="skill-tools">
							{#each selectedSkill.allowedTools.split(',').map(t => t.trim()).filter(Boolean) as tool}
								<span class="tool-tag">{tool}</span>
							{/each}
						</div>
					</div>
				{/if}
			</div>
			{#if selectedSkill.body?.trim()}
				<div class="body-section">
					<div class="body-label">SKILL.md body</div>
					<pre class="body-pre">{selectedSkill.body.trim()}</pre>
				</div>
			{:else}
				<p class="muted" style="padding: 12px 0">No body content.</p>
			{/if}
		</div>
	{/if}
</Modal>

<style>
	.page {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}
	.center {
		display: flex;
		justify-content: center;
		padding: 60px 0;
	}
	.error {
		color: var(--rose);
		padding: 16px;
	}
	.toolbar {
		display: flex;
		align-items: center;
		gap: 12px;
		flex-wrap: wrap;
	}
	.search-wrap {
		position: relative;
		flex: 1;
		min-width: 200px;
	}
	.search-wrap :global(.search-icon) {
		position: absolute;
		left: 10px;
		top: 50%;
		transform: translateY(-50%);
		color: var(--text-muted);
		pointer-events: none;
	}
	.search {
		width: 100%;
		padding: 7px 10px 7px 32px;
		background: var(--surface-1);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text);
		font-size: var(--font-size-sm);
		box-sizing: border-box;
	}
	.search:focus {
		outline: none;
		border-color: var(--border-focus);
	}
	.filter-tabs {
		display: flex;
		gap: 4px;
	}
	.filter-tab {
		display: flex;
		align-items: center;
		gap: 5px;
		padding: 6px 12px;
		background: var(--surface-1);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text-dim);
		font-size: var(--font-size-xs);
		font-weight: 500;
		cursor: pointer;
		transition: all var(--duration) var(--ease);
		text-transform: capitalize;
	}
	.filter-tab:hover {
		background: var(--surface-2);
		color: var(--text);
	}
	.filter-tab.active {
		background: var(--accent-dim);
		border-color: var(--accent);
		color: var(--accent);
	}
	.tab-count {
		font-family: var(--font-mono);
		font-size: 10px;
		background: var(--surface-2);
		padding: 1px 5px;
		border-radius: 99px;
		color: var(--text-muted);
	}
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 12px;
		padding: 60px 0;
		color: var(--text-muted);
	}
	.grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
		gap: 12px;
	}
	.skill-card {
		background: var(--surface-0);
		border: 1px solid var(--border-subtle);
		border-radius: var(--radius-lg);
		padding: 14px 16px;
		cursor: pointer;
		transition: all var(--duration) var(--ease);
		display: flex;
		flex-direction: column;
		gap: 6px;
	}
	.skill-card:hover {
		border-color: var(--border-strong);
		background: var(--surface-1);
	}
	.skill-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 8px;
	}
	.skill-dir {
		font-size: var(--font-size-sm);
		font-weight: 600;
		color: var(--text-bright);
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.skill-name {
		font-size: var(--font-size-xs);
		color: var(--text-dim);
		font-weight: 500;
	}
	.skill-desc {
		font-size: var(--font-size-sm);
		color: var(--text);
		line-height: 1.4;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}
	.skill-desc.muted {
		color: var(--text-muted);
		font-style: italic;
	}
	.skill-tools {
		display: flex;
		flex-wrap: wrap;
		gap: 4px;
		margin-top: 2px;
	}
	.tool-tag {
		font-size: 10px;
		padding: 1px 6px;
		background: var(--surface-2);
		color: var(--text-dim);
		border-radius: 99px;
		font-family: var(--font-mono);
	}
	.detail {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}
	.detail-meta {
		display: flex;
		flex-direction: column;
		gap: 8px;
		background: var(--surface-0);
		border: 1px solid var(--border-subtle);
		border-radius: var(--radius);
		padding: 12px 14px;
	}
	.meta-row {
		display: flex;
		align-items: flex-start;
		gap: 12px;
	}
	.meta-label {
		font-size: var(--font-size-xs);
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--text-muted);
		min-width: 90px;
		padding-top: 2px;
	}
	.desc-text {
		font-size: var(--font-size-sm);
		color: var(--text);
		line-height: 1.4;
		flex: 1;
	}
	.body-section {
		display: flex;
		flex-direction: column;
		gap: 6px;
	}
	.body-label {
		font-size: var(--font-size-xs);
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--text-muted);
	}
	.body-pre {
		background: var(--surface-0);
		border: 1px solid var(--border-subtle);
		border-radius: var(--radius);
		padding: 14px;
		font-family: var(--font-mono);
		font-size: var(--font-size-xs);
		color: var(--text-dim);
		white-space: pre-wrap;
		word-break: break-word;
		line-height: 1.6;
		max-height: 480px;
		overflow-y: auto;
	}
	.mono {
		font-family: var(--font-mono);
	}
	.muted {
		color: var(--text-muted);
	}
	@media (max-width: 768px) {
		.toolbar { flex-direction: column; align-items: stretch; }
		.filter-tabs { overflow-x: auto; }
		.grid { grid-template-columns: 1fr; }
	}
</style>
