<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/state';
	import { api , errMsg} from '$lib/api';
	import { t } from '$lib/i18n';
	import { telegramBotsCache, emailBotsCache, matrixBotsCache } from '$lib/stores/caches.svelte';
	import Loading from '$lib/components/Loading.svelte';
	import { snackError } from '$lib/stores/snackbar.svelte';
	import { highlightFromUrl } from '$lib/highlight';
	import TelegramBotTab from './TelegramBotTab.svelte';
	import EmailBotTab from './EmailBotTab.svelte';
	import MatrixBotTab from './MatrixBotTab.svelte';

	type BotTab = 'telegram' | 'email' | 'matrix';
	let activeTab = $derived((page.url.searchParams.get('tab') as BotTab | null) || 'telegram');

	let loaded = $state(false);
	let error = $state('');

	// Global settings (loaded for webhook mode checks)
	let settings = $state<Record<string, string>>({});

	onMount(load);
	async function load() {
		try {
			[, settings] = await Promise.all([
				telegramBotsCache.fetch(true),
				api('/settings'),
				emailBotsCache.fetch(true),
				matrixBotsCache.fetch(true),
			]);
		} catch (err: unknown) { error = errMsg(err, t('common.loadError')); snackError(error); }
		finally { loaded = true; highlightFromUrl(); }
	}
</script>

{#if !loaded}<Loading />{:else}

{#if activeTab === 'telegram'}
	<TelegramBotTab {settings} onreload={load} />
{/if}

{#if activeTab === 'email'}
	<EmailBotTab onreload={load} />
{/if}

{#if activeTab === 'matrix'}
	<MatrixBotTab onreload={load} />
{/if}

{/if}
