"use client";
import { graphql, unmaskFragment, type FragmentType } from "@/gql";
import { type ImageSliderBlockFragment } from "@/gql/graphql";
import { ImageFigure } from "@/components/general/Image";
import { ImageFragmentDefinition } from "@/lib/common";
import styles from "./imageSliderBlock.module.scss";

const ImageSliderItemFragmentDefinition = graphql(`
  fragment ImageSliderItem on ImageSliderItemBlock {
    image {
      ...Image
    }
    text
  }
`);

export const ImageSliderBlockFragmentDefinition = graphql(`
  fragment ImageSliderBlock on ImageSliderBlock {
    images {
      __typename
      ... on ImageSliderItemBlock {
        ...ImageSliderItem
      }
    }
  }
`);

// import swiper modules & styles
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination, Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import "./swiper.scss";

const Slide = ({
  item: maskedItem,
}: {
  item: FragmentType<typeof ImageSliderItemFragmentDefinition>;
}) => {
  const item = unmaskFragment(ImageSliderItemFragmentDefinition, maskedItem);
  const image = unmaskFragment(ImageFragmentDefinition, item.image);
  return (
    <ImageFigure
      key={image.id}
      src={image.url}
      alt={image.alt ?? ""}
      width={image.width}
      height={image.height}
      attribution={image.attribution}
      caption={item.text}
      sizes="100vw"
    />
  );
};

export const ImageSliderBlock = ({
  block,
  hero,
  pageContent,
}: {
  block: ImageSliderBlockFragment;
  hero?: boolean;
  pageContent?: boolean;
}) => {
  return (
    <div
      className={styles.imageSliderBlock}
      data-hero={hero}
      data-pagecontent={pageContent}
    >
      <Swiper
        pagination={{
          type: "fraction",
        }}
        navigation={true}
        modules={[Pagination, Navigation]}
        className="mySwiper"
      >
        {block.images?.map((item, index) => {
          if (item?.__typename !== "ImageSliderItemBlock") {
            return null;
          }
          return (
            <SwiperSlide key={index}>
              <Slide item={item} />
            </SwiperSlide>
          );
        })}
      </Swiper>
    </div>
  );
};
