<script lang="ts">
	import type { PageData } from './$types';

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

	interface Entity {
		id: string;
		name: string;
		type: string;
		aliases: string[];
		avatar_url: string | null;
		edge_count: number;
	}

	let entities = $state<Entity[]>(data.entities as Entity[]);
	let selected = $state<Set<string>>(new Set());
	let targetId = $state<string | null>(null);
	let merging = $state(false);
	let message = $state('');
	let filter = $state('');

	let filtered = $derived(
		filter
			? entities.filter(
					(e) =>
						e.name.toLowerCase().includes(filter.toLowerCase()) ||
						e.aliases?.some((a) => a.toLowerCase().includes(filter.toLowerCase()))
				)
			: entities
	);

	const typeColors: Record<string, string> = {
		person: '#3b82f6',
		organisasjon: '#f59e0b',
		sted: '#10b981',
		tema: '#8b5cf6',
		konsept: '#ec4899'
	};

	function toggleSelect(id: string) {
		const next = new Set(selected);
		if (next.has(id)) {
			next.delete(id);
			if (targetId === id) targetId = null;
		} else {
			next.add(id);
		}
		selected = next;
	}

	function setTarget(id: string) {
		targetId = id;
	}

	async function doMerge() {
		if (!targetId || selected.size < 2) return;
		const sourceIds = [...selected].filter((id) => id !== targetId);

		merging = true;
		message = '';

		try {
			const res = await fetch('/api/entities/merge', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ target_id: targetId, source_ids: sourceIds })
			});

			if (!res.ok) {
				const err = await res.json().catch(() => ({ message: res.statusText }));
				message = `Feil: ${err.message ?? res.statusText}`;
				return;
			}

			const result = await res.json();
			message = `Slettet ${result.merged.join(', ')} → beholdt ${result.target.name} (${result.target.aliases?.length ?? 0} aliaser)`;

			// Oppdater listen
			entities = entities.filter((e) => !sourceIds.includes(e.id));
			const idx = entities.findIndex((e) => e.id === targetId);
			if (idx >= 0) entities[idx] = { ...entities[idx], ...result.target };

			selected = new Set();
			targetId = null;
		} catch (e) {
			message = `Feil: ${e instanceof Error ? e.message : 'ukjent'}`;
		} finally {
			merging = false;
		}
	}
</script>

