"use client";

import { useQuery } from "@tanstack/react-query";
import Image from "next/image";

import { getLandingPageData } from "@/services/subscription.service";
import config from "@/utils/config";

import ImageWithFallback from "../../common/ImageWithFallback";

const defaultImage = config.APP_CONFIG.DEFAULT_IMG;

const storeLogos = [
  "apple",
  "lowes",
  "amazon",
  "best_buy",
  "ebay",
  "kohls",
  "walmart",
  "target",
  "chewy",
  "adidas",
  "sephora",
  "the_home_depot",
];

type FreeShippingStoresSectionProps = {
  publisher_domain?: string;
};

export default function FreeShippingStoresSection({
  publisher_domain = "",
}: FreeShippingStoresSectionProps) {
  const cdn = config.ENV_VARS.CDN_URL;

  const { data } = useQuery({
    queryKey: ["landingPage", publisher_domain],
    queryFn: () => getLandingPageData(publisher_domain),
  });

  const apiStores = Object.values(data?.popular_stores || {});

  return (
    <section className="py-5 section-stores" id="stores">
      <div className="container py-md-3 text-center">
        <h2 className="fw-bold section-title">Save at All Your Favorite Stores</h2>
        <p className="text-muted mb-5">
          Rebates.com automatically finds the best offers at over 10,000 stores.
        </p>
        <div className="row row-cols-2 row-cols-md-3 row-cols-lg-6 g-4 align-items-center justify-content-center">
          {apiStores.length > 0
            ? apiStores.map((store: any, index: number) => (
              <div key={index} className="col">
                <div className="store-pill">
                  <ImageWithFallback
                    src={store?.image_url || defaultImage}
                    alt={store?.brand_name || "store"}
                    width={120}
                    height={40}
                    className="store-logo"
                    fallback={store?.txt_img}
                  />
                </div>
              </div>
            ))
            : storeLogos.map((store) => (
              <div key={store} className="col">
                <div className="store-pill">
                  <Image
                    src={`${cdn}/assets/img/logos/${store}.svg`}
                    alt={store.replace(/_/g, " ")}
                    width={120}
                    height={40}
                    className="store-logo"
                  />
                </div>
              </div>
            ))}
        </div>
      </div>
    </section>
  );
}
