/**
 * Suggestions Analytics Hook
 *
 * Provides analytics tracking for query suggestions components using
 * Analytics V3 event structure and schema/fields (event_name, event_ts,
 * correlation_id/search_id via context, and V3 top-level fields such as
 * original_query, position, section, clicked_item_id, click_type, tab_id,
 * suggestions_count, etc.). All events are sent via client.trackEvent(payload, context)
 * so the SDK can attach correlation_id, search_id, event_ts, orgcode, xstoreid.
 */
import { useCallback, useRef, useEffect } from 'react';
import { log } from '@seekora-ai/ui-sdk-core';
// ============================================================================
// Event Names
// ============================================================================
const EVENTS = {
    SUGGESTION_CLICK: 'suggestions.click',
    SUGGESTION_IMPRESSION: 'suggestions.impression',
    PRODUCT_CLICK: 'suggestions.product_click',
    CATEGORY_CLICK: 'suggestions.category_click',
    BRAND_CLICK: 'suggestions.brand_click',
    TAB_SELECT: 'suggestions.tab_select',
    RECENT_CLICK: 'suggestions.recent_click',
    TRENDING_CLICK: 'suggestions.trending_click',
    SEARCH_SUBMIT: 'suggestions.search_submit',
    DROPDOWN_OPEN: 'suggestions.dropdown_open',
    DROPDOWN_CLOSE: 'suggestions.dropdown_close',
    // Variant & product interaction events
    VARIANT_SELECT: 'product.variant_select',
    VARIANT_HOVER: 'product.variant_hover',
    ADD_TO_CART: 'product.add_to_cart',
    PRODUCT_IMPRESSION: 'product.impression',
    SWATCH_CLICK: 'product.swatch_click',
};
// ============================================================================
// Hook Implementation
// ============================================================================
export function useSuggestionsAnalytics(options) {
    const { client, enabled = true, analyticsTags = [], impressionDebounce = 500, trackImpressions = true, trackClicks = true, context: contextOption, } = options;
    // Refs for debouncing and tracking
    const impressionTimerRef = useRef(null);
    const lastImpressionRef = useRef(null);
    const dropdownOpenTimeRef = useRef(null);
    // Cleanup on unmount
    useEffect(() => {
        return () => {
            if (impressionTimerRef.current) {
                clearTimeout(impressionTimerRef.current);
            }
        };
    }, []);
    // Helper to send event (optional context links event to search for v3 analytics)
    const sendEvent = useCallback(async (eventName, metadata, context) => {
        if (!enabled || !client)
            return;
        const searchContext = context ?? contextOption;
        try {
            // Extract query for search-related events (backend requires query at top level for search events)
            const { query, ...restMetadata } = metadata;
            const isSearchEvent = eventName.includes('search') || eventName === EVENTS.SEARCH_SUBMIT;
            await client.trackEvent?.({
                event_name: eventName,
                analytics_tags: analyticsTags,
                // Include query at top level for search events
                ...(isSearchEvent && query ? { query } : {}),
                metadata: {
                    ...restMetadata,
                    timestamp: Date.now(),
                    source: 'suggestions_dropdown',
                },
            }, searchContext);
            log.verbose(`Analytics: ${eventName}`, metadata);
        }
        catch (error) {
            log.warn(`Failed to track ${eventName}`, { error });
        }
    }, [client, enabled, analyticsTags, contextOption]);
    // Track suggestion click
    const trackSuggestionClick = useCallback((data) => {
        if (!trackClicks)
            return;
        sendEvent(EVENTS.SUGGESTION_CLICK, {
            suggestion_query: data.suggestion.query,
            suggestion_id: data.suggestion.objectID,
            suggestion_popularity: data.suggestion.popularity,
            position: data.position,
            section: data.section || 'suggestions',
            original_query: data.query,
            total_suggestions: data.totalSuggestions,
        });
    }, [sendEvent, trackClicks]);
    // Track product click
    const trackProductClick = useCallback((data) => {
        if (!trackClicks)
            return;
        sendEvent(EVENTS.PRODUCT_CLICK, {
            product_id: data.product.id || data.product.objectID,
            product_title: data.product.title || data.product.name,
            product_price: data.product.price,
            position: data.position,
            section: data.section || 'products',
            tab_id: data.tabId,
            original_query: data.query,
        });
        // Also track as a general product click for analytics (with context when available)
        const searchContext = contextOption;
        if (client?.trackClick) {
            Promise.resolve(client.trackClick(data.product.id || data.product.objectID || '', data.position + 1, searchContext)).catch(() => { });
        }
    }, [client, contextOption, sendEvent, trackClicks]);
    // Track category click
    const trackCategoryClick = useCallback((category, query) => {
        if (!trackClicks)
            return;
        sendEvent(EVENTS.CATEGORY_CLICK, {
            category_value: category.value,
            category_count: category.count,
            category_path: category.path,
            original_query: query,
        });
    }, [sendEvent, trackClicks]);
    // Track brand click
    const trackBrandClick = useCallback((brand, query) => {
        if (!trackClicks)
            return;
        sendEvent(EVENTS.BRAND_CLICK, {
            brand_name: brand.name,
            brand_count: brand.count,
            original_query: query,
        });
    }, [sendEvent, trackClicks]);
    // Track tab selection
    const trackTabSelect = useCallback((tab, query) => {
        sendEvent(EVENTS.TAB_SELECT, {
            tab_id: tab.id,
            tab_label: tab.label,
            tab_filter: tab.filter,
            products_count: tab.products?.length || 0,
            nb_hits: tab.nb_hits,
            original_query: query,
        });
    }, [sendEvent]);
    // Track recent search click
    const trackRecentSearchClick = useCallback((search) => {
        if (!trackClicks)
            return;
        sendEvent(EVENTS.RECENT_CLICK, {
            query: search.query,
            original_timestamp: search.timestamp,
            results_count: search.resultsCount,
        });
    }, [sendEvent, trackClicks]);
    // Track trending click
    const trackTrendingClick = useCallback((trending, position) => {
        if (!trackClicks)
            return;
        sendEvent(EVENTS.TRENDING_CLICK, {
            query: trending.query,
            count: trending.count,
            trend_score: trending.trend_score,
            position,
        });
    }, [sendEvent, trackClicks]);
    // Track impression (debounced)
    const trackImpression = useCallback((data) => {
        if (!trackImpressions)
            return;
        // Create a hash of the impression to avoid duplicates
        const impressionHash = `${data.query}:${data.suggestions.length}:${data.products?.length || 0}`;
        if (impressionHash === lastImpressionRef.current)
            return;
        // Clear existing timer
        if (impressionTimerRef.current) {
            clearTimeout(impressionTimerRef.current);
        }
        // Debounce the impression
        impressionTimerRef.current = setTimeout(() => {
            lastImpressionRef.current = impressionHash;
            sendEvent(EVENTS.SUGGESTION_IMPRESSION, {
                query: data.query,
                suggestions_count: data.suggestions.length,
                suggestions: data.suggestions.slice(0, 10).map((s, i) => ({
                    query: s.query,
                    position: i,
                    popularity: s.popularity,
                })),
                products_count: data.products?.length || 0,
                categories_count: data.categories?.length || 0,
                brands_count: data.brands?.length || 0,
                impression_timestamp: data.timestamp,
            });
        }, impressionDebounce);
    }, [sendEvent, trackImpressions, impressionDebounce]);
    // Track search submit
    const trackSearchSubmit = useCallback((query, fromSuggestion, suggestion) => {
        sendEvent(EVENTS.SEARCH_SUBMIT, {
            query,
            from_suggestion: fromSuggestion,
            suggestion_query: suggestion?.query,
            suggestion_id: suggestion?.objectID,
            suggestion_popularity: suggestion?.popularity,
        });
    }, [sendEvent]);
    // Track dropdown open
    const trackDropdownOpen = useCallback((query) => {
        dropdownOpenTimeRef.current = Date.now();
        sendEvent(EVENTS.DROPDOWN_OPEN, {
            query,
            has_query: query.length > 0,
        });
    }, [sendEvent]);
    // Track dropdown close
    const trackDropdownClose = useCallback((query, selectedSuggestion) => {
        const duration = dropdownOpenTimeRef.current
            ? Date.now() - dropdownOpenTimeRef.current
            : null;
        sendEvent(EVENTS.DROPDOWN_CLOSE, {
            query,
            selected_suggestion: selectedSuggestion,
            had_selection: !!selectedSuggestion,
            duration_ms: duration,
        });
        dropdownOpenTimeRef.current = null;
    }, [sendEvent]);
    return {
        trackSuggestionClick,
        trackProductClick,
        trackCategoryClick,
        trackBrandClick,
        trackTabSelect,
        trackRecentSearchClick,
        trackTrendingClick,
        trackImpression,
        trackSearchSubmit,
        trackDropdownOpen,
        trackDropdownClose,
    };
}
export default useSuggestionsAnalytics;
