/**
 * ProductCard – one product tile (primitive)
 *
 * Without displayConfig: renders the original minimal layout (image, title, price).
 * With displayConfig: renders layout variants (minimal, standard, detailed, compact, horizontal).
 */
import React, { useMemo, useEffect } from "react";
import { clsx } from "clsx";
import { ImageDisplay } from "../primitives/ImageDisplay";
import { extractBadges, getPriceRange, findVariantBySelections, } from "../suggestions/utils";
import { useCardAnalytics, } from "../../hooks/useCardAnalytics";
import { ensureSeekoraStyles } from "../../styles/inject";
import { MinimalLayout, StandardLayout, DetailedLayout, CompactLayout, HorizontalLayout, } from "./ProductCardLayouts";
export function ProductCard({ product, position, section, tabId, onSelect, className, style, imageVariant = "single", displayConfig, onVariantHover, onVariantClick, selectedVariants, asLink, actionButtons, actionButtonsPosition = "inline", showActionLabels = false, enableImageZoom = false, imageZoomMode = "both", imageZoomLevel = 2.5, surface = "results_page", objectType = "product", searchId, trackingEnabled = true, }) {
    // V4 analytics wiring: Search Impression on first viewport entry +
    // Object Clicked wrapping the consumer's onSelect. No-op when there's
    // no SearchProvider above or trackingEnabled=false.
    const { ref: trackerRef, onClick: trackedOnClick } = useCardAnalytics({
        objectId: String(product.id ?? ""),
        position,
        objectType,
        surface,
        searchId,
        onSelect,
        enabled: trackingEnabled && Boolean(product.id),
    });
    // Inject canonical stylesheet once on mount
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    // Find selected variant if selections are provided
    const selectedVariant = useMemo(() => {
        if (!selectedVariants || !product.options || !product.variants)
            return null;
        return findVariantBySelections(product.options, product.variants, selectedVariants);
    }, [selectedVariants, product.options, product.variants]);
    // Compute effective display data (use selected variant if available, otherwise product defaults)
    const effectiveImages = useMemo(() => {
        // Priority: selected variant image > product images > product image
        if (selectedVariant?.image)
            return [selectedVariant.image];
        if (product.images?.length)
            return product.images;
        if (product.image ?? product.imageUrl)
            return [String(product.image ?? product.imageUrl)];
        return [];
    }, [selectedVariant, product]);
    const effectiveTitle = useMemo(() => {
        // Show variant title if available (e.g., "T-Shirt - Black / M")
        if (selectedVariant?.title && selectedVariant.title !== product.title) {
            return `${product.title ?? product.name ?? ""} - ${selectedVariant.title}`;
        }
        return product.title ?? product.name ?? "";
    }, [selectedVariant, product]);
    const effectivePrice = useMemo(() => {
        const variantPrice = selectedVariant?.price;
        if (variantPrice != null)
            return typeof variantPrice === "number"
                ? variantPrice
                : Number(variantPrice);
        const productPrice = product.price;
        return productPrice != null
            ? typeof productPrice === "number"
                ? productPrice
                : Number(productPrice)
            : null;
    }, [selectedVariant, product.price]);
    const effectiveComparePrice = useMemo(() => {
        const variantCompare = selectedVariant?.comparePrice;
        if (variantCompare != null)
            return typeof variantCompare === "number"
                ? variantCompare
                : Number(variantCompare);
        const productCompare = product.original_price ?? product.compare_at_price;
        return productCompare != null
            ? typeof productCompare === "number"
                ? productCompare
                : Number(productCompare)
            : null;
    }, [selectedVariant, product]);
    // Legacy vars for backwards compat
    const images = effectiveImages;
    const title = effectiveTitle;
    const price = effectivePrice;
    // Hover state for card
    const [isHovered, setIsHovered] = React.useState(false);
    // If no displayConfig, render original minimal layout (backwards compat)
    if (!displayConfig) {
        const minimalClassName = clsx("seekora-suggestions-product-card", isHovered && "seekora-suggestions-product-card--hover", className);
        const minimalProps = {
            ref: trackerRef,
            className: minimalClassName,
            style,
            onMouseEnter: () => setIsHovered(true),
            onMouseLeave: () => setIsHovered(false),
            "data-position": position,
            "data-section": section,
            "data-tab-id": tabId,
        };
        const safeUrl = (() => {
            if (!product.url)
                return false;
            if (product.url.startsWith("/"))
                return true;
            try {
                const p = new URL(product.url, window.location.origin);
                return p.protocol === "https:" || p.protocol === "http:";
            }
            catch {
                return false;
            }
        })();
        const Tag = asLink && safeUrl ? "a" : "div";
        const extraProps = asLink && safeUrl
            ? { href: product.url, onClick: trackedOnClick }
            : {
                role: "button",
                tabIndex: 0,
                onClick: trackedOnClick,
                onKeyDown: (e) => {
                    if (e.key === "Enter" || e.key === " ") {
                        e.preventDefault();
                        trackedOnClick();
                    }
                },
            };
        return (React.createElement(Tag, { ...minimalProps, ...extraProps },
            images.length > 0 ? (React.createElement(ImageDisplay, { images: images, variant: imageVariant, alt: title, className: "seekora-suggestions-product-card-image", enableZoom: enableImageZoom, zoomMode: imageZoomMode, zoomLevel: imageZoomLevel })) : (React.createElement("div", { className: "seekora-suggestions-product-card-placeholder", "aria-hidden": true })),
            React.createElement("span", { className: "seekora-suggestions-product-card-title" }, title),
            price != null && !Number.isNaN(price) ? (React.createElement("span", { className: "seekora-suggestions-product-card-price" },
                product.currency ?? "$",
                price.toFixed(2))) : null));
    }
    // Enhanced layout with displayConfig
    const layoutStyle = displayConfig.style ?? "minimal";
    const comparePrice = effectiveComparePrice;
    const brand = product.brand ?? null;
    const options = product.options ?? [];
    const variants = product.variants ?? [];
    const badges = useMemo(() => {
        if (displayConfig.showBadges === false)
            return [];
        if (displayConfig.badgeExtractor)
            return displayConfig.badgeExtractor(product.tags, product);
        return extractBadges(product.tags, product);
    }, [displayConfig, product]);
    const priceRange = useMemo(() => {
        if (!displayConfig.showPriceRange)
            return null;
        return getPriceRange(product.variants);
    }, [displayConfig.showPriceRange, product.variants]);
    const layoutProps = {
        product,
        images,
        title,
        price,
        comparePrice,
        brand,
        badges,
        priceRange,
        options,
        variants,
        displayConfig,
        imageVariant,
        onVariantHover,
        onVariantClick,
        selectedVariants,
        actionButtons,
        actionButtonsPosition,
        showActionLabels,
        enableImageZoom,
        imageZoomMode,
        imageZoomLevel,
    };
    const layoutMap = {
        minimal: MinimalLayout,
        standard: StandardLayout,
        detailed: DetailedLayout,
        compact: CompactLayout,
        horizontal: HorizontalLayout,
    };
    const LayoutComponent = layoutMap[layoutStyle] ?? MinimalLayout;
    const rootClassName = clsx("seekora-product-card", `seekora-product-card--${layoutStyle}`, "seekora-suggestions-product-card", isHovered && "seekora-product-card--hover", className);
    const rootStyle = { ...style };
    if (asLink && product.url) {
        return (React.createElement("a", { ref: trackerRef, href: product.url, className: rootClassName, style: rootStyle, onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false), onClick: (e) => {
                trackedOnClick();
            }, "data-layout": layoutStyle, "data-position": position, "data-section": section, "data-tab-id": tabId },
            React.createElement(LayoutComponent, { ...layoutProps })));
    }
    return (React.createElement("div", { ref: trackerRef, role: "button", tabIndex: 0, className: rootClassName, style: rootStyle, onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false), onClick: trackedOnClick, onKeyDown: (e) => {
            if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                trackedOnClick();
            }
        }, "data-layout": layoutStyle, "data-position": position, "data-section": section, "data-tab-id": tabId },
        React.createElement(LayoutComponent, { ...layoutProps })));
}
