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

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

	// ── Subscribe / unsubscribe ──────────────────────────────────────────────────
	let subscribed = $state(untrack(() => data.isSubscribed));
	let followerCount = $state(untrack(() => data.profile.followerCount));
	let subLoading = $state(false);

	async function toggleSubscribe() {
		if (subLoading) return;
		subLoading = true;
		try {
			const method = subscribed ? 'DELETE' : 'POST';
			const res = await fetch(`/api/users/${data.profile.username}/subscribe`, { method });
			if (res.ok) {
				subscribed = !subscribed;
				followerCount += subscribed ? 1 : -1;
			}
		} finally {
			subLoading = false;
		}
	}

	// ── Helpers ──────────────────────────────────────────────────────────────────
	function initials(username: string): string {
		return username.slice(0, 2).toUpperCase();
	}

	function joinDate(iso: string): string {
		try {
			return new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'long' });
		} catch {
			return '';
		}
	}

	function parseGenres(genres: string[] | string | null | undefined): string[] {
		if (!genres) return [];
		if (Array.isArray(genres)) return genres;
		try {
			const parsed = JSON.parse(genres);
			return Array.isArray(parsed) ? parsed : [];
		} catch {
			return [];
		}
	}
</script>

<svelte:head>
	<title>{m.user_page_title({ username: data.profile.username })}</title>
</svelte:head>

