<script lang="ts">
	import type { PageData } from './$types';
	import type { ChapterIdx } from '$lib/server/pocketbase';
	import * as m from '$lib/paraglide/messages.js';

	let { data }: { data: PageData } = $props();

	const PAGE_SIZE = 100;

	// ── Search ──────────────────────────────────────────────────────────────────
	let searchQuery = $state('');

	const filtered = $derived(
		(() => {
			const q = searchQuery.trim().toLowerCase();
			if (!q) return data.chapters;
			return data.chapters.filter(
				(c: ChapterIdx) =>
					String(c.number).includes(q) ||
					c.title.toLowerCase().includes(q)
			);
		})()
	);

	// ── Page groups (only shown when not searching) ──────────────────────────
	const totalGroups = $derived(Math.ceil(data.chapters.length / PAGE_SIZE));

	// Which group the current chapter is in (0-indexed)
	const currentGroup = $derived(
		data.lastChapter
			? Math.floor(
					(data.chapters.findIndex((c: ChapterIdx) => c.number === data.lastChapter)) /
					PAGE_SIZE
			  )
			: 0
	);

	let activeGroup = $state(0);

	// On mount, jump to the group containing the current chapter
	$effect(() => {
		if (data.lastChapter && currentGroup >= 0) {
			activeGroup = currentGroup;
		}
	});

	const visibleChapters = $derived(
		searchQuery.trim()
			? filtered
			: data.chapters.slice(activeGroup * PAGE_SIZE, (activeGroup + 1) * PAGE_SIZE)
	);

	function groupLabel(i: number): string {
		const from = i * PAGE_SIZE + 1;
		const to = Math.min((i + 1) * PAGE_SIZE, data.chapters.length);
		return `${from}–${to}`;
	}
</script>

<svelte:head>
	<title>{m.chapters_page_title({ title: data.book.title })}</title>
</svelte:head>

<!-- ── Back link + title ─────────────────────────────────────────────────── -->
<div class="flex items-center gap-3 mb-5">
	<a
		href="/books/{data.book.slug}"
		class="flex items-center gap-1.5 text-(--color-muted) hover:text-(--color-text) transition-colors text-sm"
	>
		<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
			<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
		</svg>
		{m.common_back()}
	</a>
	<span class="text-(--color-border)">/</span>
	<h1 class="text-base font-semibold text-(--color-text) truncate">{data.book.title}</h1>
</div>

