/**
 * Graph state management — core atoms
 *
 * Foundation atoms for the Graphology + Jotai graph system.
 * Position, derived, and mutation atoms live in their own modules.
 *
 * @see ./graph-position.ts  — position atoms
 * @see ./graph-derived.ts   — read-only UI derivation atoms
 * @see ./graph-mutations.ts — write atoms (CRUD, split/merge, DB sync)
 */

import { atom } from 'jotai';
import Graph from 'graphology';
import type {
	GraphNodeAttributes,
	GraphEdgeAttributes,
	EdgeCreationState,
} from './types';

// --- Graph Configuration ---

export const graphOptions = {
	type: 'directed' as const,
	multi: true,
	allowSelfLoops: true,
};

// --- Core Graph Atoms ---

/**
 * Currently active graph ID
 */
export const currentGraphIdAtom = atom<string | null>(null);

/**
 * Main graph instance
 */
export const graphAtom = atom<Graph<GraphNodeAttributes, GraphEdgeAttributes>>(
	new Graph<GraphNodeAttributes, GraphEdgeAttributes>(graphOptions),
);

/**
 * Version counter to trigger re-renders
 */
export const graphUpdateVersionAtom = atom(0);

// --- Edge Creation State ---

export const edgeCreationAtom = atom<EdgeCreationState>({
	isCreating: false,
	sourceNodeId: null,
	sourceNodePosition: null,
	targetPosition: null,
	hoveredTargetNodeId: null,
	sourceHandle: null,
	targetHandle: null,
	sourcePort: null,
	targetPort: null,
	snappedTargetPosition: null,
});

// --- Drag State ---

export const draggingNodeIdAtom = atom<string | null>(null);
export const preDragNodeAttributesAtom = atom<GraphNodeAttributes | null>(null);
