<script lang="ts">
import { goto } from '$app/navigation';
import { untrack } from 'svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import CorrespondenzPersonBar from './CorrespondenzPersonBar.svelte';
import CorrespondenzFilterControls from './CorrespondenzFilterControls.svelte';
import SinglePersonHintBar from './SinglePersonHintBar.svelte';
import ConversationTimeline from './ConversationTimeline.svelte';
import CorrespondenzEmptyState from './CorrespondenzEmptyState.svelte';
import { m } from '$lib/paraglide/messages.js';

let { data } = $props();

// Filter values are local $state so swapPersons/toggleSort can mutate them before goto.
// They are initialised once from server data and never re-synced — navigation replaces
// the page component, so each load gets a fresh init.
let senderId = $state(untrack(() => data.filters.senderId));
let receiverId = $state(untrack(() => data.filters.receiverId));
let fromDate = $state(untrack(() => data.filters.from));
let toDate = $state(untrack(() => data.filters.to));
let sortDir = $state(untrack(() => data.filters.dir));

// Names are pure reads of server data — no local mutation needed.
const senderName = $derived(data.initialValues.senderName);
const receiverName = $derived(data.initialValues.receiverName);

// Side-effect only: persist the resolved sender to localStorage once the name is available.
$effect(() => {
	if (data.filters.senderId && data.initialValues.senderName) {
		persistRecentPerson(data.filters.senderId, data.initialValues.senderName);
	}
});

const isSinglePerson = $derived(!!senderId && !receiverId);

const RECENT_STORAGE_KEY = 'korrespondenz_recent_persons';
const MAX_RECENT = 5;

function persistRecentPerson(id: string, name: string) {
	if (!id) return;
	try {
		const raw = localStorage.getItem(RECENT_STORAGE_KEY);
		const existing: { id: string; name: string }[] = raw ? JSON.parse(raw) : [];
		const filtered = existing.filter((p) => p.id !== id);
		const updated = [{ id, name }, ...filtered].slice(0, MAX_RECENT);
		localStorage.setItem(RECENT_STORAGE_KEY, JSON.stringify(updated));
	} catch {
		// localStorage unavailable — silently ignore
	}
}

function applyFilters() {
	const params = new SvelteURLSearchParams();
	if (senderId) params.set('senderId', senderId);
	if (receiverId) params.set('receiverId', receiverId);
	if (fromDate) params.set('from', fromDate);
	if (toDate) params.set('to', toDate);
	params.set('dir', sortDir);
	goto(`/korrespondenz?${params.toString()}`, { keepFocus: true });
}

function toggleSort() {
	sortDir = sortDir === 'DESC' ? 'ASC' : 'DESC';
	applyFilters();
}

function swapPersons() {
	const tmp = senderId;
	senderId = receiverId;
	receiverId = tmp;
	applyFilters();
}

function selectPerson(id: string) {
	if (!id) {
		document.querySelector<HTMLInputElement>('#senderId-search')?.focus();
		return;
	}
	senderId = id;
	receiverId = '';
	applyFilters();
}
</script>

<!-- Strips — pulled up to negate main's py-6 top padding so they sit flush -->
<div class="-mt-6">
	<!-- Strip: Row 1 — full width, no container -->
	<CorrespondenzPersonBar
		bind:senderId={senderId}
		bind:receiverId={receiverId}
		initialSenderName={data.initialValues.senderName}
		initialReceiverName={data.initialValues.receiverName}
		onapplyFilters={applyFilters}
		onswapPersons={swapPersons}
	/>

	<!-- Strip: Row 2 — full width -->
	<CorrespondenzFilterControls
		senderId={senderId}
		bind:fromDate={fromDate}
		bind:toDate={toDate}
		bind:sortDir={sortDir}
		documentCount={data.documents.length}
		onapplyFilters={applyFilters}
		ontoggleSort={toggleSort}
	/>

	<!-- Single-person hint bar -->
	{#if isSinglePerson}
		<SinglePersonHintBar
			senderName={senderName}
			fromDate={fromDate || undefined}
			toDate={toDate || undefined}
			sortDir={sortDir}
		/>
	{/if}
</div>

<!-- Content area with padding -->
<div class="px-[18px] py-[14px]">
	{#if !senderId}
		<CorrespondenzEmptyState onSelectPerson={selectPerson} />
	{:else if data.documents.length === 0}
		<div
			class="flex flex-col items-center justify-center rounded-sm border border-line bg-muted py-24 text-center shadow-sm"
		>
			<p class="font-serif text-ink">{m.conv_no_results_heading()}</p>
			<p class="mt-2 text-sm text-ink-3">{m.conv_no_results_text()}</p>
		</div>
	{:else}
		<ConversationTimeline
			documents={data.documents}
			senderId={senderId}
			receiverId={receiverId}
			canWrite={data.canWrite}
			senderName={senderName}
			receiverName={receiverName}
		/>
	{/if}
</div>
