"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isTerminalPhase } from "../execution/execution-phases.js";
import { useWorkspaceEditorsStoreRef, } from "../internal/store/index.js";
import { PLAN_DOCUMENT_ENTRY_ID, PLAN_DOCUMENT_PATH } from "./plan-document.js";
/**
 * Create a {@link SessionPanelController} for a viewer instance.
 */
export function useSessionPanel({ phase, hasChanges, planKey = null, defaultView = "files", }) {
    const editorsStore = useWorkspaceEditorsStoreRef();
    const [isOpen, setIsOpen] = useState(false);
    const [view, setViewState] = useState(defaultView);
    // Sticky explicit pick (rail click) — auto-switching yields to it until a
    // meaningful state change resets it. Same semantics as the retired tab FSM.
    const userPickedViewRef = useRef(false);
    // Render-synced mirror so imperative callbacks read the current view without
    // re-binding on every view change.
    const viewRef = useRef(view);
    viewRef.current = view;
    // Last selection reported by the panel subtree; consulted by transitions that
    // fire at the owner level (open, phase change) where selection state is
    // deliberately not subscribed.
    const selectionRef = useRef(null);
    // Running⇄terminal transition → reset the sticky pick and re-derive the view.
    // Adjust-state-during-render (the established ResizableSplit pattern) so it
    // lands before paint without an effect.
    const [prevPhase, setPrevPhase] = useState(phase);
    if (phase !== prevPhase) {
        const wasTerminal = prevPhase !== null && isTerminalPhase(prevPhase);
        const isNowTerminal = phase !== null && isTerminalPhase(phase);
        setPrevPhase(phase);
        if (wasTerminal !== isNowTerminal) {
            userPickedViewRef.current = false;
            setViewState(selectionRef.current ? "inspect" : defaultView);
        }
    }
    // First write-back arrived → surface Changes, but only in an open panel and
    // never over an explicit pick. Collapsed panels signal via badges alone.
    const [prevHasChanges, setPrevHasChanges] = useState(hasChanges);
    if (hasChanges !== prevHasChanges) {
        setPrevHasChanges(hasChanges);
        if (hasChanges && isOpen && !userPickedViewRef.current) {
            setViewState("changes");
        }
    }
    const openPlanDocument = useCallback(() => {
        editorsStore.openPinned(PLAN_DOCUMENT_ENTRY_ID, PLAN_DOCUMENT_PATH);
        setIsOpen(true);
    }, [editorsStore]);
    // A new plan arrived (first plan, or a refinement superseding it) → open the
    // plan document tab, expanding a collapsed panel (see the planKey option doc
    // for why this one trigger may open the panel). An effect, NOT the
    // render-adjust idiom the phase/changes triggers use: those set this
    // component's own state, which the idiom permits — this one mutates the
    // external editors store (notifying subscribers), which is illegal during
    // render. The ref (not effect-less prev-state) swallows the identity present
    // at mount: loading a session with an old plan never hijacks the layout.
    const prevPlanKeyRef = useRef(planKey);
    useEffect(() => {
        if (planKey === prevPlanKeyRef.current)
            return;
        prevPlanKeyRef.current = planKey;
        if (planKey !== null) {
            openPlanDocument();
        }
    }, [planKey, openPlanDocument]);
    const openPanel = useCallback(() => {
        setIsOpen(true);
        // Re-derive the auto view on entry: a selection made while collapsed
        // surfaces as Inspect now (the collapsed panel ignored it by design).
        if (!userPickedViewRef.current && selectionRef.current) {
            setViewState("inspect");
        }
    }, []);
    const closePanel = useCallback(() => setIsOpen(false), []);
    const setView = useCallback((viewId) => {
        userPickedViewRef.current = true;
        setViewState(viewId);
    }, []);
    const openFile = useCallback((entryId, path, options) => {
        editorsStore.openPreview(entryId, path, options);
        setIsOpen(true);
    }, [editorsStore]);
    const activateEditor = useCallback((entryId, path) => editorsStore.activate(entryId, path), [editorsStore]);
    const pinEditor = useCallback((entryId, path) => editorsStore.pin(entryId, path), [editorsStore]);
    const closeEditor = useCallback((entryId, path) => editorsStore.close(entryId, path), [editorsStore]);
    const notifySelection = useCallback((item) => {
        if (item === selectionRef.current)
            return;
        selectionRef.current = item;
        if (item) {
            if (isOpen && !userPickedViewRef.current)
                setViewState("inspect");
        }
        else if (viewRef.current === "inspect") {
            // Selection cleared: leave Inspect (its content is gone) and unstick,
            // returning to the panel's home view.
            userPickedViewRef.current = false;
            setViewState(defaultView);
        }
    }, [isOpen, defaultView]);
    return useMemo(() => ({
        editorsStore,
        isOpen,
        view,
        openPanel,
        closePanel,
        setView,
        openFile,
        activateEditor,
        pinEditor,
        closeEditor,
        openPlanDocument,
        notifySelection,
    }), [
        editorsStore,
        isOpen,
        view,
        openPanel,
        closePanel,
        setView,
        openFile,
        activateEditor,
        pinEditor,
        closeEditor,
        openPlanDocument,
        notifySelection,
    ]);
}
//# sourceMappingURL=useSessionPanel.js.map