(function installShowcaseFilter(scope) {
  function normalize(value) {
    return String(value ?? "").trim().toLocaleLowerCase("en");
  }

  function filterProducts(products, filters = {}) {
    const query = normalize(filters.query);
    const exactFilters = ["shape", "color", "clarity", "availability"];

    return products.filter((product) => {
      if (query) {
        const searchable = [product.product_id, product.name, product.shape, product.color, product.clarity]
          .map(normalize)
          .join(" ");
        if (!searchable.includes(query)) return false;
      }

      return exactFilters.every((field) => {
        const expected = normalize(filters[field]);
        return !expected || normalize(product[field]) === expected;
      });
    });
  }

  function buildProductPresentation(product, media, mission) {
    const mediaById = new Map(media.map((item) => [item.media_id, item]));
    const selectedMedia = product.media_ids
      .map((mediaId) => mediaById.get(mediaId))
      .filter((item) => item && item.missions.includes(mission.id));
    return { cta: mission.cta, media: selectedMedia };
  }

  scope.ZenityXShowcaseFilter = Object.freeze({ buildProductPresentation, filterProducts });
})(globalThis);
