import { isValidBranchParam } from "@/lib/frontend/params";
import { branchPath } from "@/lib/frontend/routes";
import {
	parseSearchUrlState,
	serializeSearchUrlState,
	SEARCH_SCOPE,
} from "@/lib/frontend/search/urlState";

export function readRouteBranchFromPathname(pathname) {
	if (typeof pathname !== "string" || !pathname.startsWith("/")) return null;

	const seg = pathname.split("/").filter(Boolean)[0] || null;
	return seg && isValidBranchParam(seg) ? seg : null;
}

export function isSearchRoutePathname(pathname) {
	if (typeof pathname !== "string" || !pathname.startsWith("/")) return false;

	const parts = pathname.split("/").filter(Boolean);
	return parts.length >= 2 && parts[1] === "search";
}

export function replaceBranchInPathnameOrFallback(pathname, nextBranch) {
	const current = readRouteBranchFromPathname(pathname);
	if (!current) return branchPath(nextBranch);

	const parts = pathname.split("/").filter(Boolean);
	if (parts.length === 0) return branchPath(nextBranch);

	parts[0] = nextBranch;
	return `/${parts.join("/")}`;
}

export function buildNextSearchQueryString({
	currentSearch,
	currentRouteBranch,
	nextBranch,
}) {
	const sp = new URLSearchParams(currentSearch || "");
	const parsed = parseSearchUrlState(sp, { routeBranch: currentRouteBranch });

	const nextState =
		parsed.scope === SEARCH_SCOPE.SINGLE
			? { ...parsed, branch: nextBranch }
			: parsed;

	const qs = serializeSearchUrlState(nextState);
	return qs ? `?${qs}` : "";
}

export function buildNextUrlForBranchSwitch({ pathname, search, nextBranch }) {
	if (!isValidBranchParam(nextBranch)) return null;

	const currentRouteBranch = readRouteBranchFromPathname(pathname);

	// Outside a branch route -> go to branch root
	if (!currentRouteBranch) return branchPath(nextBranch);

	const nextPathname = replaceBranchInPathnameOrFallback(pathname, nextBranch);

	const nextSearch = isSearchRoutePathname(pathname)
		? buildNextSearchQueryString({
				currentSearch: search,
				currentRouteBranch,
				nextBranch,
		  })
		: search || "";

	return `${nextPathname}${nextSearch}`;
}

export function safeReadLocalStorageBranch(storageKey) {
	if (typeof window === "undefined") return null;

	try {
		const raw = window.localStorage.getItem(String(storageKey || ""));
		return raw && isValidBranchParam(raw) ? raw : null;
	} catch {
		return null;
	}
}

export function safeWriteLocalStorageBranch(storageKey, branch) {
	if (typeof window === "undefined") return;

	try {
		window.localStorage.setItem(String(storageKey || ""), String(branch));
	} catch {
		// ignore
	}
}
