/**
 * useVariantSelection – manages variant selection state
 *
 * Single source of truth for variant interactions on product pages.
 * Cards display variants passively; product pages use this hook.
 */
import { useState, useMemo, useCallback } from 'react';
import { findVariantBySelections, getAvailableValuesForOption } from '../components/suggestions/utils';
export function useVariantSelection({ options = [], variants = [], initialSelections = {}, onVariantChange, } = {}) {
    const [selections, setSelections] = useState(initialSelections);
    const selectedVariant = useMemo(() => findVariantBySelections(options, variants, selections), [options, variants, selections]);
    const isComplete = useMemo(() => options.length > 0 && options.every((opt) => !!selections[opt.name]), [options, selections]);
    const availableValues = useMemo(() => {
        const result = {};
        for (const option of options) {
            result[option.name] = getAvailableValuesForOption(option.name, options, variants, selections);
        }
        return result;
    }, [options, variants, selections]);
    const effectivePrice = selectedVariant?.price ?? null;
    const effectiveComparePrice = selectedVariant?.comparePrice ?? null;
    const setSelection = useCallback((optionName, value) => {
        setSelections((prev) => {
            const next = { ...prev, [optionName]: value };
            const variant = findVariantBySelections(options, variants, next);
            onVariantChange?.(variant, next);
            return next;
        });
    }, [options, variants, onVariantChange]);
    const resetSelections = useCallback(() => {
        setSelections({});
        onVariantChange?.(null, {});
    }, [onVariantChange]);
    return {
        selections,
        setSelection,
        resetSelections,
        selectedVariant,
        availableValues,
        isComplete,
        effectivePrice,
        effectiveComparePrice,
    };
}