<div class="page">
	<h1>Entiteter</h1>

	<div class="toolbar">
		<input
			type="text"
			class="search"
			placeholder="Filtrer entiteter..."
			bind:value={filter}
		/>

		{#if selected.size >= 2}
			<div class="merge-bar">
				<span>{selected.size} valgt</span>
				{#if targetId}
					<button class="merge-btn" onclick={doMerge} disabled={merging}>
						{merging ? 'Slår sammen...' : `Slå sammen → ${entities.find((e) => e.id === targetId)?.name}`}
					</button>
				{:else}
					<span class="hint">Klikk "Behold" på entiteten som skal beholdes</span>
				{/if}
				<button class="clear-btn" onclick={() => { selected = new Set(); targetId = null; }}>Avbryt</button>
			</div>
		{/if}
	</div>

	{#if message}
		<div class="message" class:error={message.startsWith('Feil')}>{message}</div>
	{/if}

	<table>
		<thead>
			<tr>
				<th class="col-check"></th>
				<th>Navn</th>
				<th>Type</th>
				<th>Aliaser</th>
				<th class="col-edges">Edges</th>
				<th class="col-action"></th>
			</tr>
		</thead>
		<tbody>
			{#each filtered as entity (entity.id)}
				<tr class:selected={selected.has(entity.id)} class:is-target={targetId === entity.id}>
					<td class="col-check">
						<input
							type="checkbox"
							checked={selected.has(entity.id)}
							onchange={() => toggleSelect(entity.id)}
						/>
					</td>
					<td>
						<span class="dot" style:background={typeColors[entity.type] ?? '#8b92a5'}></span>
						{entity.name}
					</td>
					<td class="type">{entity.type}</td>
					<td class="aliases">{entity.aliases?.join(', ') || '—'}</td>
					<td class="col-edges">{entity.edge_count}</td>
					<td class="col-action">
						{#if selected.has(entity.id) && selected.size >= 2}
							<button
								class="target-btn"
								class:active={targetId === entity.id}
								onclick={() => setTarget(entity.id)}
							>
								{targetId === entity.id ? '✓ Beholdes' : 'Behold'}
							</button>
						{/if}
					</td>
				</tr>
			{/each}
		</tbody>
	</table>
</div>

<style>
	.page {
		max-width: 900px;
		margin: 0 auto;
		padding: 2rem 1rem;
	}

	h1 {
		font-size: 1.3rem;
		font-weight: 700;
		color: #f1f3f5;
		margin-bottom: 1rem;
	}

	.toolbar {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
		margin-bottom: 1rem;
	}

	.search {
		background: #0f1117;
		border: 1px solid #2d3148;
		border-radius: 6px;
		color: #e1e4e8;
		padding: 0.4rem 0.6rem;
		font-size: 0.85rem;
		font-family: inherit;
	}

	.search:focus {
		outline: none;
		border-color: #3b82f6;
	}

	.merge-bar {
		display: flex;
		align-items: center;
		gap: 0.75rem;
		padding: 0.5rem 0.75rem;
		background: rgba(139, 92, 246, 0.1);
		border: 1px solid rgba(139, 92, 246, 0.3);
		border-radius: 6px;
		font-size: 0.8rem;
		color: #c4b5fd;
	}

	.merge-btn {
		background: #8b5cf6;
		color: white;
		border: none;
		border-radius: 4px;
		padding: 0.3rem 0.6rem;
		font-size: 0.8rem;
		font-family: inherit;
		cursor: pointer;
	}

	.merge-btn:hover:not(:disabled) {
		background: #7c3aed;
	}

	.merge-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.clear-btn {
		background: none;
		border: 1px solid #2d3148;
		border-radius: 4px;
		color: #8b92a5;
		padding: 0.3rem 0.6rem;
		font-size: 0.8rem;
		font-family: inherit;
		cursor: pointer;
	}

	.hint {
		font-size: 0.75rem;
		color: #8b92a5;
	}

	.message {
		padding: 0.5rem 0.75rem;
		border-radius: 6px;
		font-size: 0.8rem;
		margin-bottom: 1rem;
		background: rgba(16, 185, 129, 0.1);
		color: #6ee7b7;
		border: 1px solid rgba(16, 185, 129, 0.3);
	}

	.message.error {
		background: rgba(248, 113, 113, 0.1);
		color: #fca5a5;
		border-color: rgba(248, 113, 113, 0.3);
	}

	table {
		width: 100%;
		border-collapse: collapse;
	}

	th {
		text-align: left;
		font-size: 0.7rem;
		font-weight: 600;
		color: #8b92a5;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		padding: 0.4rem 0.5rem;
		border-bottom: 1px solid #2d3148;
	}

	td {
		padding: 0.45rem 0.5rem;
		font-size: 0.85rem;
		color: #e1e4e8;
		border-bottom: 1px solid rgba(45, 49, 72, 0.5);
	}

	tr.selected {
		background: rgba(139, 92, 246, 0.05);
	}

	tr.is-target {
		background: rgba(16, 185, 129, 0.08);
	}

	.col-check { width: 30px; }
	.col-edges { width: 60px; text-align: center; }
	.col-action { width: 80px; }

	.dot {
		display: inline-block;
		width: 7px;
		height: 7px;
		border-radius: 50%;
		margin-right: 0.4rem;
		vertical-align: middle;
	}

	.type {
		color: #8b92a5;
		font-size: 0.75rem;
	}

	.aliases {
		color: #8b92a5;
		font-size: 0.75rem;
		max-width: 200px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.target-btn {
		background: none;
		border: 1px solid #2d3148;
		border-radius: 4px;
		color: #8b92a5;
		padding: 0.2rem 0.4rem;
		font-size: 0.7rem;
		font-family: inherit;
		cursor: pointer;
	}

	.target-btn:hover {
		border-color: #10b981;
		color: #6ee7b7;
	}

	.target-btn.active {
		background: rgba(16, 185, 129, 0.15);
		border-color: #10b981;
		color: #6ee7b7;
	}
</style>
