<script lang="ts">
	import { adbReconnect } from '$lib/core/stores/adbReconnectStore';
	import * as adb from '$lib/core/adb/adb';
	import Button from '$lib/components/ui/button/button.svelte';
	import { addNotification } from '$lib/core/stores/noti';
	import { page } from '$app/stores';

	let pending = $derived($adbReconnect);

	/**
	 * Determine which Android server channel to reconnect based on
	 * the current route — same logic as the authed layout's
	 * getAutoConnectChannel().
	 */
	function getReconnectChannel(pathname: string): 'brew' | 'recipe' | 'adb' {
		if (pathname.startsWith('/tools/create-menu')) return 'recipe';
		if (pathname.startsWith('/tools/brew')) return 'brew';
		return 'adb';
	}

	async function handleConfirm() {
		try {
			const channel = getReconnectChannel($page.url.pathname);
			if (channel === 'recipe') {
				await adb.reconnectAndroidRecipeMenuServer();
			} else {
				await adb.reconnectAndroidServer();
			}
			adbReconnect.confirmReconnect();
			addNotification('INFO:Android socket reconnected');
		} catch (e) {
			addNotification('ERR:Failed to reconnect Android socket');
			// Keep the banner visible so the user can retry
		}
	}

	function handleDismiss() {
		adbReconnect.dismissReconnect();
	}
</script>

{#if pending}
	<div
		class="fixed bottom-0 left-0 right-0 z-50 border-t border-amber-500/30 bg-amber-950/95 px-4 py-3 backdrop-blur-sm"
		role="alert"
	>
		<div class="flex items-center justify-between gap-4">
			<div class="flex items-center gap-3">
				<div class="h-2.5 w-2.5 shrink-0 animate-pulse rounded-full bg-amber-400"></div>
				<div>
					<p class="text-sm font-medium text-amber-100">
						{pending.reason}
					</p>
					<p class="text-xs text-amber-300/70">
						Press Reconnect to restore the connection.
					</p>
				</div>
			</div>
			<div class="flex shrink-0 gap-2">
				<Button variant="outline" size="sm" onclick={handleDismiss} class="border-amber-600/50 text-amber-200 hover:bg-amber-800/50">
					Dismiss
				</Button>
				<Button size="sm" onclick={handleConfirm} class="bg-amber-600 hover:bg-amber-500">
					Reconnect
				</Button>
			</div>
		</div>
	</div>
{/if}
