/**
 * Locked Node Store
 *
 * Manages "locking" onto a node for detailed viewing/editing.
 * Triple-click on a node locks it, showing additional panels/pages.
 */

import { atom } from 'jotai';
import type { NodeId } from './types';
import { uiNodesAtom } from './graph-derived';

// =============================================================================
// Locked Node Atoms
// =============================================================================

/**
 * Currently locked node ID (null = no node locked).
 */
export const lockedNodeIdAtom = atom<NodeId | null>(null);

/**
 * Full node data for the locked node.
 */
export const lockedNodeDataAtom = atom((get) => {
	const id = get(lockedNodeIdAtom);
	if (!id) return null;
	const nodes = get(uiNodesAtom);
	return nodes.find((n) => n.id === id) || null;
});

/**
 * Current page index for locked node (0-based).
 */
export const lockedNodePageIndexAtom = atom(0);

/**
 * Total number of pages available (set by app).
 */
export const lockedNodePageCountAtom = atom(1);

// =============================================================================
// Action Atoms
// =============================================================================

/**
 * Lock onto a node (typically triggered by triple-click).
 * @param nodeId - The node ID to lock onto
 * @param nodeData - Optional node data (for app compatibility, not used internally)
 */
export const lockNodeAtom = atom(null, (_get, set, payload: { nodeId: NodeId; nodeData?: unknown }) => {
	set(lockedNodeIdAtom, payload.nodeId);
	set(lockedNodePageIndexAtom, 0); // Reset to first page
});

/**
 * Unlock the currently locked node.
 */
export const unlockNodeAtom = atom(null, (_get, set) => {
	set(lockedNodeIdAtom, null);
});

/**
 * Navigate to next page in locked node view.
 */
export const nextLockedPageAtom = atom(null, (get, set) => {
	const current = get(lockedNodePageIndexAtom);
	const pageCount = get(lockedNodePageCountAtom);
	set(lockedNodePageIndexAtom, (current + 1) % pageCount);
});

/**
 * Navigate to previous page in locked node view.
 */
export const prevLockedPageAtom = atom(null, (get, set) => {
	const current = get(lockedNodePageIndexAtom);
	const pageCount = get(lockedNodePageCountAtom);
	set(lockedNodePageIndexAtom, (current - 1 + pageCount) % pageCount);
});

/**
 * Go to specific page by index.
 */
export const goToLockedPageAtom = atom(null, (get, set, index: number) => {
	const pageCount = get(lockedNodePageCountAtom);
	if (index >= 0 && index < pageCount) {
		set(lockedNodePageIndexAtom, index);
	}
});

// =============================================================================
// Derived Atoms
// =============================================================================

/**
 * Whether a node is currently locked.
 */
export const hasLockedNodeAtom = atom((get) => get(lockedNodeIdAtom) !== null);
