// #region DatasetReviewSessionStore [C:4] [TYPE Store] [SEMANTICS dataset, review, session, store, state]
// @BRIEF Manage active dataset review session state including loading, local edits, error capture, and reset semantics.
// @LAYER UI
// @RELATION DEPENDS_ON -> [ApiModule]
// @PRE Consumers provide session-shaped payloads and initialize the store before reading derived session fields.
// @POST Store transitions keep session, loading, error, and dirty flags internally consistent after each helper call.
// @SIDE_EFFECT Mutates the writable dataset review session store in frontend memory.
// @UX_STATE Loading -> Session detail is being fetched
// @UX_STATE Ready -> Session detail available for UI binding
// @UX_STATE Saving -> Updates are being persisted
// @UX_STATE Error -> Failed to load or update session
// @DATA_CONTRACT Input[SessionDetail | Partial<SessionDetail> | boolean | string | null] -> Output[DatasetReviewSessionStoreState]
// @RATIONALE Migrated from Svelte 4 writable to Svelte 5 $state runes.
//            Backward-compatible .subscribe() retained for $datasetReviewSessionStore syntax.

export type UiPhase = 'empty' | 'importing' | 'review' | 'partial_preview' | 'launch_blocked' | 'run_ready' | 'run_in_progress';

interface DatasetReviewSessionState {
	session: Record<string, unknown> | null;
	isLoading: boolean;
	isSaving: boolean;
	error: string | null;
	lastUpdated: Date | null;
	isDirty: boolean;
}

const initialState: DatasetReviewSessionState = {
	session: null,
	isLoading: false,
	isSaving: false,
	error: null,
	lastUpdated: null,
	isDirty: false,
};

// Reactive state (Svelte 5 rune)
let _state: DatasetReviewSessionState = $state(initialState);

// Subscriber list for backward compat with $datasetReviewSessionStore syntax
let _subscribers: Array<(value: DatasetReviewSessionState) => void> = [];

function _notify(): void {
	const current = _state;
	_subscribers.forEach((fn) => fn(current));
}

export const datasetReviewSessionStore = {
	subscribe(run: (value: DatasetReviewSessionState) => void): () => void {
		_subscribers.push(run);
		run(_state);
		return () => {
			_subscribers = _subscribers.filter((fn) => fn !== run);
		};
	},
	get value(): DatasetReviewSessionState {
		return _state;
	},
};

export function setSession(session: Record<string, unknown>): void {
	_state = {
		..._state,
		session,
		isLoading: false,
		error: null,
		lastUpdated: new Date(),
		isDirty: false,
	};
	_notify();
}

export function setLoading(isLoading: boolean): void {
	if (_state.isLoading === isLoading) return;
	_state = { ..._state, isLoading };
	_notify();
}

export function setError(error: string | null): void {
	if (_state.error === error && !_state.isLoading && !_state.isSaving) return;
	_state = { ..._state, error, isLoading: false, isSaving: false };
	_notify();
}

export function setDirty(isDirty: boolean): void {
	if (_state.isDirty === isDirty) return;
	_state = { ..._state, isDirty };
	_notify();
}

export function resetSession(): void {
	_state = { ...initialState };
	_notify();
}

export function patchSession(patch: Record<string, unknown>): void {
	if (!_state.session) return;
	_state = {
		..._state,
		session: { ..._state.session, ...patch },
		isDirty: true,
	};
	_notify();
}

export function getSessionUiPhase(session: Record<string, unknown> | null): UiPhase {
	if (!session) return 'empty';

	const readiness = String(session.readiness_state || '');
	if (readiness === 'importing') return 'importing';
	if (readiness === 'partially_ready' || readiness === 'compiled_preview_ready') return 'partial_preview';
	if (readiness === 'recovery_required') return 'launch_blocked';
	if (readiness === 'run_ready') return 'run_ready';
	if (readiness === 'run_in_progress') return 'run_in_progress';
	return 'review';
}
// #endregion DatasetReviewSessionStore
