import Autoplay from 'embla-carousel-autoplay'
import useEmblaCarousel from 'embla-carousel-react'
import { Link, useRouteLoaderData } from 'react-router'

import type { loader } from '~/routes/_news'

export const Banner = () => {
  const loaderData = useRouteLoaderData<typeof loader>('routes/_news')
  const { adsData } = loaderData || {}
  const [emblaReference] = useEmblaCarousel({ loop: true }, [Autoplay()])

  return (
    <div className="">
      <div className="relative">
        <div
          className="embla overflow-hidden"
          ref={emblaReference}
        >
          <div className="embla__container flex">
            {adsData?.map(({ image_url: urlImage, url: link, id }, index) => (
              <div
                key={index}
                className="embla__slide max-h-[100px] min-h-[65px] w-full min-w-0 flex-none"
              >
                <Link
                  to={link}
                  className="mt-2 h-full py-2"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img
                    src={urlImage}
                    alt={id}
                    className="h-[70px] w-[100%] object-contain object-center sm:h-full"
                  />
                </Link>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
