import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { filterModels, groupModels } from "./utils.js";
function useModelPickerState(opts) {
    const { models, value, onChange, groupBy: initialGroupBy = "subscription", recommendedModelIds, previewModelIds, filter, initiallyCollapsedGroups, i18n } = opts;
    const reactId = useId();
    const id = `apollo-model-picker-${reactId}`;
    const triggerRef = useRef(null);
    const searchRef = useRef(null);
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState('');
    const [activeIndex, setActiveIndex] = useState(0);
    const [groupBy, setGroupBy] = useState(initialGroupBy);
    const [collapsedSet, setCollapsedSet] = useState(()=>new Set(initiallyCollapsedGroups ?? []));
    const visibleModels = useMemo(()=>filter ? models.filter(filter) : models, [
        models,
        filter
    ]);
    const annotated = useMemo(()=>{
        const groups = groupModels(visibleModels, groupBy, {
            recommendedModelIds,
            previewModelIds,
            i18n
        });
        return groups.flatMap((g)=>g.models.map((m)=>({
                    ...m,
                    groupKey: g.key,
                    groupLabel: g.label
                })));
    }, [
        visibleModels,
        groupBy,
        recommendedModelIds,
        previewModelIds,
        i18n
    ]);
    const filtered = useMemo(()=>filterModels(annotated, query), [
        annotated,
        query
    ]);
    const groupCounts = useMemo(()=>{
        const out = {};
        for (const m of annotated)out[m.groupKey] = (out[m.groupKey] ?? 0) + 1;
        return out;
    }, [
        annotated
    ]);
    const selected = useMemo(()=>annotated.find((m)=>m.modelId === value) ?? models.find((m)=>m.modelId === value) ?? null, [
        annotated,
        models,
        value
    ]);
    const unknownValue = useMemo(()=>{
        if (!value) return null;
        if (selected) return null;
        if (0 === models.length) return null;
        return value;
    }, [
        models,
        selected,
        value
    ]);
    const collapsedGroups = useMemo(()=>query.trim() ? new Set() : collapsedSet, [
        query,
        collapsedSet
    ]);
    const toggleGroup = useCallback((groupKey)=>{
        setCollapsedSet((prev)=>{
            const next = new Set(prev);
            if (next.has(groupKey)) next.delete(groupKey);
            else next.add(groupKey);
            return next;
        });
    }, []);
    useEffect(()=>{
        if (open) {
            const sel = filtered.findIndex((m)=>m.modelId === value);
            setActiveIndex(sel >= 0 ? sel : 0);
            requestAnimationFrame(()=>searchRef.current?.focus());
        } else setQuery('');
    }, [
        open
    ]);
    useEffect(()=>{
        if (activeIndex >= filtered.length) setActiveIndex(0);
    }, [
        filtered.length,
        activeIndex
    ]);
    const choose = useCallback((m)=>{
        onChange?.(m);
        setOpen(false);
        triggerRef.current?.focus();
    }, [
        onChange
    ]);
    const onSearchKeyDown = useCallback((e)=>{
        if ('ArrowDown' === e.key) {
            e.preventDefault();
            setActiveIndex((i)=>Math.min(i + 1, Math.max(filtered.length - 1, 0)));
        } else if ('ArrowUp' === e.key) {
            e.preventDefault();
            setActiveIndex((i)=>Math.max(i - 1, 0));
        } else if ('Enter' === e.key) {
            e.preventDefault();
            const m = filtered[activeIndex];
            if (m) choose(m);
        } else if ('Escape' === e.key) {
            e.preventDefault();
            setOpen(false);
            triggerRef.current?.focus();
        }
    }, [
        filtered,
        activeIndex,
        choose
    ]);
    return {
        open,
        setOpen,
        query,
        setQuery,
        groupBy,
        setGroupBy,
        visibleModels,
        annotated,
        filtered,
        groupCounts,
        collapsedGroups,
        toggleGroup,
        selected,
        unknownValue,
        activeIndex,
        setActiveIndex,
        onSearchKeyDown,
        choose,
        id,
        triggerRef,
        searchRef
    };
}
export { useModelPickerState };
