<script lang="ts">
	import { page } from '$app/stores';
	import { onMount } from 'svelte';
	import { helpApi, type HelpArticle } from '$lib/api/help';
	import { Button } from '$lib/components/ui/button/index.js';
	import {
		Loader2,
		ArrowLeft,
		Calendar,
		User,
		BookOpen,
		Download,
		FileText,
		ExternalLink
	} from 'lucide-svelte';
	import { marked } from 'marked';
	import DOMPurify from 'dompurify';

	// Helper to resolve an API path from the DB (e.g., /api/uploads/...) to a full URL pointing to the local backend.
	function resolveAssetUrl(url: string | undefined): string {
		try {
			if (!url) return '';
			if (url.startsWith('http://') || url.startsWith('https://')) return url;

			// Fallback to empty string if VITE_API_URL is missing
			// @ts-ignore
			const apiUrl = import.meta.env.VITE_API_URL || '';
			const base = apiUrl.replace(/\/$/, '');
			const cleanUrl = url.replace(/^\/api\//, '/');
			const finalUrl = `${base}${cleanUrl}`;
			return finalUrl;
		} catch (e) {
			console.error('[SSR DEBUG] Error in resolveAssetUrl:', e);
			return '';
		}
	}

	let article: HelpArticle | null = null; // Removed $state() as it's not reactive by itself in Svelte 5 standard store usage unless wrapped
	let loading = true; // Use standard value, reactive via variable assignment in Svelte 5 runes if enabled
	let error: string | null = null;
	let toc: { id: string; text: string; level: number }[] = [];

	onMount(async () => {
		const uuid = $page.params.uuid;
		try {
			article = await helpApi.getArticle(uuid);
			if (article) {
				parseTOC(article.content);
			}
		} catch (e: any) {
			error = e.message;
		} finally {
			loading = false;
		}
	});

	function parseTOC(content: string) {
		const lines = content.split('\n');
		toc = [];
		let inCodeBlock = false; // Simple check to avoid parsing headers inside code blocks

		lines.forEach((line) => {
			if (line.trim().startsWith('```')) {
				inCodeBlock = !inCodeBlock;
				return;
			}
			if (inCodeBlock) return;

			const match = line.match(/^(#{1,3})\s+(.*)$/);
			if (match) {
				const level = match[1].length;
				const text = match[2];
				const id = text.toLowerCase().replace(/[^\w]+/g, '-');
				toc = [...toc, { id, text, level }];
			}
		});
	}

	import { browser } from '$app/environment';

	function renderMarkdown(content: string) {
		if (!content) return '';
		try {
			const rawHtml = marked.parse(content) as string;
			// Add IDs to headers for TOC navigation
			let htmlWithIds = rawHtml.replace(/<h([1-3])>(.*?)<\/h\1>/g, (match, level, text) => {
				const id = text.toLowerCase().replace(/[^\w]+/g, '-');
				return `<h${level} id="${id}">${text}</h${level}>`;
			});

			// Rewrite image src and link hrefs to point to the local backend
			htmlWithIds = htmlWithIds.replace(/src="([^"]+)"/g, (match, src) => {
				return `src="${resolveAssetUrl(src)}"`;
			});
			htmlWithIds = htmlWithIds.replace(/href="(\/api\/uploads\/[^"]+)"/g, (match, href) => {
				return `href="${resolveAssetUrl(href)}"`;
			});

			if (browser && typeof window !== 'undefined') {
				// DOMPurify only works in the browser
				return DOMPurify.sanitize(htmlWithIds);
			}
			return htmlWithIds; // SSR returns raw HTML (or could use isomorphic-dompurify)
		} catch (e) {
			console.error('Markdown parsing error:', e);
			return '';
		}
	}

	function scrollToHeader(id: string) {
		const element = document.getElementById(id);
		if (element) {
			element.scrollIntoView({ behavior: 'smooth' });
		}
	}
</script>

