// ==========================================
// Notes Surface — useWorkspace Hook
// ==========================================
// Coordinator hook: manages sidebar state and active note.
// Persists active selection to sessionStorage for reload restore.
//
// v0.37.11: New Preact surface.

const { useState, useCallback, useEffect } = window.hooks;

const STORAGE_KEY = 'sw-notes-active';

/**
 * @returns {{
 *   activeNoteId: string|null,
 *   sidebarOpen: boolean,
 *   setSidebarOpen: (v: boolean) => void,
 *   selectNote: (id: string) => void,
 *   clearSelection: () => void,
 * }}
 */
export function useWorkspace() {
    const stored = _loadStored();
    const [activeNoteId, setActiveNoteId] = useState(stored);
    const [sidebarOpen, setSidebarOpen] = useState(true);

    // Persist on change
    useEffect(() => {
        if (activeNoteId) {
            try { sessionStorage.setItem(STORAGE_KEY, activeNoteId); } catch (_) {}
        } else {
            sessionStorage.removeItem(STORAGE_KEY);
        }
    }, [activeNoteId]);

    const selectNote = useCallback((id) => {
        setActiveNoteId(id);
        // Auto-close sidebar on mobile
        if (window.innerWidth < 768) setSidebarOpen(false);
    }, []);

    const clearSelection = useCallback(() => {
        setActiveNoteId(null);
    }, []);

    return {
        activeNoteId,
        sidebarOpen,
        setSidebarOpen,
        selectNote,
        clearSelection,
    };
}

function _loadStored() {
    try {
        return sessionStorage.getItem(STORAGE_KEY) || null;
    } catch (_) { return null; }
}
