<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import Button from "$lib/components/ui/Button.svelte";
	import Input from "$lib/components/ui/Input.svelte";
	import DrillDown from "$lib/components/settings/DrillDown.svelte";
	import SettingsList from "$lib/components/settings/SettingsList.svelte";
	import FormRow from "$lib/components/settings/FormRow.svelte";
	import FormActions from "$lib/components/settings/FormActions.svelte";
	import Copy from "$icon/copy";
	import CopyCheck from "$icon/copy-check";
	import Plus from "$icon/plus";
	import X from "$icon/x";

	let { data } = $props();

	const back = $derived(`/${data.repo.ownerHandle}/${data.repo.name}/settings`);
	const did = $derived(data.repo.ownerDid);

	// the point of the screen: these survive a rename, the handle-based ones don't
	const stableUrls = $derived([`https://tangled.org/${did}`, `git@tangled.org:${did}`]);

	let copied = $state<string | null>(null);
	const copy = async (url: string) => {
		await navigator.clipboard.writeText(url);
		copied = url;
		setTimeout(() => (copied === url ? (copied = null) : null), 1500);
	};

	let name = $state("");
	const valid = $derived(name.trim().length > 0 && name.trim() !== data.repo.name);

	// mocked — renaming is not wired up yet
	const submit = () => goto(resolve(back as "/"));
</script>

<DrillDown
	backLabel="General"
	backHref={back}
	title="Rename repository"
	description={[
		"Existing git remotes that use the old name will break.",
		"Use the stable, DID-based URLs below to avoid breakage on future renames."
	]}
>
	<div class="flex w-full flex-col gap-1">
		{#each stableUrls as url (url)}
			<div class="flex items-center gap-2">
				<code class="font-mono typography-monospace-regular break-all text-foreground-default">
					{url}
				</code>
				<button
					type="button"
					onclick={() => copy(url)}
					aria-label="Copy {url}"
					class="cursor-pointer text-foreground-muted hover:text-foreground-default"
				>
					{#if copied === url}
						<CopyCheck class="size-3.5" aria-hidden="true" />
					{:else}
						<Copy class="size-3.5" aria-hidden="true" />
					{/if}
				</button>
			</div>
		{/each}
	</div>

	<SettingsList padding="tight">
		<FormRow label="Name" for="repo-name">
			<Input id="repo-name" bind:value={name} placeholder="great-project" />
		</FormRow>
	</SettingsList>

	<FormActions>
		<Button href={resolve(back as "/")} icon={X}>Cancel</Button>
		<Button variant="primary" icon={Plus} disabled={!valid} onclick={submit}>Add</Button>
	</FormActions>
</DrillDown>
