"use client";
import { useCallback, useMemo, useRef, useState } from "react";
/**
 * Identity of a plan for draft scoping: the execution that published it plus
 * the artifact's content hash. A refined plan (new execution) or a republished
 * plan (same key, new hash) produces a NEW identity, which orphans any draft
 * of the previous plan — a draft of plan N must never silently ride along
 * once plan N+1 exists.
 */
export function planDraftKey(plan) {
    return `${plan.executionId}:${plan.artifact.contentHash}`;
}
/**
 * Owns the local draft of the session's current plan (Phase: refine before
 * build). The draft is a client-side overlay — the published `plan.md`
 * artifact is immutable and is never written back (edit-as-input, not
 * artifact mutation). The approved plan (draft if edited, else the artifact
 * text) is delivered to the implement execution as an attachment.
 *
 * Ownership lives at the viewer level, NOT inside the plan document tab's
 * editor: the panel subtree unmounts wholesale on collapse (and the editor
 * remounts per plan identity), so editor-local state would be destroyed by
 * every collapse or tab switch — silently losing the user's edits.
 *
 * Supersession is derived, not synchronized: the draft is stored with the
 * plan identity it was made against ({@link planDraftKey}), and reads resolve
 * against the CURRENT plan's identity. When a newer plan arrives the old
 * draft simply stops matching — no effect, no cleanup, no stale-flush race.
 */
export function usePlanDraft(plan) {
    const [draft, setDraftState] = useState(null);
    const currentKey = plan ? planDraftKey(plan) : null;
    const draftText = draft !== null && currentKey !== null && draft.key === currentKey
        ? draft.text
        : null;
    // Render-synced mirrors so `readDraft` stays referentially stable while
    // always observing the latest draft/plan (the useSessionPanel viewRef
    // pattern).
    const draftRef = useRef(draft);
    draftRef.current = draft;
    const currentKeyRef = useRef(currentKey);
    currentKeyRef.current = currentKey;
    const setDraft = useCallback((text) => {
        const key = currentKeyRef.current;
        if (!key)
            return;
        setDraftState(text === null ? null : { key, text });
    }, []);
    const readDraft = useCallback(() => {
        const current = draftRef.current;
        const key = currentKeyRef.current;
        return current !== null && key !== null && current.key === key
            ? current.text
            : null;
    }, []);
    return useMemo(() => ({
        draftText,
        isEdited: draftText !== null,
        setDraft,
        readDraft,
    }), [draftText, setDraft, readDraft]);
}
//# sourceMappingURL=usePlanDraft.js.map