<script lang="ts">
	import ParallaxLandscape from "$lib/components/ParallaxLandscape.svelte";
	import Icon from "@iconify/svelte";
	import { onMount } from "svelte";

	import CatalogueHeader from "$lib/components/catalogue/CatalogueHeader.svelte";
	import ReportCard from "$lib/components/catalogue/ReportCard.svelte";
	import IncidentCard from "$lib/components/catalogue/IncidentCard.svelte";
	import CompanyModal from "$lib/components/catalogue/CompanyModal.svelte";
	import IncidentModal from "$lib/components/catalogue/IncidentModal.svelte";

	
	type ViewMode = "company" | "user";
	let viewMode = $state<ViewMode>("company");

	
	interface Report {
		company_name: string;
		year: string | number;
		sector: string;
		greenwashing_score: number | string;
		filename: string;
		title?: string;
		snippet?: string;
	}

	interface Incident {
		_id: string;
		product_name: string;
		detected_brand: string;
		user_description?: string;
		created_at: string;
		image_base64?: string;
		report_type?: "product" | "company";
		analysis: {
			verdict: string;
			confidence: string;
			severity: string;
			reasoning: string;
			is_greenwashing: boolean;
			key_claims?: string[];
			red_flags?: string[];
			recommendations?: string;
		};
	}

	let reports = $state<Report[]>([]);
	let incidents = $state<Incident[]>([]);
	let searchQuery = $state("");
	let isLoading = $state(false);

	
	const categories = [
		"All",
		"Tech",
		"Energy",
		"Automotive",
		"Aerospace",
		"Data",
		"Retail",
		"Other",
	];
	let selectedCategory = $state("All");

	
	async function fetchReports() {
		isLoading = true;
		try {
			const res = await fetch("/api/reports/");
			const data = await res.json();
			if (Array.isArray(data)) reports = data;
		} catch (e) {
			console.error("Failed to fetch reports", e);
		} finally {
			isLoading = false;
		}
	}

	async function fetchIncidents() {
		isLoading = true;
		try {
			const res = await fetch("/api/incidents/list");
			const data = await res.json();
			if (Array.isArray(data)) incidents = data;
		} catch (e) {
			console.error("Failed to fetch incidents", e);
		} finally {
			isLoading = false;
		}
	}

	onMount(() => {
		fetchReports();
		fetchIncidents();
	});

	
	async function handleSearch() {
		if (!searchQuery.trim()) {
			fetchReports();
			return;
		}
		isLoading = true;
		try {
			const res = await fetch(
				"/api/reports/search",
				{
					method: "POST",
					headers: { "Content-Type": "application/json" },
					body: JSON.stringify({ query: searchQuery }),
				},
			);
			const data = await res.json();
			if (Array.isArray(data)) reports = data;
		} catch (e) {
			console.error("Search failed", e);
		} finally {
			isLoading = false;
		}
	}

	let debounceTimer: ReturnType<typeof setTimeout>;
	function onSearchInput() {
		clearTimeout(debounceTimer);
		debounceTimer = setTimeout(handleSearch, 600);
	}

	
	let currentPage = $state(1);
	const itemsPerPage = 10;

	let filteredReports = $derived.by(() => {
		if (searchQuery.length > 0) return reports;
		if (selectedCategory === "All") return reports;
		return reports.filter((r) =>
			(r.sector?.toLowerCase() || "other").includes(
				selectedCategory.toLowerCase(),
			),
		);
	});

	let paginatedReports = $derived.by(() => {
		const start = (currentPage - 1) * itemsPerPage;
		return filteredReports.slice(start, start + itemsPerPage);
	});

	let totalPages = $derived(Math.ceil(filteredReports.length / itemsPerPage));

	$effect(() => {
		const _ = searchQuery;
		const __ = selectedCategory;
		currentPage = 1;
	});

	function goToPage(page: number) {
		if (page >= 1 && page <= totalPages) {
			currentPage = page;
		}
	}

	
	let selectedReport = $state<Report | null>(null);
	let selectedIncident = $state<Incident | null>(null);
</script>

<svelte:head>
	<title>Ethix - Sustainability Reports</title>
	<meta
		name="description"
		content="Search and browse verified sustainability reports and greenwashing analysis."
	/>
</svelte:head>

<div class="relative w-full min-h-screen overflow-x-hidden">
	
	{#if selectedReport}
		<CompanyModal
			report={selectedReport}
			onclose={() => (selectedReport = null)}
		/>
	{/if}

	{#if selectedIncident}
		<IncidentModal
			incident={selectedIncident}
			onclose={() => (selectedIncident = null)}
		/>
	{/if}

	<div class="hidden lg:block">
		<ParallaxLandscape />
		<div class="fixed inset-0 pointer-events-none"></div>
	</div>

	<div
		class="relative z-10 px-6 sm:px-8 lg:px-12 pt-16 pb-35 max-w-275 mx-auto"
	>
		<CatalogueHeader
			bind:viewMode
			bind:searchQuery
			bind:selectedCategory
			{categories}
			{onSearchInput}
			{currentPage}
			{totalPages}
			{goToPage}
		/>

		{#if isLoading}
			<div
				class="flex flex-col items-center justify-center py-24 gap-5 bg-black/60 backdrop-blur-2xl rounded-3xl border border-white/15 shadow-2xl shadow-black/50 mt-8"
			>
				<Icon
					icon="eos-icons:loading"
					width="48"
					class="text-emerald-400"
				/>
				<p class="text-white/70 font-medium text-lg">
					Syncing with database...
				</p>
			</div>
		{:else if viewMode === "company"}
			{#if filteredReports.length === 0}
				<div
					class="bg-black/60 backdrop-blur-2xl rounded-3xl p-16 text-center border border-white/15 shadow-2xl shadow-black/50 mt-8"
				>
					<p class="text-white/70 text-lg font-medium">
						No reports found matching your criteria.
					</p>
				</div>
			{:else}
				<div class="flex flex-col gap-6 mt-8">
					{#each paginatedReports as report}
						<ReportCard
							{report}
							openReport={(r) => (selectedReport = r)}
							{searchQuery}
						/>
					{/each}
				</div>
			{/if}
		{:else if incidents.length === 0}
			<div
				class="bg-black/60 backdrop-blur-2xl rounded-3xl p-20 text-center border border-white/15 shadow-2xl shadow-black/50 flex flex-col items-center gap-5 mt-8"
			>
				<Icon
					icon="ri:file-warning-line"
					width="56"
					class="text-white/30"
				/>
				<p class="text-white/70 text-lg font-medium">
					No user reports yet.
				</p>
				<p class="text-white/50 text-sm">
					Be the first to report greenwashing!
				</p>
			</div>
		{:else}
			<div class="flex flex-col gap-6 mt-8">
				{#each incidents as incident}
					<IncidentCard
						{incident}
						onclick={() => (selectedIncident = incident)}
					/>
				{/each}
			</div>
		{/if}
	</div>
</div>

<style>
	:global(body) {
		background-color: #0c0c0c;
		color: white;
	}
</style>
