<script lang="ts">
	import { slide } from 'svelte/transition';
	import { t } from '$lib/i18n';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import IconButton from '$lib/components/IconButton.svelte';
	import EntitySelect from '$lib/components/EntitySelect.svelte';
	import type { NotificationTarget, TargetReceiver, TelegramChat } from '$lib/types';

	interface Props {
		target: NotificationTarget;
		typeIcons: Record<string, string>;
		addingReceiverForTarget: number | null;
		receiverForm: Record<string, any>;
		receiverSubmitting: boolean;
		receiverHeadersError: string;
		receiverBotChats: Record<number, TelegramChat[]>;
		receiverTesting: Record<number, boolean>;
		receiverLabel: (target: NotificationTarget, recv: TargetReceiver) => string;
		onopenReceiverForm: (targetId: number, targetType: string) => void;
		onsaveReceiver: (targetId: number) => void;
		oncancelReceiver: () => void;
		ontoggleReceiver: (targetId: number, receiver: TargetReceiver) => void;
		onremoveReceiver: (targetId: number, receiver: TargetReceiver) => void;
		ontestReceiver: (targetId: number, receiverId: number) => void;
		onloadBotChats: (botId: number) => void;
		onchangeReceiverForm: (form: Record<string, any>) => void;
		ontoggleBroadcastChild?: (targetId: number, childId: number) => void;
	}

	let {
		target,
		typeIcons,
		addingReceiverForTarget,
		receiverForm = $bindable(),
		receiverSubmitting,
		receiverHeadersError,
		receiverBotChats,
		receiverTesting,
		receiverLabel,
		onopenReceiverForm,
		onsaveReceiver,
		oncancelReceiver,
		ontoggleReceiver,
		onremoveReceiver,
		ontestReceiver,
		onloadBotChats,
		onchangeReceiverForm,
		ontoggleBroadcastChild,
	}: Props = $props();
</script>

