/**
 * useClickTracking Hook
 *
 * Wraps result link clicks with analytics fire-before-navigate.
 * - For target="_blank" links: fires analytics normally (page stays)
 * - For same-page navigation: uses sendBeacon + small delay before navigation
 * - Tracks click_target: 'new_tab' | 'same_page' | 'in_page'
 * - Includes destination_url and source_url in click event payload
 */
import { useCallback, useRef } from "react";
import { useSearchContext } from "../components/SearchProvider";
import { useSearchState } from "./useSearchState";
export const useClickTracking = () => {
    const { client, enableAnalytics, stateManager } = useSearchContext();
    const { results } = useSearchState();
    const pendingRef = useRef(false);
    const trackClick = useCallback(async (options) => {
        if (!enableAnalytics || pendingRef.current)
            return;
        pendingRef.current = true;
        try {
            const sourceUrl = typeof window !== "undefined" ? window.location.href : undefined;
            const searchContext = results?.context;
            // Include A/B test fields from state manager (beacon payloads bypass client.trackEvent)
            const abTestId = stateManager.getAbTestId?.();
            const abVariant = stateManager.getAbVariant?.();
            const eventPayload = {
                event_name: "product_click",
                clicked_item_id: options.itemId,
                position: options.position,
                destination_url: options.destinationUrl || "",
                source_url: sourceUrl || "",
                click_target: options.clickTarget || "in_page",
                ...(abTestId && { ab_test_id: abTestId }),
                ...(abVariant && { ab_variant: abVariant }),
                ...options.metadata,
            };
            if (options.clickTarget === "same_page") {
                // For same_page navigation, track via SDK then flush to ensure delivery before navigation
                if (client.trackEvent) {
                    await client.trackEvent(eventPayload, searchContext);
                    await client.flushEventQueue();
                }
            }
            else {
                // Normal tracking via client SDK — V4 canonical Object Clicked.
                const searchId = searchContext
                    ?.search_id;
                if (searchId) {
                    await client.trackObjectClicked({
                        object_ids: [options.itemId],
                        object_positions: [options.position],
                        search_id: searchId,
                    });
                }
                else {
                    await client.trackObjectClickedOutsideSearch({
                        object_ids: [options.itemId],
                        object_positions: [options.position],
                    });
                }
            }
        }
        catch {
            // Silently fail — analytics should never break navigation
        }
        finally {
            pendingRef.current = false;
        }
    }, [client, enableAnalytics, results, stateManager]);
    const createClickHandler = useCallback((options, onComplete) => {
        return (e) => {
            const anchor = e.currentTarget;
            const href = anchor.href;
            const target = anchor.target;
            const isNewTab = target === "_blank" || e.metaKey || e.ctrlKey;
            const clickTarget = isNewTab ? "new_tab" : "same_page";
            const trackOptions = { ...options, destinationUrl: href, clickTarget };
            if (isNewTab) {
                // New tab: page stays, track normally
                trackClick(trackOptions);
                onComplete?.();
            }
            else {
                // Same page: prevent default, track with beacon, then navigate
                e.preventDefault();
                trackClick(trackOptions).then(() => {
                    // Small delay to ensure beacon fires
                    setTimeout(() => {
                        onComplete?.();
                        window.location.href = href;
                    }, 50);
                });
            }
        };
    }, [trackClick]);
    return { trackClick, createClickHandler };
};
