/**
 * useExperiment Hook
 *
 * Fetches experiment variant assignments from the backend and caches them.
 * Auto-injects ab_test_id and ab_variant into SearchProvider context.
 *
 * Usage:
 *   const { experimentId, variantId, variantConfig, isLoading } = useExperiment('search-ranking-v2');
 */
import { useState, useEffect, useCallback, useRef } from 'react';
import { useSearchContext } from '../components/SearchProvider';
const CACHE_PREFIX = 'seekora_experiment_';
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
function getCachedAssignment(userKey, experimentId) {
    if (typeof localStorage === 'undefined')
        return null;
    try {
        const key = `${CACHE_PREFIX}${userKey}_${experimentId}`;
        const raw = localStorage.getItem(key);
        if (!raw)
            return null;
        const cached = JSON.parse(raw);
        if (Date.now() - cached.timestamp > CACHE_TTL_MS) {
            localStorage.removeItem(key);
            return null;
        }
        return cached.assignment;
    }
    catch {
        return null;
    }
}
function setCachedAssignment(userKey, assignment) {
    if (typeof localStorage === 'undefined')
        return;
    try {
        const key = `${CACHE_PREFIX}${userKey}_${assignment.experiment_id}`;
        const cached = { assignment, timestamp: Date.now() };
        localStorage.setItem(key, JSON.stringify(cached));
    }
    catch {
        // Silently fail — localStorage may be full or unavailable
    }
}
export const useExperiment = (experimentId) => {
    const { client, stateManager } = useSearchContext();
    const [allAssignments, setAllAssignments] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const fetchedRef = useRef(false);
    const fetchAssignments = useCallback(async () => {
        if (fetchedRef.current)
            return;
        fetchedRef.current = true;
        setIsLoading(true);
        try {
            // Try to determine user key for caching
            const clientAny = client;
            const userKey = clientAny.userId || clientAny.anonymousId || clientAny.anonId || '';
            // Check cache first for specific experiment
            if (experimentId && userKey) {
                const cached = getCachedAssignment(userKey, experimentId);
                if (cached) {
                    setAllAssignments([cached]);
                    // Update state manager and SDK client with cached assignment
                    stateManager.setAbTest(cached.experiment_id, cached.variant_id);
                    if (typeof clientAny.setAbTest === 'function') {
                        clientAny.setAbTest(cached.experiment_id, cached.variant_id);
                    }
                    setIsLoading(false);
                    return;
                }
            }
            // Fetch from backend via SDK client (handles auth, baseUrl, headers internally)
            if (typeof clientAny.getExperimentAssignment !== 'function') {
                setIsLoading(false);
                return;
            }
            const data = await client.getExperimentAssignment();
            const assignments = data.assignments || [];
            // Cache all assignments
            assignments.forEach(a => setCachedAssignment(userKey, a));
            setAllAssignments(assignments);
            // If a specific experiment was requested, set it on the state manager and SDK client
            const setAbFields = (expId, varId) => {
                stateManager.setAbTest(expId, varId);
                client.setAbTest(expId, varId);
            };
            if (experimentId) {
                const match = assignments.find(a => a.experiment_id === experimentId);
                if (match) {
                    setAbFields(match.experiment_id, match.variant_id);
                }
            }
            else if (assignments.length > 0) {
                // Use the first assignment by default
                setAbFields(assignments[0].experiment_id, assignments[0].variant_id);
            }
            setError(null);
        }
        catch (err) {
            setError(err instanceof Error ? err : new Error(String(err)));
        }
        finally {
            setIsLoading(false);
        }
    }, [client, stateManager, experimentId]);
    useEffect(() => {
        fetchAssignments();
    }, [fetchAssignments]);
    // Find the specific experiment assignment
    const assignment = experimentId
        ? allAssignments.find(a => a.experiment_id === experimentId)
        : allAssignments[0] || null;
    return {
        experimentId: assignment?.experiment_id || null,
        variantId: assignment?.variant_id || null,
        variantConfig: assignment?.variant_config || null,
        isLoading,
        error,
        allAssignments,
    };
};
