<script lang="ts">
	import Modal from './Modal.svelte';
	import MdiIcon from './MdiIcon.svelte';
	import { t } from '$lib/i18n';
	import type { BlockedByDetail } from '$lib/api';

	let { open = false, detail = null, onclose } = $props<{
		open: boolean;
		detail: BlockedByDetail | null;
		onclose: () => void;
	}>();

	const blockedCount = $derived(detail?.blocked_by?.length ?? 0);
</script>

<Modal {open} title={t('common.cannotDelete')} onclose={onclose}>
	{#if detail}
		<div class="flex items-start gap-3 mb-4">
			<div class="flex items-center justify-center w-9 h-9 rounded-full flex-shrink-0"
				style="background: var(--color-error-bg); color: var(--color-error-fg);">
				<MdiIcon name="mdiLinkVariant" size={20} />
			</div>
			<div class="flex-1 min-w-0">
				<p class="text-sm font-medium mb-1 break-words">{detail.message}</p>
				{#if detail.entity}
					<p class="text-xs break-all" style="color: var(--color-muted-foreground);">{detail.entity}</p>
				{/if}
			</div>
		</div>
		<div class="flex items-center justify-between mb-2">
			<p class="text-xs" style="color: var(--color-muted-foreground);">{t('common.blockedByIntro')}</p>
			{#if blockedCount > 0}
				<span class="text-[0.65rem] font-mono px-1.5 py-0.5 rounded"
					style="background: var(--color-muted); color: var(--color-muted-foreground);">
					{blockedCount}
				</span>
			{/if}
		</div>
		{#if blockedCount > 0}
			<ul class="space-y-1.5 max-h-64 overflow-y-auto pr-1 mb-5">
				{#each detail.blocked_by as consumer}
					<li class="flex items-start gap-2 text-sm px-3 py-2 rounded-md"
						style="background: var(--color-muted); border: 1px solid var(--color-border);">
						<span class="flex-shrink-0 mt-0.5" style="color: var(--color-muted-foreground);">
							<MdiIcon name="mdiChevronRight" size={14} />
						</span>
						<span class="font-mono text-xs break-all min-w-0 flex-1">{consumer}</span>
					</li>
				{/each}
			</ul>
		{/if}
	{/if}
	<div class="flex justify-end">
		<button onclick={onclose} class="blocked-by-close-btn">
			{t('common.close')}
		</button>
	</div>
</Modal>

<style>
	.blocked-by-close-btn {
		padding: 0.5rem 1rem;
		border-radius: 0.5rem;
		font-size: 0.875rem;
		border: 1px solid var(--color-border);
		background: transparent;
		color: var(--color-foreground);
		cursor: pointer;
		transition: all 0.2s ease;
	}
	.blocked-by-close-btn:hover {
		background: var(--color-muted);
	}
</style>
