/**
 * useImpressionTracker — records `Search Impression` into the batched
 * impression buffer when the ref'd element first crosses the visibility
 * threshold (default 0.5).
 *
 * Phase 2b of the V4 analytics pivot (SCRUM-259). Replaces the per-card
 * `trackSearchImpression` emission with a `buffer.record()` call against
 * the `SearchImpressionBuffer` from `<BufferProvider>`. The buffer
 * accumulates entries within a debounce window and flushes ONE batched
 * `Search Impression` event with parallel arrays.
 *
 * The hook is a thin React shell: it owns the IntersectionObserver
 * registration via `observeOnce` (framework-agnostic), then records into
 * the buffer.
 *
 * Usage:
 *   const ref = useRef<HTMLDivElement>(null);
 *   useImpressionTracker(ref, {
 *     ctx, objectId: result.id, position: index + 1,
 *     surface: "results_page", searchId,
 *   });
 *   return <div ref={ref}>...</div>;
 *
 * If `ctx` is null/undefined (no SearchProvider in the tree yet, SSR
 * first paint) the hook is a no-op. If no `<BufferProvider>` is above,
 * the buffer hook returns a no-op shim — descendant cards still render
 * but no V4 emission happens.
 */
import { useEffect } from "react";
import { observeOnce } from "@seekora-ai/ui-sdk-core";
import { useSearchImpressionBuffer } from "./useSearchImpressionBuffer";
export function useImpressionTracker(ref, props) {
    const { ctx, objectId, objectType = "product", position, surface, searchId, objectData, } = props;
    const impressionBuffer = useSearchImpressionBuffer();
    useEffect(() => {
        const el = ref.current;
        if (!el || !ctx)
            return undefined;
        // Only the "results_page" / "dropdown" surfaces hit the impression
        // buffer; "recommendation_widget" is an outside-search surface
        // that should go through the viewed buffer instead (use
        // `useCardAnalytics` with `surface="recommendation_widget"`).
        if (surface === "recommendation_widget")
            return undefined;
        if (!searchId)
            return undefined;
        return observeOnce(el, () => {
            impressionBuffer.record(objectId, position, searchId, { object_type: objectType, ...(objectData ?? {}) }, surface);
        });
        // Buffer ref is stable across renders.
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [ref, ctx, objectId, objectType, position, surface, searchId, objectData]);
}
