<script lang="ts">
	import { user, pageMeta } from '$lib/config';
	import { blogName, blogTagline } from '$lib/config/blog';
	import { formatPostDate } from '$lib/blog/date';
	import { themeColors } from '$lib/stores/theme';
	import TuiHeader from '$lib/components/tui/TuiHeader.svelte';
	import TuiFooter from '$lib/components/tui/TuiFooter.svelte';
	import '$lib/assets/css/terminal-tui.css';
	import '$lib/assets/css/tui-body.css';

	let { data } = $props();

	let activeTag = $state<string | null>(null);
	let searchQuery = $state('');
	let currentPage = $state(1);

	const POSTS_PER_PAGE = 5;

	const filteredPosts = $derived.by(() => {
		const query = searchQuery.trim().toLowerCase();
		return data.posts.filter((post) => {
			const matchesTag = !activeTag || post.tags.includes(activeTag);
			const matchesQuery =
				!query ||
				post.title.toLowerCase().includes(query) ||
				post.excerpt.toLowerCase().includes(query) ||
				post.tags.some((tag) => tag.toLowerCase().includes(query));
			return matchesTag && matchesQuery;
		});
	});

	const totalPages = $derived(Math.max(1, Math.ceil(filteredPosts.length / POSTS_PER_PAGE)));

	const paginatedPosts = $derived(
		filteredPosts.slice((currentPage - 1) * POSTS_PER_PAGE, currentPage * POSTS_PER_PAGE)
	);

	$effect(() => {
		activeTag;
		searchQuery;
		currentPage = 1;
	});

	function goToPage(page: number) {
		currentPage = Math.min(Math.max(1, page), totalPages);
	}

	const meta = pageMeta['/blog'];
</script>

<svelte:head>
	<title>{meta?.title ?? `${user.displayname} — Blog`}</title>
	<meta name="description" content={meta?.description ?? 'Blog posts'} />
</svelte:head>

