<script lang="ts">
	import { onMount } from "svelte";
	import SidebarHeader from "./SidebarHeader.svelte";
	import {
		drawRoute,
		removeAllRoutes,
		startRoute,
	} from "$lib/services/navigation/routing.svelte";
	import { Button } from "$lib/components/ui/button";
	import { RouteIcon, SaveIcon, SendIcon } from "@lucide/svelte";
	import { map } from "../map.svelte";
	import { m } from "$lang/messages";
	import RequiresCapability from "../RequiresCapability.svelte";
	import { hasStore, updateStore } from "$lib/services/stores.svelte";

	const {
		route,
	}: {
		route: Trip;
	} = $props();

	onMount(async () => {
		removeAllRoutes();
		drawRoute(route);

		if (route) {
			isSaved = await hasStore({
				name: route.locations.map((l) => l.lat + "-" + l.lon).join(";"),
				type: "route",
			});
		}
	});

	let isSaved = $state(false);
</script>

<SidebarHeader
	onback={() => {
		removeAllRoutes();
	}}
>
	{m["sidebar.trip.header"]()}
</SidebarHeader>

<div id="actions" class="flex gap-2">
	<Button
		onclick={async () => {
			await startRoute(route);
			requestAnimationFrame(() => {
				map.updateMapPadding();
			});
		}}
	>
		<RouteIcon />
		{m["sidebar.trip.start"]()}
	</Button>
	<RequiresCapability capability="stores">
		<Button
			variant="secondary"
			onclick={async () => {
				if (isSaved) {
					await updateStore(
						{
							name: route.locations.map((l) => l.lat + "-" + l.lon).join(";"),
							type: "route",
						},
						null,
					);
					isSaved = false;
					// view.back();
				} else {
					const name = prompt("Trip name?");
					if (!name) return;
					await updateStore(
						{
							name: route.locations.map((l) => l.lat + "-" + l.lon).join(";"),
							type: "route",
						},
						{
							...route,
							name,
						},
					);
					isSaved = true;
				}
			}}
		>
			<SaveIcon />
			{isSaved ? m.unsave() : m["sidebar.trip.save"]()}
		</Button>
	</RequiresCapability>
	<Button variant="secondary" disabled>
		<SendIcon />
		{m["sidebar.trip.send"]()}
	</Button>
</div>

<div class="flex flex-col gap-2 mt-2">
	{#each route.legs[0].maneuvers as maneuver (maneuver)}
		<li>
			{maneuver.instruction}
		</li>
	{/each}
</div>
