"use client";
import { useEffect, useRef, useState } from "react";
import { createElkLayoutEngine } from "./elk-layout-engine.js";
/**
 * Behavior hook (DD-003 layer 2) that asynchronously creates an ELK layout
 * engine and manages its lifecycle.
 *
 * Returns the engine once ready, or `null` while loading / if `elkjs` is
 * not installed. The caller can pass the return value directly to
 * `WorkflowCanvasEditor`'s `layoutEngine` prop — `null` is safe and causes
 * the canvas to use the default dagre engine.
 *
 * The engine (and its Web Worker, if any) is terminated on unmount.
 *
 * @example
 * ```tsx
 * const workerFactory = () =>
 *   new Worker(new URL("elkjs/lib/elk-worker.min.js", import.meta.url));
 *
 * function MyEditor({ yaml }: { yaml: string }) {
 *   const elkEngine = useElkLayoutEngine({ workerFactory });
 *   return <WorkflowCanvasEditor yaml={yaml} layoutEngine={elkEngine} />;
 * }
 * ```
 */
export function useElkLayoutEngine(options) {
    const [engine, setEngine] = useState(null);
    const engineRef = useRef(null);
    const optionsRef = useRef(options);
    optionsRef.current = options;
    const enabled = options?.enabled !== false;
    useEffect(() => {
        if (!enabled) {
            return;
        }
        let cancelled = false;
        const opts = {};
        if (optionsRef.current?.workerFactory) {
            opts.workerFactory = optionsRef.current.workerFactory;
        }
        if (optionsRef.current?.layoutOptions) {
            opts.layoutOptions = optionsRef.current.layoutOptions;
        }
        createElkLayoutEngine(opts).then((created) => {
            if (cancelled) {
                created.terminate?.();
                return;
            }
            engineRef.current = created;
            setEngine(created);
        }, () => {
            // elkjs not installed or import failed — return null,
            // callers fall back to dagre via useWorkflowLayout.
        });
        return () => {
            cancelled = true;
            engineRef.current?.terminate?.();
            engineRef.current = null;
            setEngine(null);
        };
    }, [enabled]);
    return engine;
}
//# sourceMappingURL=useElkLayoutEngine.js.map