"use client";

const ACTIVE_SESSION_ID_KEY = "claw.activeSessionId";
export const ACTIVE_SESSION_CHANGED_EVENT = "claw-active-session-changed";
export const PENDING_WORKSPACE_SESSION_CHANGED_EVENT =
	"claw-pending-workspace-session-changed";

declare global {
	interface Window {
		__clawPendingWorkspaceSessionId?: string | null;
	}
}

export function readActiveSessionId() {
	if (typeof window === "undefined") return null;
	return (
		normalizeSessionId(window.sessionStorage.getItem(ACTIVE_SESSION_ID_KEY)) ??
		normalizeSessionId(window.localStorage.getItem(ACTIVE_SESSION_ID_KEY))
	);
}

export function writeActiveSessionId(sessionId: string | null | undefined) {
	if (typeof window === "undefined") return;
	const normalized = normalizeSessionId(sessionId);
	if (!normalized) {
		clearActiveSessionId();
		return;
	}
	window.sessionStorage.setItem(ACTIVE_SESSION_ID_KEY, normalized);
	window.localStorage.setItem(ACTIVE_SESSION_ID_KEY, normalized);
	const pendingSessionId = readPendingWorkspaceSessionId();
	if (pendingSessionId && pendingSessionId !== normalized) {
		clearPendingWorkspaceSessionId();
	}
	window.dispatchEvent(
		new CustomEvent(ACTIVE_SESSION_CHANGED_EVENT, {
			detail: { sessionId: normalized },
		}),
	);
}

export function clearActiveSessionId() {
	if (typeof window === "undefined") return;
	window.sessionStorage.removeItem(ACTIVE_SESSION_ID_KEY);
	window.localStorage.removeItem(ACTIVE_SESSION_ID_KEY);
	clearPendingWorkspaceSessionId();
	window.dispatchEvent(
		new CustomEvent(ACTIVE_SESSION_CHANGED_EVENT, {
			detail: { sessionId: null },
		}),
	);
}

export function writePendingWorkspaceSessionId(
	sessionId: string | null | undefined,
) {
	if (typeof window === "undefined") return;
	const normalized = normalizeSessionId(sessionId);
	if (!normalized) {
		clearPendingWorkspaceSessionId();
		return;
	}
	window.__clawPendingWorkspaceSessionId = normalized;
	window.dispatchEvent(
		new CustomEvent(PENDING_WORKSPACE_SESSION_CHANGED_EVENT, {
			detail: { sessionId: normalized },
		}),
	);
}

export function readPendingWorkspaceSessionId() {
	if (typeof window === "undefined") return null;
	return normalizeSessionId(window.__clawPendingWorkspaceSessionId);
}

export function clearPendingWorkspaceSessionId() {
	if (typeof window === "undefined") return;
	window.__clawPendingWorkspaceSessionId = null;
	window.dispatchEvent(
		new CustomEvent(PENDING_WORKSPACE_SESSION_CHANGED_EVENT, {
			detail: { sessionId: null },
		}),
	);
}

function normalizeSessionId(value: unknown) {
	if (typeof value !== "string") return null;
	const trimmed = value.trim();
	return trimmed || null;
}
