/**
 * SectionSearchProvider – preset query + filter section
 *
 * Runs client.search(query, { refinements, hitsPerPage, sortBy }) on mount and when
 * query/filters change. Does not use global SearchStateManager. Use for menus,
 * sidebar, front-page blocks (e.g. "New arrivals", "On sale").
 */
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useSearchContext } from '../SearchProvider';
import { SectionSearchContext } from './SectionSearchContext';
function extractItems(response) {
    if (!response)
        return [];
    if (Array.isArray(response.results))
        return response.results;
    if (Array.isArray(response.hits))
        return response.hits;
    const data = response.data;
    if (data && Array.isArray(data.results))
        return data.results;
    if (data && Array.isArray(data.data))
        return data.data;
    return [];
}
function extractTotal(response) {
    if (!response)
        return 0;
    const n = response.totalResults ?? response.total ?? response.total_results;
    if (typeof n === 'number')
        return n;
    const data = response.data;
    if (data?.total_results != null)
        return Number(data.total_results);
    if (data?.data?.total_results != null)
        return Number(data.data.total_results);
    return 0;
}
export function SectionSearchProvider({ children, query, refinements = [], maxItems = 12, sortBy, enabled = true, sectionId, searchOptions, }) {
    const { client } = useSearchContext();
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [totalCount, setTotalCount] = useState(0);
    useEffect(() => {
        if (!enabled || !client?.search) {
            setItems([]);
            setLoading(false);
            setError(null);
            setTotalCount(0);
            return;
        }
        let cancelled = false;
        setLoading(true);
        setError(null);
        const options = {
            ...searchOptions,
            per_page: maxItems,
            page: 1,
        };
        if (sortBy)
            options.sort_by = sortBy;
        if (refinements.length > 0) {
            options.filter_by = refinements.map((r) => `${r.field}:${r.value}`).join(',');
        }
        client
            .search(query, options)
            .then((response) => {
            if (cancelled)
                return;
            setItems(extractItems(response));
            setTotalCount(extractTotal(response));
            setLoading(false);
        })
            .catch((err) => {
            if (cancelled)
                return;
            setError(err instanceof Error ? err : new Error(String(err)));
            setItems([]);
            setLoading(false);
        });
        return () => {
            cancelled = true;
        };
    }, [client, enabled, query, maxItems, sortBy, refinements, searchOptions]);
    const trackClick = useCallback((item, position) => {
        if (!client?.trackEvent)
            return;
        const id = item?.id ?? item?.objectID;
        client.trackEvent({
            event_name: 'section_result_click',
            clicked_item_id: id,
            position,
            section: sectionId,
            metadata: { section_id: sectionId },
        }, undefined);
    }, [client, sectionId]);
    const value = useMemo(() => ({
        items,
        loading,
        error,
        totalCount,
        sectionId,
        trackClick,
    }), [items, loading, error, totalCount, sectionId, trackClick]);
    return React.createElement(SectionSearchContext.Provider, { value: value }, children);
}
