// ==========================================
// Notes Surface — useSidebar Hook
// ==========================================
// Loads folders and tags for the sidebar.
// Subscribes to WS events for live updates.
//
// v0.37.11: New Preact surface.

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

const COLLAPSE_KEY = 'sw-notes-sidebar-collapsed';

/**
 * @returns {{
 *   folders: Array<{ path: string, count: number }>,
 *   tags: Array<[string, number]>,
 *   activeFolder: string,
 *   activeTag: string,
 *   search: string,
 *   setActiveFolder: (f: string) => void,
 *   setActiveTag: (t: string) => void,
 *   setSearch: (q: string) => void,
 *   collapsed: { folders: boolean, tags: boolean },
 *   toggleCollapsed: (key: string) => void,
 *   loading: boolean,
 * }}
 */
export function useSidebar() {
    const [folders, setFolders] = useState([]);
    const [allNotes, setAllNotes] = useState([]);
    const [activeFolder, setActiveFolder] = useState('');
    const [activeTag, setActiveTag] = useState('');
    const [search, setSearch] = useState('');
    const [collapsed, setCollapsed] = useState(_loadCollapsed);
    const [loading, setLoading] = useState(true);

    // ── Load data ───────────────────────────
    const reload = useCallback(async () => {
        if (!window.sw?.api?.notes) return;

        try {
            const [fResp, nResp] = await Promise.all([
                window.sw.api.notes.folders().catch(() => []),
                window.sw.api.notes.list({ per_page: 200 }).catch(() => []),
            ]);

            setFolders(_extract(fResp));
            setAllNotes(_extract(nResp));
        } catch (_) {}

        setLoading(false);
    }, []);

    useEffect(() => { reload(); }, [reload]);

    // ── WebSocket live updates ──────────────
    useEffect(() => {
        if (!window.sw?.on) return;

        const events = [
            'note.created', 'note.updated', 'note.deleted',
        ];

        events.forEach(ev => window.sw.on(ev, reload));
        return () => {
            events.forEach(ev => window.sw.off?.(ev, reload));
        };
    }, [reload]);

    // ── Aggregate tags from notes ───────────
    const tags = useMemo(() => {
        const counts = {};
        for (const n of allNotes) {
            for (const t of (n.tags || [])) {
                counts[t] = (counts[t] || 0) + 1;
            }
        }
        return Object.entries(counts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 30);
    }, [allNotes]);

    // ── Collapse sections ───────────────────
    const toggleCollapsed = useCallback((key) => {
        setCollapsed(prev => {
            const next = { ...prev, [key]: !prev[key] };
            try { localStorage.setItem(COLLAPSE_KEY, JSON.stringify(next)); } catch (_) {}
            return next;
        });
    }, []);

    return {
        folders,
        tags,
        activeFolder,
        activeTag,
        search,
        setActiveFolder,
        setActiveTag,
        setSearch,
        collapsed,
        toggleCollapsed,
        loading,
    };
}

function _extract(resp) {
    if (!resp) return [];
    if (Array.isArray(resp)) return resp;
    if (Array.isArray(resp.data)) return resp.data;
    const vals = Object.values(resp);
    for (const v of vals) {
        if (Array.isArray(v)) return v;
    }
    return [];
}

function _loadCollapsed() {
    try {
        return JSON.parse(localStorage.getItem(COLLAPSE_KEY)) || {};
    } catch (_) { return {}; }
}
