<script lang="ts">
	import { Download, RefreshCcw } from '@lucide/svelte';
	import { Panel, useSvelteFlow } from '@xyflow/svelte';

	import { Button } from '$lib/components/ui/button';
	import { breakpointsState } from '$lib/state/breakpoints.svelte';
	import { mapNodesExport } from '$lib/helpers/map-nodes-export';
	import * as Tooltip from '$lib/components/ui/tooltip';

	const { getNodes, getEdges } = useSvelteFlow();
	let showPanelFlowActions = $derived(getNodes().length > 1);

	function handleReset() {
		const ok = confirm('Are you sure you want to reset the flow?');
		if (ok) {
			location.reload();
		}
	}

	function handleExport() {
		const ok = confirm('Are you sure you want to export the flow?');
		if (ok) {
			const exported = mapNodesExport(getNodes(), getEdges());
			const blob = new Blob([JSON.stringify(exported, null, 2)], { type: 'application/json' });
			const url = URL.createObjectURL(blob);
			window.open(url, '_blank');
		}
	}
</script>

{#if showPanelFlowActions}
	<Panel
		position={breakpointsState.isMobile ? 'bottom-left' : 'top-left'}
		class="flex items-center justify-end gap-2 p-1 lg:p-2"
	>
		<Tooltip.Root delayDuration={0}>
			<Tooltip.Trigger>
				<Button
					variant="outline"
					size={breakpointsState.isMobile ? 'icon-sm' : 'icon-lg'}
					class=""
					onclick={handleReset}
					title="Reset flow"
				>
					<RefreshCcw class={breakpointsState.isMobile ? 'size-4' : 'size-[18px]'} />
				</Button>
			</Tooltip.Trigger>
			<Tooltip.Content>Reset the flow</Tooltip.Content>
		</Tooltip.Root>
		<Tooltip.Root delayDuration={0}>
			<Tooltip.Trigger>
				<Button
					variant="outline"
					size={breakpointsState.isMobile ? 'icon-sm' : 'icon-lg'}
					class=""
					title="Export flow"
					onclick={handleExport}
				>
					<Download class={breakpointsState.isMobile ? 'size-4' : 'size-5'} />
				</Button>
			</Tooltip.Trigger>
			<Tooltip.Content>Export the flow as JSON file</Tooltip.Content>
		</Tooltip.Root>
	</Panel>
{/if}
