"use client";
import { useMemo, useCallback, useState, useRef, useEffect } from "react";
import { getCoreRowModel, getSortedRowModel, useReactTable, } from "@tanstack/react-table";
import { useFetch } from "../../internal/useFetch";
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
const DEFAULT_PAGE_SIZE = 20;
const INITIAL_DATA = {
    entries: [],
    totalCount: 0,
    totalPages: 0,
};
/**
 * Headless hook that manages resource collection state: data fetching,
 * sorting, selection, and pagination.
 *
 * Wraps `useFetch` for data and `@tanstack/react-table` for table state
 * (sorting, selection, column visibility). The hook itself produces no
 * DOM — it returns data, state, and a TanStack Table instance that view
 * components (`ResourceTable`, `ResourceCards`, `ResourceList`) consume.
 *
 * Platform builders who want full rendering control use this hook
 * directly. The `ResourceWorkbench` shell composes it internally.
 *
 * @example
 * ```tsx
 * const collection = useResourceCollection({
 *   listFn: (params) => stigmer.agent.list(params),
 *   org: "acme",
 *   query: debouncedQuery,
 *   page: 1,
 *   columns: agentColumns,
 * });
 * ```
 */
export function useResourceCollection(options) {
    const { listFn, org, query = "", scope = "org", page = 1, pageSize = DEFAULT_PAGE_SIZE, sort = null, onSortChange, columns = [], enableSelection = false, } = options;
    // --- Data fetching via useFetch -----------------------------------------
    const { data, isLoading, isRefetching, error, refetch } = useFetch(listFn && org
        ? async () => {
            const params = {
                org,
                query: query || undefined,
                excludePublic: false,
                crossOrgPublic: scope === "all",
                page: { num: page, size: pageSize },
            };
            const result = await listFn(params);
            return {
                entries: [...result.entries],
                totalCount: result.totalCount,
                totalPages: result.totalPages,
            };
        }
        : null, [listFn, org, query, scope, page, pageSize], INITIAL_DATA);
    const items = data.entries;
    // --- TanStack Table sorting bridge --------------------------------------
    const sortingState = useMemo(() => {
        if (!sort)
            return [];
        return [{ id: sort.id, desc: sort.direction === "desc" }];
    }, [sort]);
    const onSortChangeRef = useRef(onSortChange);
    onSortChangeRef.current = onSortChange;
    const handleSortingChange = useCallback((updater) => {
        const next = typeof updater === "function" ? updater(sortingState) : updater;
        if (next.length === 0) {
            onSortChangeRef.current?.(null);
        }
        else {
            const col = next[0];
            onSortChangeRef.current?.({
                id: col.id,
                direction: (col.desc ? "desc" : "asc"),
            });
        }
    }, [sortingState]);
    // --- Row selection state ------------------------------------------------
    const [rowSelection, setRowSelection] = useState({});
    // Clear selection when page, query, or scope changes to prevent stale refs.
    const clearKey = `${page}-${query}-${scope}`;
    const prevClearKey = useRef(clearKey);
    useEffect(() => {
        if (prevClearKey.current !== clearKey) {
            prevClearKey.current = clearKey;
            setRowSelection({});
        }
    }, [clearKey]);
    // --- TanStack Table column conversion -----------------------------------
    const tanstackColumns = useMemo(() => {
        return columns.map((col) => ({
            id: col.id,
            header: col.header,
            cell: (info) => col.cell(info.row.original),
            enableSorting: col.sortable ?? false,
            size: col.minWidth,
            minSize: col.minWidth,
        }));
    }, [columns]);
    // --- TanStack Table instance -------------------------------------------
    const table = useReactTable({
        data: items,
        columns: tanstackColumns,
        state: {
            sorting: sortingState,
            rowSelection,
        },
        onSortingChange: handleSortingChange,
        onRowSelectionChange: enableSelection ? setRowSelection : undefined,
        getCoreRowModel: getCoreRowModel(),
        getSortedRowModel: getSortedRowModel(),
        getRowId: (row) => row.id ?? String(items.indexOf(row)),
        manualPagination: true,
        manualSorting: true,
        enableRowSelection: enableSelection,
    });
    const tableOrNull = tanstackColumns.length > 0 ? table : null;
    return {
        items,
        totalCount: data.totalCount,
        totalPages: data.totalPages,
        currentPage: page,
        isLoading,
        isRefetching,
        error,
        refetch,
        table: tableOrNull,
        rowSelection,
        setRowSelection,
    };
}
//# sourceMappingURL=useResourceCollection.js.map