/**
 * useQuerySuggestions Hook
 *
 * Hook for fetching query suggestions with debouncing.
 * Fires a V4 Suggestion Impression event once per resolved response
 * (including zero-result responses) so the analytics pipeline captures
 * every dropdown render.
 */
import { useState, useEffect, useRef } from "react";
import { trackSuggestionImpression } from "@seekora-ai/search-sdk";
import { log } from "@seekora-ai/ui-sdk-core";
import { useTrackContext } from "../components/SearchProvider";
export const useQuerySuggestions = ({ client, query, enabled = true, debounceMs = 300, maxSuggestions = 10, }) => {
    const [suggestions, setSuggestions] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const debounceTimerRef = useRef(null);
    // V4 track context — null when no SearchProvider is in scope; impression
    // emission is a no-op in that case, not a crash.
    const trackCtx = useTrackContext();
    useEffect(() => {
        // Clear previous timer
        if (debounceTimerRef.current) {
            clearTimeout(debounceTimerRef.current);
        }
        if (!enabled || !query.trim()) {
            setSuggestions([]);
            setLoading(false);
            setError(null);
            return;
        }
        setLoading(true);
        setError(null);
        debounceTimerRef.current = setTimeout(async () => {
            const startedAt = Date.now();
            try {
                // SDK V4 widened the second arg to an options object — was a positional
                // hitsPerPage number in V3. Translate to the new shape.
                const response = await client.getSuggestions?.(query, {
                    hitsPerPage: maxSuggestions,
                });
                // Transform suggestions to SuggestionItem format
                // getSuggestions returns an array of suggestion objects with structure:
                // { query: string, popularity: number, objectID: string, ... }
                const rawSuggestions = Array.isArray(response) ? response : [];
                const suggestionItems = rawSuggestions.map((suggestion) => {
                    // Extract query - it should be in suggestion.query
                    const suggestionQuery = suggestion.query || suggestion.text || suggestion;
                    // Extract count/popularity
                    const count = suggestion.popularity !== undefined
                        ? suggestion.popularity
                        : suggestion.count !== undefined
                            ? suggestion.count
                            : undefined;
                    const item = {
                        query: typeof suggestionQuery === "string"
                            ? suggestionQuery
                            : String(suggestionQuery),
                        count: typeof count === "number" ? count : undefined,
                        metadata: suggestion,
                    };
                    return item;
                });
                setSuggestions(suggestionItems);
                // V4 Suggestion Impression — fire once per resolved response,
                // even when the list is empty (suggestions_count 0 is a valid
                // signal that no completions matched the prefix).
                // Guard: only emit when a TrackContext is wired (SearchProvider
                // present). Never throws — analytics must not break the UI.
                if (trackCtx) {
                    try {
                        trackSuggestionImpression(trackCtx, {
                            query_prefix: query,
                            suggestion_texts: suggestionItems.map((s) => s.query),
                            suggestion_positions: suggestionItems.map((_, i) => i + 1),
                            suggestion_types: suggestionItems.map(() => "query"),
                            suggestions_count: suggestionItems.length,
                            latency_ms: Date.now() - startedAt,
                            surface: "dropdown",
                        });
                    }
                    catch (emitErr) {
                        log.warn("useQuerySuggestions: impression emit failed", {
                            error: emitErr instanceof Error ? emitErr.message : String(emitErr),
                        });
                    }
                }
            }
            catch (err) {
                const error = err instanceof Error ? err : new Error(String(err));
                // Check if it's a 404 error (suggestions not enabled for this store).
                // The search SDK wraps axios errors into plain Error objects with the status
                // embedded in the message, e.g. "[getSuggestions] ... (404)".
                const errMsg = error.message || "";
                const is404 = err?.response?.status === 404 ||
                    err?.status === 404 ||
                    /\(404\)/.test(errMsg);
                if (is404) {
                    // Silently handle 404 - suggestions feature not enabled
                    log.verbose("Query suggestions not enabled for this store (404)");
                    setSuggestions([]);
                    setError(null);
                }
                else {
                    // For other errors, log and set error state
                    log.error("Error in useQuerySuggestions:", error);
                    setError(error);
                    setSuggestions([]);
                }
            }
            finally {
                setLoading(false);
            }
        }, debounceMs);
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, [client, query, enabled, debounceMs, maxSuggestions, trackCtx]);
    return {
        suggestions,
        loading,
        error,
    };
};
