"use client";

import {
	createContext,
	type MutableRefObject,
	type ReactNode,
	useContext,
} from "react";

export interface EditorContextValue {
	// Content state
	content: string;
	onChange: (content: string) => void;
	path: string;

	// Status
	isDirty: boolean;
	isSaving: boolean;

	// Actions
	onSave?: () => void;
	onClose?: () => void;

	// Editor ref for jump-to-line functionality
	editorRef: MutableRefObject<EditorHandle | null>;

	// Recovery state (for autosave restore)
	recovery?: {
		timestamp: number;
		onRestore: () => void;
		onDismiss: () => void;
	};
}

// Handle exposed by EditorPane for external control
export interface EditorHandle {
	jumpToLine: (line: number) => void;
}

const EditorContext = createContext<EditorContextValue | null>(null);

export function useEditorContext() {
	const context = useContext(EditorContext);
	if (!context) {
		throw new Error("useEditorContext must be used within an EditorProvider");
	}
	return context;
}

// Optional hook that doesn't throw - useful for components that can work with or without context
export function useEditorContextOptional() {
	return useContext(EditorContext);
}

interface EditorProviderProps {
	children: ReactNode;
	value: EditorContextValue;
}

export function EditorProvider({ children, value }: EditorProviderProps) {
	return (
		<EditorContext.Provider value={value}>{children}</EditorContext.Provider>
	);
}
