function num(v) {
    const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
    return Number.isFinite(n) ? n : undefined;
}
function money(amount, currencyCode) {
    return {
        amount: String(amount ?? "0"),
        currencyCode: String(currencyCode ?? "USD"),
    };
}
/**
 * Adapt a raw search-result item to the HydrogenProduct shape theme cards
 * consume. Reads the Storefront-API-aligned document the Shopify connector v2
 * syncs (GID id, priceRange MoneyV2, featuredImage, media). Falls back to the
 * item root and to a media[0].image when featuredImage is absent.
 */
export function toHydrogenProduct(item) {
    const doc = (item && item.document) || item || {};
    const fi = doc.featuredImage ||
        (Array.isArray(doc.media) ? doc.media[0]?.image : undefined) ||
        (typeof doc.image === "string" && doc.image
            ? { url: doc.image }
            : undefined) ||
        (Array.isArray(doc.images) && doc.images[0]
            ? { url: doc.images[0] }
            : undefined);
    const pr = doc.priceRange || {};
    const cmp = doc.compareAtPriceRange?.minVariantCompareAtPrice;
    // Derive product-level currency code for wrapping variant scalar prices.
    const productCurrency = String(pr.minVariantPrice?.currencyCode ?? "USD") || "USD";
    // Map raw connector variant objects to HydrogenVariant shape.
    let variants;
    let productAvailableForSale;
    if (Array.isArray(doc.variants) && doc.variants.length > 0) {
        // The connector delivers variants doubly nested: [[v1, v2]] or [[v1],[v2]].
        // Flatten one level so both flat [v] and nested [[v]] inputs are handled.
        const flatVariants = doc.variants
            .flat()
            .filter((v) => v && typeof v === "object" && !Array.isArray(v));
        const mapped = flatVariants.map((v) => {
            // availableForSale: prefer explicit boolean; fall back to inventoryQuantity.
            let avail;
            if (typeof v.availableForSale === "boolean") {
                avail = v.availableForSale;
            }
            else if (typeof v.inventoryQuantity === "number") {
                avail = v.inventoryQuantity > 0;
            }
            else {
                avail = true;
            }
            const variant = {
                id: String(v.id),
                availableForSale: avail,
            };
            if (v.title != null) {
                variant.title = String(v.title);
            }
            if (v.price != null) {
                variant.price = {
                    amount: String(v.price),
                    currencyCode: productCurrency,
                };
            }
            if (Array.isArray(v.selectedOptions)) {
                variant.selectedOptions = v.selectedOptions;
            }
            return variant;
        });
        variants = mapped.length > 0 ? mapped : undefined;
        productAvailableForSale =
            mapped.length > 0 ? mapped.some((v) => v.availableForSale) : undefined;
    }
    return {
        id: String(item?.id ?? doc.id ?? ""),
        handle: String(doc.handle ??
            (typeof doc.url === "string"
                ? doc.url.replace(/^\/+products\/+/, "").replace(/[?#].*$/, "")
                : "")),
        title: String(doc.title ?? doc.name ?? ""),
        vendor: doc.vendor,
        featuredImage: fi
            ? {
                url: String(fi.url ?? fi.src ?? ""),
                altText: fi.altText ?? fi.alt ?? doc.title ?? null,
                width: num(fi.width),
                height: num(fi.height),
            }
            : null,
        priceRange: {
            minVariantPrice: money(pr.minVariantPrice?.amount ?? doc.price, pr.minVariantPrice?.currencyCode ?? doc.currencyCode ?? doc.currency),
            maxVariantPrice: pr.maxVariantPrice
                ? money(pr.maxVariantPrice.amount, pr.maxVariantPrice.currencyCode)
                : undefined,
        },
        compareAtPriceRange: cmp
            ? { minVariantCompareAtPrice: money(cmp.amount, cmp.currencyCode) }
            : undefined,
        variants,
        availableForSale: productAvailableForSale,
    };
}
