import type { CatalogProduct } from '../components/CatalogProductCard';
import { isVariantAvailable } from './variantStock';
import { SITE_URL } from './seo';
import { productVariantUrl } from './productOffer';

// Same-store campaigns stay local; unsupported protocols are never rendered.
export function heroLink(value: string): string {
  try {
    const url = new URL(value, SITE_URL);
    if (!['https:', 'http:'].includes(url.protocol)) return '/#vune';
    if ([new URL(SITE_URL).hostname, `www.${new URL(SITE_URL).hostname}`].includes(url.hostname)) return `${url.pathname}${url.search}${url.hash}`;
    return url.href;
  } catch { return '/#vune'; }
}

export function getHeroOffer(link: string, products: CatalogProduct[]) {
  const href = heroLink(link);
  const product = products.find((item) => href.split('?')[0].split('#')[0] === `/product/${item.slug}`);
  if (!product) return null;
  const available = product.variants.filter((variant) => isVariantAvailable(variant, product.stock)
    && Number.isFinite(Number(variant.currentPrice)) && Number(variant.currentPrice) > 0);
  const cheapest = [...available].sort((a, b) => Number(a.currentPrice) - Number(b.currentPrice))[0];
  if (!cheapest) return null;
  return { product, price: Number(cheapest.currentPrice), href: heroLink(productVariantUrl(product.slug, cheapest)) };
}
