<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import Button from "$lib/components/ui/Button.svelte";
	import Input, { inputField } from "$lib/components/ui/Input.svelte";
	import Toggle from "$lib/components/ui/Toggle.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 Check from "$icon/check";
	import X from "$icon/x";

	const SUFFIX = ".tngl.sh";

	let ownDomain = $state(false);
	let handle = $state("");

	const valid = $derived(handle.trim().length > 0);

	// mocked — a real handle change needs an OAuth re-auth round trip
	const submit = () => goto(resolve("/settings"));
</script>

<DrillDown backLabel="Profile" backHref="/settings" title="Change handle">
	<SettingsList padding="tight">
		<FormRow label="I have my own domain">
			<div class="flex sm:justify-end">
				<Toggle bind:checked={ownDomain} aria-label="I have my own domain" />
			</div>
		</FormRow>
		<FormRow label="Handle" for="handle">
			{#if ownDomain}
				<Input id="handle" bind:value={handle} placeholder="example.com" />
			{:else}
				<!-- the subdomain suffix lives inside the field, so borrow Input's own
				     surface styling rather than re-deriving it -->
				<div class={inputField({ class: "gap-0 overflow-hidden py-0 pr-0" })}>
					<input
						id="handle"
						bind:value={handle}
						placeholder="handle"
						class="min-w-0 flex-1 bg-transparent py-1 typography-paragraph-regular outline-none placeholder:text-foreground-placeholder"
					/>
					<span
						class="self-stretch border-l border-border-default bg-background-muted px-2 py-1 typography-paragraph-regular text-foreground-muted"
					>
						{SUFFIX}
					</span>
				</div>
			{/if}
		</FormRow>
	</SettingsList>

	<FormActions>
		<Button href="/settings" icon={X}>Cancel</Button>
		<Button variant="primary" icon={Check} disabled={!valid} onclick={submit}>Save</Button>
	</FormActions>
</DrillDown>
