import { beforeNavigate, goto } from '$app/navigation';

export function createUnsavedWarning() {
	let isDirty = $state(false);
	let showUnsavedWarning = $state(false);
	let discardTarget: string | null = $state(null);

	beforeNavigate(({ cancel, to }) => {
		if (isDirty) {
			cancel();
			showUnsavedWarning = true;
			discardTarget = to?.url.href ?? null;
		}
	});

	function markDirty() {
		isDirty = true;
		showUnsavedWarning = false;
	}

	function discard() {
		isDirty = false;
		showUnsavedWarning = false;
		if (discardTarget) goto(discardTarget);
	}

	function clearOnSuccess() {
		isDirty = false;
		showUnsavedWarning = false;
	}

	return {
		get isDirty() {
			return isDirty;
		},
		get showUnsavedWarning() {
			return showUnsavedWarning;
		},
		get discardTarget() {
			return discardTarget;
		},
		markDirty,
		discard,
		clearOnSuccess
	};
}