<!-- ── Search bar ───────────────────────────────────────────────────────── -->
<div class="relative mb-4">
	<svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-(--color-muted) pointer-events-none" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
		<circle cx="11" cy="11" r="8"/><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-4.35-4.35"/>
	</svg>
	<input
		type="search"
		placeholder={m.chapters_search_placeholder()}
		bind:value={searchQuery}
		class="w-full pl-9 pr-4 py-2.5 rounded-lg bg-(--color-surface-2) border border-(--color-border) text-(--color-text) placeholder-zinc-500 text-sm focus:outline-none focus:border-(--color-brand) transition-colors"
	/>
	{#if searchQuery}
		<button
			onclick={() => (searchQuery = '')}
			class="absolute right-3 top-1/2 -translate-y-1/2 text-(--color-muted) hover:text-(--color-text)"
			aria-label="Clear search"
		>
			<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
			</svg>
		</button>
	{/if}
</div>

<!-- ── Page-group selector (hidden while searching) ──────────────────────── -->
{#if !searchQuery && totalGroups > 1}
	<div class="flex flex-wrap gap-1.5 mb-4">
		{#each Array(totalGroups) as _, i}
			<button
				onclick={() => (activeGroup = i)}
				class="px-2.5 py-1 rounded text-xs font-medium transition-colors
					{activeGroup === i
						? 'bg-(--color-brand) text-(--color-surface)'
						: 'bg-(--color-surface-2) text-(--color-muted) hover:bg-(--color-surface-3) hover:text-(--color-text)'}
					{currentGroup === i && activeGroup !== i ? 'ring-1 ring-(--color-brand)/50' : ''}"
			>
				{groupLabel(i)}
			</button>
		{/each}
	</div>
{/if}

<!-- ── Jump-to-current banner ──────────────────────────────────────────── -->
{#if data.lastChapter && data.lastChapter > 0 && !searchQuery && activeGroup !== currentGroup}
	<button
		onclick={() => (activeGroup = currentGroup)}
		class="flex items-center gap-2 w-full px-3 py-2 mb-3 rounded-lg bg-(--color-brand)/10 border border-(--color-brand)/25 text-(--color-brand) text-sm hover:bg-(--color-brand)/20 transition-colors"
	>
		<svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
			<path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7"/>
		</svg>
		{m.chapters_jump_to({ n: String(data.lastChapter) })}
	</button>
{/if}

<!-- ── Chapter list ───────────────────────────────────────────────────── -->
{#if visibleChapters.length === 0}
	{#if searchQuery}
		<p class="text-(--color-muted) text-sm py-8 text-center">{m.chapters_no_match({ q: searchQuery })}</p>
	{:else}
		<p class="text-(--color-muted) text-sm">{m.chapters_none_available()}</p>
	{/if}
{:else}
	<!-- Result count while searching -->
	{#if searchQuery}
		<p class="text-xs text-(--color-muted) mb-2">{m.chapters_result_count({ n: String(visibleChapters.length) })}</p>
	{/if}

	<div class="flex flex-col gap-0.5">
		{#each visibleChapters as chapter}
			{@const isCurrent = data.lastChapter === chapter.number}
			<a
				href="/books/{data.book.slug}/chapters/{chapter.number}"
				id="ch-{chapter.number}"
				class="flex items-center gap-3 px-3 py-2.5 rounded transition-colors group
					{isCurrent ? 'bg-(--color-surface-2)' : 'hover:bg-(--color-surface-2)/60'}"
			>
				<!-- Number badge -->
				<span
					class="w-9 text-right text-sm font-mono flex-shrink-0
						{isCurrent ? 'text-(--color-brand) font-semibold' : 'text-(--color-muted)'}"
				>
					{chapter.number}
				</span>

				<!-- Title -->
				<span
					class="flex-1 min-w-0 text-sm truncate transition-colors
						{isCurrent ? 'text-(--color-brand-dim) font-medium' : 'text-(--color-text) group-hover:text-(--color-text)'}"
				>
					{chapter.title || m.reader_chapter_n({ n: String(chapter.number) })}
				</span>

				<!-- Date — desktop only -->
				{#if chapter.date_label}
					<span class="hidden sm:block text-xs text-(--color-muted) flex-shrink-0">
						{chapter.date_label}
					</span>
				{/if}

				<!-- Reading indicator -->
				{#if isCurrent}
					<span class="text-xs text-(--color-brand) font-medium flex-shrink-0">{m.chapters_reading_indicator()}</span>
				{/if}
			</a>
		{/each}
	</div>

	<!-- Bottom page-group nav (mirrors top, for long lists) -->
	{#if !searchQuery && totalGroups > 1}
		<div class="flex flex-wrap gap-1.5 mt-5 pt-4 border-t border-(--color-border)">
			{#each Array(totalGroups) as _, i}
				<button
					onclick={() => { activeGroup = i; window.scrollTo({ top: 0, behavior: 'smooth' }); }}
					class="px-2.5 py-1 rounded text-xs font-medium transition-colors
						{activeGroup === i
							? 'bg-(--color-brand) text-(--color-surface)'
							: 'bg-(--color-surface-2) text-(--color-muted) hover:bg-(--color-surface-3) hover:text-(--color-text)'}
						{currentGroup === i && activeGroup !== i ? 'ring-1 ring-(--color-brand)/50' : ''}"
				>
					{groupLabel(i)}
				</button>
			{/each}
		</div>
	{/if}
{/if}