<div class="blog-container">
	<div
		class="tui-terminal"
		style="
			--terminal-bg: {$themeColors.terminal};
			--terminal-text: {$themeColors.text};
			--terminal-muted: {$themeColors.textMuted};
			--terminal-border: {$themeColors.border};
			--terminal-prompt: {$themeColors.terminalPrompt};
			--terminal-user: {$themeColors.terminalUser};
			--terminal-path: {$themeColors.terminalPath};
			--terminal-primary: {$themeColors.primary};
			--terminal-secondary: {$themeColors.secondary};
			--terminal-accent: {$themeColors.accent};
			--terminal-bg-light: {$themeColors.backgroundLight};
		"
		role="region"
		aria-label="Blog"
	>
		<div class="tui-border-glow"></div>

		<div class="tui-content">
			<TuiHeader title="~/blog" interactive={false} hasButtons={false} />

			<div class="tui-body">
				<div class="blog-body">
					<div class="blog-hero">
						<h1 class="blog-name">{blogName}</h1>
						<p class="blog-tagline">{blogTagline}</p>
						<div class="blog-links">
							<a class="blog-link" href="/blog/rss.xml" target="_blank" rel="noopener noreferrer">RSS Feed</a>
						</div>
					</div>

					<input class="search-input" type="search" placeholder="Search posts..." bind:value={searchQuery} />

					{#if data.tags.length}
						<div class="tag-filter">
							<button class="tag-chip" class:active={activeTag === null} onclick={() => (activeTag = null)}>
								all
							</button>
							{#each data.tags as tag (tag)}
								<button
									class="tag-chip"
									class:active={activeTag === tag}
									onclick={() => (activeTag = activeTag === tag ? null : tag)}
								>
									{tag}
								</button>
							{/each}
						</div>
					{/if}

					{#if filteredPosts.length === 0}
						<p class="empty-state">
							{data.posts.length === 0 ? 'No posts yet. Check back soon.' : 'No posts match your search.'}
						</p>
					{:else}
						<div class="post-list">
							{#each paginatedPosts as post (post.slug)}
								<a class="post-card" href={`/blog/${post.slug}`}>
									<div class="post-meta">
										<span class="post-author">{post.author}</span>
										<span class="post-date">{formatPostDate(post.date)}</span>
										<span class="post-reading-time">{post.readingTime} min read</span>
									</div>
									<h2 class="post-title">{post.title}</h2>
									<p class="post-excerpt">{post.excerpt}</p>
									{#if post.tags.length}
										<div class="post-tags">
											{#each post.tags as tag (tag)}
												<span class="post-tag">{tag}</span>
											{/each}
										</div>
									{/if}
								</a>
							{/each}
						</div>

						{#if totalPages > 1}
							<div class="pagination">
								<button
									class="page-btn"
									disabled={currentPage === 1}
									onclick={() => goToPage(currentPage - 1)}
								>
									&larr; Prev
								</button>
								<span class="page-status">Page {currentPage} of {totalPages}</span>
								<button
									class="page-btn"
									disabled={currentPage === totalPages}
									onclick={() => goToPage(currentPage + 1)}
								>
									Next &rarr;
								</button>
							</div>
						{/if}
					{/if}
				</div>
			</div>

			<TuiFooter isTyping={false} linesCount={filteredPosts.length} skipAnimation={() => {}} />
		</div>
	</div>
</div>

<style>
	.blog-container {
		padding: 0;
		min-height: calc(100vh - var(--navbar-height, 60px));
	}

	.blog-body {
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
	}

	.blog-hero {
		padding-bottom: 1.25rem;
		border-bottom: 1px solid var(--terminal-border);
	}

	.blog-name {
		margin: 0;
		font-size: 1.75rem;
		color: var(--terminal-primary);
	}

	.blog-tagline {
		margin: 0.25rem 0 0.75rem 0;
		color: var(--terminal-muted);
		font-size: 0.95rem;
	}

	.blog-links {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		font-size: 0.85rem;
	}

	.blog-link {
		color: var(--terminal-accent);
	}

	.blog-link:hover {
		color: var(--terminal-primary);
	}

	.blog-link-separator {
		color: var(--terminal-muted);
	}

	.search-input {
		width: 100%;
		padding: 0.6rem 0.9rem;
		background: var(--terminal-bg-light);
		border: 1px solid var(--terminal-border);
		border-radius: 6px;
		color: var(--terminal-text);
		font-family: inherit;
		font-size: 0.9rem;
	}

	.search-input:focus {
		outline: none;
		border-color: var(--terminal-primary);
	}

	.search-input::placeholder {
		color: var(--terminal-muted);
	}

	.tag-filter {
		display: flex;
		flex-wrap: wrap;
		gap: 0.5rem;
	}

	.tag-chip {
		padding: 0.3rem 0.75rem;
		background: transparent;
		border: 1px solid var(--terminal-border);
		border-radius: 4px;
		color: var(--terminal-muted);
		font-family: inherit;
		font-size: 0.8rem;
		transition:
			border-color 0.15s ease,
			color 0.15s ease;
	}

	.tag-chip:hover {
		border-color: var(--terminal-primary);
		color: var(--terminal-text);
	}

	.tag-chip.active {
		border-color: var(--terminal-accent);
		color: var(--terminal-accent);
	}

	.empty-state {
		color: var(--terminal-muted);
	}

	.post-list {
		display: flex;
		flex-direction: column;
		gap: 1rem;
	}

	.post-card {
		display: block;
		padding: 1.1rem 1.25rem;
		border: 1px solid var(--terminal-border);
		border-radius: 8px;
		color: inherit;
		transition:
			border-color 0.15s ease,
			background 0.15s ease;
	}

	.post-card:hover {
		border-color: var(--terminal-primary);
		background: var(--terminal-bg-light);
	}

	.post-meta {
		display: flex;
		gap: 0.75rem;
		color: var(--terminal-muted);
		font-size: 0.8rem;
		margin-bottom: 0.4rem;
	}

	.post-author {
		color: var(--terminal-text);
		font-weight: 600;
	}

	.post-title {
		margin: 0 0 0.4rem 0;
		font-size: 1.15rem;
		color: var(--terminal-primary);
	}

	.post-excerpt {
		margin: 0 0 0.6rem 0;
		color: var(--terminal-text);
		font-size: 0.9rem;
		line-height: 1.6;
	}

	.post-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 0.4rem;
	}

	.post-tag {
		padding: 0.15rem 0.55rem;
		background: var(--terminal-bg-light);
		border-radius: 4px;
		color: var(--terminal-accent);
		font-size: 0.75rem;
	}

	.pagination {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 1rem;
		padding-top: 0.5rem;
	}

	.page-btn {
		padding: 0.4rem 0.9rem;
		background: transparent;
		border: 1px solid var(--terminal-border);
		border-radius: 4px;
		color: var(--terminal-text);
		font-family: inherit;
		font-size: 0.85rem;
		transition:
			border-color 0.15s ease,
			color 0.15s ease;
	}

	.page-btn:hover:not(:disabled) {
		border-color: var(--terminal-primary);
		color: var(--terminal-primary);
	}

	.page-btn:disabled {
		opacity: 0.4;
		cursor: default;
	}

	.page-status {
		color: var(--terminal-muted);
		font-size: 0.85rem;
	}
</style>