<!-- ── Header ────────────────────────────────────────────────────────────── -->
<div class="flex items-start gap-5 mb-8">
	<!-- Avatar -->
	<div class="flex-shrink-0">
		{#if data.avatarUrl}
			<img
				src={data.avatarUrl}
				alt={data.profile.username}
				class="w-20 h-20 rounded-full object-cover ring-2 ring-(--color-border)"
			/>
		{:else}
			<div class="w-20 h-20 rounded-full bg-(--color-surface-3) flex items-center justify-center text-2xl font-bold text-(--color-text) ring-2 ring-(--color-border)">
				{initials(data.profile.username)}
			</div>
		{/if}
	</div>

	<!-- Info -->
	<div class="flex-1 min-w-0">
		<h1 class="text-xl font-bold text-(--color-text) mb-0.5">{data.profile.username}</h1>
		<p class="text-xs text-(--color-muted) mb-3">{m.user_joined({ date: joinDate(data.profile.created) })}</p>

		<!-- Stats row -->
		<div class="flex gap-5 text-sm mb-4">
			<span>
				<span class="font-semibold text-(--color-text)">{followerCount}</span>
				<span class="text-(--color-muted) ml-1">{m.user_followers_label()}</span>
			</span>
			<span>
				<span class="font-semibold text-(--color-text)">{data.profile.followingCount}</span>
				<span class="text-(--color-muted) ml-1">{m.user_following_label()}</span>
			</span>
		</div>

		<!-- Subscribe button — only shown to logged-in visitors viewing someone else's profile -->
		{#if data.isLoggedIn && !data.isSelf}
			<button
				onclick={toggleSubscribe}
				disabled={subLoading}
				class="px-4 py-1.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50
					{subscribed
						? 'bg-(--color-surface-3) text-(--color-text) hover:bg-zinc-600 border border-(--color-border)'
						: 'bg-(--color-brand) text-(--color-surface) hover:bg-(--color-brand-dim)'}"
			>
				{#if subLoading}
					…
				{:else if subscribed}
					{m.user_unfollow()}
				{:else}
					{m.user_follow()}
				{/if}
			</button>
		{:else if !data.isLoggedIn}
			<a
				href="/login"
				class="inline-block px-4 py-1.5 rounded-lg text-sm font-medium bg-(--color-brand) text-(--color-surface) hover:bg-(--color-brand-dim) transition-colors"
			>
				{m.user_follow()}
			</a>
		{/if}
	</div>
</div>

<!-- ── Currently Reading ─────────────────────────────────────────────────── -->
{#if data.currentlyReading.length > 0}
	<section class="mb-10">
		<h2 class="text-base font-semibold text-(--color-text) mb-3">{m.user_currently_reading()}</h2>
		<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
			{#each data.currentlyReading as { book, chapter }}
				<a
					href="/books/{book.slug}"
					class="group flex flex-col rounded-lg overflow-hidden bg-(--color-surface-2) hover:bg-(--color-surface-3) transition-colors border border-(--color-border) hover:border-zinc-500"
				>
					<div class="aspect-[2/3] bg-(--color-surface) overflow-hidden relative">
						{#if book.cover}
							<img
								src={book.cover}
								alt={book.title}
								class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
								loading="lazy"
							/>
						{:else}
							<div class="w-full h-full flex items-center justify-center text-(--color-muted)">
								<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
								</svg>
							</div>
						{/if}
						<span class="absolute bottom-1.5 right-1.5 text-xs bg-(--color-brand) text-(--color-surface) font-bold px-1.5 py-0.5 rounded">
							ch.{chapter}
						</span>
					</div>
					<div class="p-2">
						<h3 class="text-xs font-semibold text-(--color-text) line-clamp-2 leading-snug">{book.title}</h3>
						{#if book.author}
							<p class="text-xs text-(--color-muted) truncate mt-0.5">{book.author}</p>
						{/if}
					</div>
				</a>
			{/each}
		</div>
	</section>
{/if}

<!-- ── Library ───────────────────────────────────────────────────────────── -->
{#if data.library.length > 0}
	<section class="mb-10">
		<h2 class="text-base font-semibold text-(--color-text) mb-3">
			{m.user_library_count({ n: String(data.library.length) })}
		</h2>
		<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
			{#each data.library as { book, chapter, saved }}
				{@const genres = parseGenres(book.genres)}
				<a
					href="/books/{book.slug}"
					class="group flex flex-col rounded-lg overflow-hidden bg-(--color-surface-2) hover:bg-(--color-surface-3) transition-colors border border-(--color-border) hover:border-zinc-500"
				>
					<div class="aspect-[2/3] bg-(--color-surface) overflow-hidden relative">
						{#if book.cover}
							<img
								src={book.cover}
								alt={book.title}
								class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
								loading="lazy"
							/>
						{:else}
							<div class="w-full h-full flex items-center justify-center text-(--color-muted)">
								<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
								</svg>
							</div>
						{/if}
						{#if chapter}
							<span class="absolute bottom-1.5 right-1.5 text-xs bg-(--color-surface)/80 text-(--color-text) font-medium px-1.5 py-0.5 rounded">
								ch.{chapter}
							</span>
						{/if}
						{#if saved && !chapter}
							<span class="absolute top-1.5 right-1.5">
								<svg class="w-3.5 h-3.5 text-(--color-brand)" fill="currentColor" viewBox="0 0 24 24">
									<path d="M5 3a2 2 0 00-2 2v16l9-4 9 4V5a2 2 0 00-2-2H5z"/>
								</svg>
							</span>
						{/if}
					</div>
					<div class="p-2">
						<h3 class="text-xs font-semibold text-(--color-text) line-clamp-2 leading-snug">{book.title}</h3>
						{#if book.author}
							<p class="text-xs text-(--color-muted) truncate mt-0.5">{book.author}</p>
						{/if}
						{#if genres.length > 0}
							<p class="text-xs text-(--color-muted) truncate mt-0.5">{genres[0]}</p>
						{/if}
					</div>
				</a>
			{/each}
		</div>
	</section>
{/if}

<!-- ── Empty state ───────────────────────────────────────────────────────── -->
{#if data.library.length === 0 && data.currentlyReading.length === 0}
	<div class="py-16 text-center text-(--color-muted)">
		<svg class="w-10 h-10 mx-auto mb-3 text-(--color-border)" fill="none" stroke="currentColor" viewBox="0 0 24 24">
			<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
		</svg>
		<p class="text-sm">{m.user_no_books()}</p>
	</div>
{/if}