<div class="flex h-full flex-col bg-background">
	<!-- Toolbar -->
	<div
		class="sticky top-0 z-10 flex items-center gap-4 border-b bg-card/50 px-6 py-3 backdrop-blur supports-[backdrop-filter]:bg-background/60"
	>
		<Button variant="ghost" size="sm" href="/dashboard/help-center" class="gap-2">
			<ArrowLeft class="h-4 w-4" />
			Volver a la Biblioteca
		</Button>
		<div class="mx-2 h-4 w-px bg-border"></div>
		{#if article}
			<span class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
				<BookOpen class="h-4 w-4" />
				{article.category || 'General'}
			</span>
		{/if}
	</div>

	<div class="relative flex-1 overflow-hidden">
		{#if loading}
			<div class="flex h-full items-center justify-center">
				<Loader2 class="h-8 w-8 animate-spin text-primary" />
			</div>
		{:else if error}
			<div class="flex h-full flex-col items-center justify-center gap-2 text-destructive">
				<p class="text-lg font-medium">Error al cargar el capítulo</p>
				<p class="text-sm text-muted-foreground">{error}</p>
			</div>
		{:else if article}
			<div class="flex h-full">
				<!-- Article Content -->
				<div class="flex-1 overflow-y-auto scroll-smooth px-8 py-10 md:px-12 lg:px-16">
					<div class="mx-auto max-w-4xl pb-20">
						<!-- Header -->
						<div class="mb-8 border-b pb-6">
							<h1 class="mb-4 text-4xl font-bold tracking-tight text-foreground">
								{article.title}
							</h1>
							<div class="flex items-center gap-6 text-sm text-muted-foreground">
								<span class="flex items-center gap-1.5">
									<User class="h-4 w-4" />
									{article.last_editor}
								</span>
								<span class="flex items-center gap-1.5">
									<Calendar class="h-4 w-4" />
									{new Date(article.updated_at).toLocaleDateString(undefined, {
										dateStyle: 'long'
									})}
								</span>
							</div>
						</div>

						<!-- Content -->
						{#if article.content_type === 'article'}
							<article
								class="prose max-w-none prose-slate dark:prose-invert prose-headings:scroll-mt-20 prose-img:rounded-lg prose-img:shadow-md"
							>
								{@html renderMarkdown(article.content)}
							</article>
						{:else if article.content_type === 'pdf'}
							<div class="flex flex-col gap-4">
								<div class="flex items-center justify-between rounded-lg border bg-muted/30 p-4">
									<div class="flex items-center gap-3">
										<FileText class="h-8 w-8 text-red-500" />
										<div>
											<p class="font-medium">Documento PDF</p>
											<p class="text-xs text-muted-foreground">
												{article.file_size ? (article.file_size / 1024 / 1024).toFixed(2) : '??'} MB
											</p>
										</div>
									</div>
									<div class="flex gap-2">
										<Button
											variant="outline"
											size="sm"
											href={resolveAssetUrl(article.file_url)}
											target="_blank"
										>
											<ExternalLink class="mr-2 h-4 w-4" />
											Abrir en pestaña
										</Button>
										<Button
											size="sm"
											href={resolveAssetUrl(article.file_url)}
											download={article.title}
										>
											<Download class="mr-2 h-4 w-4" />
											Descargar
										</Button>
									</div>
								</div>
								<!-- PDF Embed -->
								<iframe
									src={resolveAssetUrl(article.file_url)}
									title={article.title}
									class="h-[800px] w-full rounded-xl border shadow-inner"
								></iframe>
							</div>
						{:else if article.content_type === 'video'}
							<div class="flex flex-col gap-4">
								<video controls class="w-full rounded-xl border shadow-lg">
									<source src={resolveAssetUrl(article.file_url)} type={article.mime_type} />
									Tu navegador no soporta videos.
								</video>
								<div class="rounded-lg border bg-muted/30 p-4">
									<p class="text-sm font-medium">Información del archivo</p>
									<p class="text-xs text-muted-foreground">{article.mime_type}</p>
								</div>
							</div>
						{:else}
							<div
								class="flex flex-col items-center justify-center gap-6 rounded-2xl border border-dashed py-20"
							>
								<div class="rounded-full bg-primary/10 p-6">
									<Download class="h-12 w-12 text-primary" />
								</div>
								<div class="text-center">
									<h3 class="text-xl font-semibold">Archivo para descargar</h3>
									<p class="text-muted-foreground truncate max-w-md">
										Este archivo no tiene vista previa directa.
									</p>
								</div>
								<Button
									href={resolveAssetUrl(article.file_url)}
									download={article.title}
									class="px-8 shadow-lg"
								>
									<Download class="mr-2 h-4 w-4" />
									Descargar ahora
								</Button>
							</div>
						{/if}
					</div>
				</div>

				<!-- TOC Sidebar (Desktop) -->
				{#if toc.length > 0}
					<div class="hidden w-72 overflow-y-auto border-l bg-muted/5 p-6 xl:block">
						<h4 class="mb-4 text-sm font-semibold tracking-wider text-muted-foreground uppercase">
							En este capitulo
						</h4>
						<nav class="space-y-1">
							{#each toc as item}
								<button
									class="block w-full py-1 text-left text-sm text-muted-foreground transition-colors hover:text-foreground
                                    {item.level === 1 ? 'font-medium' : 'pl-' + item.level * 2}
                                    "
									onclick={() => scrollToHeader(item.id)}
								>
									{item.text}
								</button>
							{/each}
						</nav>
					</div>
				{/if}
			</div>
		{/if}
	</div>
</div>
