import { graphql } from "@/gql";
import { EventFragment, HomeFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { FeaturedEvents } from "@/components/events/FeaturedEvents";
import { NewsList } from "@/components/news/NewsList";
import { UpcomingEvents } from "@/components/events/UpcomingEvents";
import { IconListBlock } from "@/components/blocks/IconListBlock";
import { FeaturedBlock } from "@/components/blocks/FeaturedBlock";

const HomeFragmentDefinition = graphql(`
  fragment Home on HomePage {
    ... on HomePage {
      featuredEvents {
        id
      }
    }
  }
`);

export default async function Home() {
  const homeQuery = graphql(`
    query home {
      events: eventIndex {
        ... on EventIndex {
          futureEvents {
            ... on EventPage {
              ...Event
            }
          }
        }
      }
      home: page(contentType: "home.HomePage", urlPath: "/home/") {
        ... on HomePage {
          ...Home
        }
      }
    }
  `);
  const { data, error } = await getClient().query(homeQuery, {});
  const events = (data?.events?.futureEvents ?? []) as EventFragment[];
  const home = (data?.home ?? []) as HomeFragment;

  const featuredEventIds = home.featuredEvents.map((x) => x.id);
  const featuredEvents = [
    ...events.filter((x) => featuredEventIds.includes(x.id)),
    ...events.filter((x) => !featuredEventIds.includes(x.id)),
  ];

  return (
    <main className="site-main index" id="main">
      <FeaturedEvents events={featuredEvents} />
      <UpcomingEvents events={events} />
      <NewsList heading="Siste nytt" limit={3} featured />
      <blockquote>«Hvor Glæden hersker, er alltid Fest»</blockquote>
      <IconListBlock />
      <FeaturedBlock />
      <FeaturedBlock />
    </main>
  );
}