<div class="mt-3 pt-3 border-t border-[var(--color-border)]">
{#if target.type === 'broadcast'}
	<div class="flex items-center justify-between mb-2">
		<p class="text-xs font-medium text-[var(--color-muted-foreground)] uppercase tracking-wide">{t('targets.childTargets')}</p>
	</div>
	{@const disabledIds = new Set(target.config?.disabled_child_ids || [])}
	{#if target.child_targets?.length}
		{#each target.child_targets as child (child.id)}
			{@const isDisabled = disabledIds.has(child.id)}
			<div class="flex items-center justify-between py-1.5 px-2 rounded-md hover:bg-[var(--color-muted)]" class:opacity-50={isDisabled}>
				<div class="flex items-center gap-2">
					<MdiIcon name={child.icon || typeIcons[child.type] || 'mdiTarget'} size={14} />
					<span class="text-sm">{child.name}</span>
					<span class="text-xs px-1 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{child.type}</span>
				</div>
				<IconButton
					icon={isDisabled ? 'mdiToggleSwitchOff' : 'mdiToggleSwitch'}
					title={isDisabled ? t('common.enable') : t('common.disable')}
					onclick={() => ontoggleBroadcastChild?.(target.id, child.id)}
					size={16}
				/>
			</div>
		{/each}
	{:else}
		<p class="text-xs text-[var(--color-muted-foreground)] italic">{t('targets.noChildTargets')}</p>
	{/if}
{:else}
	<div class="flex items-center justify-between mb-2">
		<p class="text-xs font-medium text-[var(--color-muted-foreground)] uppercase tracking-wide">{t('targets.receivers')}</p>
	</div>

	{#if (target.receivers || []).length === 0 && addingReceiverForTarget !== target.id}
		<p class="text-xs text-[var(--color-muted-foreground)] italic mb-2">{t('targets.noReceivers')}</p>
	{/if}

	{#each target.receivers || [] as recv (recv.id)}
		<div class="flex items-center justify-between py-1.5 px-2 rounded-md hover:bg-[var(--color-muted)]" class:opacity-50={!recv.enabled}>
			<div class="flex items-center gap-2 min-w-0">
				<MdiIcon name={typeIcons[target.type] || 'mdiTarget'} size={14} />
				<span class="text-sm truncate">{receiverLabel(target, recv)}</span>
				{#if (recv as any).language_code || recv.config?.language_code}
					<span class="text-xs px-1 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{((recv as any).language_code || recv.config.language_code).toUpperCase()}</span>
				{/if}
			</div>
			<div class="flex items-center gap-1">
				<IconButton icon="mdiSend" title={t('targets.test')}
					onclick={() => ontestReceiver(target.id, recv.id)}
					disabled={receiverTesting[recv.id]} size={16} />
				<IconButton
					icon={recv.enabled ? 'mdiToggleSwitch' : 'mdiToggleSwitchOff'}
					title={recv.enabled ? t('targets.receiverDisabled') : t('targets.receiverEnabled')}
					onclick={() => ontoggleReceiver(target.id, recv)}
					size={16}
				/>
				<IconButton
					icon="mdiDelete"
					title={t('common.delete')}
					onclick={() => onremoveReceiver(target.id, recv)}
					variant="danger"
					size={16}
				/>
			</div>
		</div>
	{/each}

	<!-- Telegram: chat picker palette opens directly from the "Add receiver" button — no inline section. -->
	{#if target.type === 'telegram'}
		{@const botId = target.config?.bot_id}
		{@const existingKeys = new Set((target.receivers || []).map((r: TargetReceiver) => r.receiver_key))}
		{@const chatItems = (receiverBotChats[botId] || []).map((c: any) => ({
			value: c.chat_id,
			label: c.title || c.username || c.chat_id,
			icon: c.type === 'private' ? 'mdiAccount' : c.type === 'channel' ? 'mdiBullhorn' : 'mdiAccountGroup',
			desc: `${c.type}${c.language_code ? ' · ' + c.language_code.toUpperCase() : ''} · ${c.chat_id}`,
			disabled: existingKeys.has(c.chat_id),
			disabledHint: existingKeys.has(c.chat_id) ? t('targets.alreadyAdded') : undefined,
		}))}
		{#if addingReceiverForTarget === target.id}
			<EntitySelect
				items={chatItems}
				bind:value={receiverForm.chat_id}
				open={true}
				showTrigger={false}
				placeholder={t('telegramBot.selectChat')}
				onselect={(v) => { if (v != null && v !== '') onsaveReceiver(target.id); }}
				onclose={oncancelReceiver}
			/>
		{/if}
		<button type="button" onclick={() => onopenReceiverForm(target.id, target.type)}
			class="mt-1 flex items-center gap-1 text-xs text-[var(--color-primary)] hover:underline cursor-pointer">
			<MdiIcon name="mdiPlus" size={14} />
			{t('targets.addReceiver')}
		</button>
	{:else if addingReceiverForTarget === target.id}
		<div in:slide={{ duration: 150 }} class="mt-2 p-2 rounded-md border border-[var(--color-border)] bg-[var(--color-background)]">
			{#if target.type === 'email'}
				<input bind:value={receiverForm.email} type="email" placeholder="recipient@example.com"
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			{:else if target.type === 'webhook'}
				<input bind:value={receiverForm.url} placeholder="https://..."
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] mb-2" />
				<input bind:value={receiverForm.headers} placeholder={'{"Authorization": "Bearer ..."}'}
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]"
					style={receiverHeadersError ? 'border-color: var(--color-error-fg)' : ''} />
				{#if receiverHeadersError}<p class="text-xs text-[var(--color-error-fg)] mt-1">{receiverHeadersError}</p>{/if}
			{:else if target.type === 'discord' || target.type === 'slack'}
				<input bind:value={receiverForm.webhook_url}
					placeholder={target.type === 'discord' ? 'https://discord.com/api/webhooks/...' : 'https://hooks.slack.com/services/...'}
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			{:else if target.type === 'ntfy'}
				<input bind:value={receiverForm.topic} placeholder="my-notifications"
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			{:else if target.type === 'matrix'}
				<input bind:value={receiverForm.room_id} placeholder="!abc123:matrix.org"
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
			{/if}

			<div class="flex gap-2 mt-2">
				<button type="button" onclick={() => onsaveReceiver(target.id)} disabled={receiverSubmitting}
					class="px-3 py-1 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-xs font-medium hover:opacity-90 disabled:opacity-50">
					{receiverSubmitting ? t('common.loading') : t('common.save')}
				</button>
				<button type="button" onclick={oncancelReceiver}
					class="px-3 py-1 border border-[var(--color-border)] rounded-md text-xs hover:bg-[var(--color-muted)]">
					{t('targets.cancel')}
				</button>
			</div>
		</div>
	{:else}
		<button type="button" onclick={() => onopenReceiverForm(target.id, target.type)}
			class="mt-1 flex items-center gap-1 text-xs text-[var(--color-primary)] hover:underline cursor-pointer">
			<MdiIcon name="mdiPlus" size={14} />
			{t('targets.addReceiver')}
		</button>
	{/if}
{/if}
</div>
