import { graphql, unmaskFragment } from "@/gql";
import { type ScheduleBlockFragment } from "@/gql/graphql";
import { RichText } from "@/components/general/RichText";
import styles from "./scheduleBlock.module.scss";

const ScheduleItemFragmentDefinition = graphql(`
  fragment ScheduleItem on ScheduleItemBlock {
    time
    scheduleItemTitle: title
    description
  }
`);

export const ScheduleBlockFragmentDefinition = graphql(`
  fragment ScheduleBlock on ScheduleBlock {
    scheduleTitle: title
    scheduleItems: items {
      __typename
      ... on ScheduleItemBlock {
        ...ScheduleItem
      }
    }
  }
`);

export const ScheduleBlock = ({
  block,
}: {
  block: ScheduleBlockFragment;
}) => {
  return (
    <section className={styles.schedule}>
      {block.scheduleTitle && (
        <h2 className={styles.heading}>{block.scheduleTitle}</h2>
      )}
      <dl className={styles.items}>
        {block.scheduleItems?.map((item, index) => {
          if (item?.__typename !== "ScheduleItemBlock") {
            return null;
          }
          const scheduleItem = unmaskFragment(
            ScheduleItemFragmentDefinition,
            item
          );
          return (
            <div key={index} className={styles.item}>
              <dt className={styles.time}>{scheduleItem.time}</dt>
              <dd className={styles.body}>
                <div className={styles.title}>
                  <RichText content={scheduleItem.scheduleItemTitle} />
                </div>
                {scheduleItem.description && (
                  <div className={styles.description}>
                    <RichText content={scheduleItem.description} />
                  </div>
                )}
              </dd>
            </div>
          );
        })}
      </dl>
    </section>
  );
};
