/**
 * ImageDisplay – configurable multi-image display (primitive)
 *
 * Variants: single, carousel, hover, thumbStrip, thumbList. Use in ItemCard,
 * ProductCard, ProductGallery. Overridable via className/style.
 */
import React, { useState, useEffect } from "react";
import { clsx } from "clsx";
import { Image as HydrogenImage } from "@shopify/hydrogen-react";
import { ensureSeekoraStyles } from "../../styles/inject";
import { ImageZoom } from "./ImageZoom";
import { useIsShopifyAvailable } from "../../hooks/useOptionalShopContext";
import { useIsMobile, useTouchTargetSize, useResponsiveGap, } from "../../utils/responsive";
/** True when the URL points at the Shopify image CDN. */
function isShopifyCdnUrl(url) {
    return typeof url === "string" && url.includes("cdn.shopify.com");
}
export function ImageDisplay({ images, variant = "single", alt = "", className, style, carouselAutoplay = false, carouselIntervalMs = 4000, enableZoom = false, zoomMode = "both", zoomLevel = 2.5, showDots = true, aspectRatio = "1/1", }) {
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    const [index, setIndex] = useState(0);
    const [hovering, setHovering] = useState(false);
    const safeImages = Array.isArray(images) ? images.filter(Boolean) : [];
    const current = safeImages[index] ?? safeImages[0];
    // Rules of Hooks: call unconditionally at the top. We branch on the
    // RESULT below (conditional render), never the hook call itself.
    const shopifyAvailable = useIsShopifyAvailable();
    // Responsive values
    const isMobile = useIsMobile();
    const arrowSize = useTouchTargetSize(32); // 44px on mobile, 32px on desktop
    const thumbSize = isMobile ? 56 : 48; // Larger thumbnails on mobile
    const responsiveGap = useResponsiveGap(8);
    /**
     * Render the inner image element. Uses hydrogen-react's `<Image>` (with
     * automatic srcSet generation + layout-shift prevention) when the URL is a
     * Shopify CDN URL AND a ShopifyProvider is mounted; otherwise falls back to
     * a bare `<img>` so non-Shopify platforms are unaffected. This is a plain
     * function returning JSX, not a hook — safe to call conditionally.
     */
    const renderImg = (props) => {
        const { src, altText, className: imgClassName, style: imgStyle } = props;
        if (shopifyAvailable && isShopifyCdnUrl(src)) {
            return (React.createElement(HydrogenImage, { data: { url: src, altText }, sizes: "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw", aspectRatio: aspectRatio, className: imgClassName, style: imgStyle, loading: "lazy" }));
        }
        return (React.createElement("img", { src: src, alt: altText, className: imgClassName, style: imgStyle, loading: "lazy" }));
    };
    if (safeImages.length === 0) {
        return (React.createElement("div", { className: clsx("seekora-img-display", "seekora-img-placeholder", className), style: style, "aria-hidden": true }));
    }
    if (variant === "single") {
        if (enableZoom) {
            return (React.createElement(ImageZoom, { src: safeImages[0], alt: alt, mode: zoomMode, zoomLevel: zoomLevel, images: safeImages, currentIndex: 0, className: clsx("seekora-img-display", "seekora-img-single", className), style: style }));
        }
        return renderImg({
            src: safeImages[0],
            altText: alt,
            className: clsx("seekora-img-display", "seekora-img-single", className),
            style,
        });
    }
    if (variant === "hover") {
        const showSecond = safeImages.length > 1 && hovering;
        const src = showSecond ? safeImages[1] : safeImages[0];
        // Pass only user-supplied objectFit / aspectRatio overrides inline
        const hoverImgOverride = style?.aspectRatio || style?.objectFit
            ? {
                ...(style.aspectRatio ? { aspectRatio: style.aspectRatio } : {}),
                ...(style.objectFit ? { objectFit: style.objectFit } : {}),
            }
            : undefined;
        if (enableZoom) {
            return (React.createElement("div", { className: clsx("seekora-img-display", "seekora-img-hover", className), style: style, onMouseEnter: () => setHovering(true), onMouseLeave: () => setHovering(false) },
                React.createElement(ImageZoom, { src: src, alt: alt, mode: zoomMode, zoomLevel: zoomLevel, images: safeImages, currentIndex: showSecond ? 1 : 0, className: "seekora-img-hover-img", style: hoverImgOverride })));
        }
        return (React.createElement("div", { className: clsx("seekora-img-display", "seekora-img-hover", className), style: style, onMouseEnter: () => setHovering(true), onMouseLeave: () => setHovering(false) }, renderImg({
            src,
            altText: alt,
            className: "seekora-img-hover-img",
            style: hoverImgOverride,
        })));
    }
    if (variant === "carousel") {
        const go = (delta) => {
            setIndex((i) => {
                const next = i + delta;
                if (next < 0)
                    return safeImages.length - 1;
                if (next >= safeImages.length)
                    return 0;
                return next;
            });
        };
        // Pass only user-supplied overrides inline
        const carouselImgOverride = style?.aspectRatio || style?.objectFit
            ? {
                ...(style.aspectRatio ? { aspectRatio: style.aspectRatio } : {}),
                ...(style.objectFit ? { objectFit: style.objectFit } : {}),
            }
            : undefined;
        const mobileAttr = isMobile ? "mobile" : "desktop";
        const mainImage = enableZoom ? (React.createElement(ImageZoom, { src: current, alt: alt, mode: zoomMode, zoomLevel: zoomLevel, images: safeImages, currentIndex: index, className: "seekora-img-carousel-main", style: carouselImgOverride })) : (renderImg({
            src: current,
            altText: alt,
            className: "seekora-img-carousel-main",
            style: carouselImgOverride,
        }));
        return (React.createElement("div", { className: clsx("seekora-img-display", "seekora-img-carousel", className), style: style },
            mainImage,
            safeImages.length > 1 && (React.createElement(React.Fragment, null,
                React.createElement("button", { type: "button", "aria-label": "Previous", className: "seekora-img-carousel-prev", "data-size": mobileAttr, onMouseDown: (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        go(-1);
                    }, onClick: (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                    } }, "\u2039"),
                React.createElement("button", { type: "button", "aria-label": "Next", className: "seekora-img-carousel-next", "data-size": mobileAttr, onMouseDown: (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        go(1);
                    }, onClick: (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                    } }, "\u203A"),
                showDots && (React.createElement("div", { className: "seekora-img-carousel-dots", "data-size": mobileAttr }, safeImages.map((_, i) => (React.createElement("button", { key: i, type: "button", "aria-label": `Go to image ${i + 1}`, className: "seekora-img-carousel-dot", "data-active": i === index ? "true" : "false", "data-size": mobileAttr, onMouseDown: (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                    }, onClick: (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        setIndex(i);
                    } })))))))));
    }
    if (variant === "thumbStrip" || variant === "thumbList") {
        const thumbMainOverride = style?.aspectRatio || style?.objectFit
            ? {
                ...(style.aspectRatio ? { aspectRatio: style.aspectRatio } : {}),
                ...(style.objectFit ? { objectFit: style.objectFit } : {}),
            }
            : undefined;
        const mobileAttr = isMobile ? "mobile" : "desktop";
        const mainImage = enableZoom ? (React.createElement(ImageZoom, { src: current, alt: alt, mode: zoomMode, zoomLevel: zoomLevel, images: safeImages, currentIndex: index, className: "seekora-img-thumb-main", style: thumbMainOverride })) : (renderImg({
            src: current,
            altText: alt,
            className: "seekora-img-thumb-main",
            style: thumbMainOverride,
        }));
        return (React.createElement("div", { className: clsx("seekora-img-display", "seekora-img-thumbstrip", className), style: responsiveGap !== 8
                ? {
                    ["--seekora-img-thumbstrip-gap"]: `${responsiveGap}px`,
                    ...style,
                }
                : style },
            mainImage,
            React.createElement("div", { className: "seekora-img-thumbs", "data-size": mobileAttr }, safeImages.map((src, i) => (React.createElement("button", { type: "button", key: i, className: clsx("seekora-img-thumb", i === index && "seekora-img-thumb--active"), "data-active": i === index ? "true" : "false", "data-size": mobileAttr, style: thumbSize !== 48
                    ? {
                        ["--seekora-img-thumb-size"]: `${thumbSize}px`,
                    }
                    : undefined, onMouseDown: (e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    setIndex(i);
                }, onClick: (e) => {
                    e.stopPropagation();
                    e.preventDefault();
                } }, renderImg({ src, altText: "" })))))));
    }
    return renderImg({
        src: current,
        altText: alt,
        className: clsx("seekora-img-display", className),
        style,
    });
}
