import { graphql } from "@/gql";
import { type SponsorFragment, type SponsorsPageFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { PageHeader } from "@/components/general/PageHeader";
import { PageContent } from "@/components/general/PageContent";
import { SponsorList } from "@/components/sponsor/SponsorList";

const SponsorsPageFragmentDefinition = graphql(`
  fragment SponsorsPage on SponsorsPage {
    __typename
    title
    seoTitle
    searchDescription
    lead
    body {
      ...Blocks
    }
    sponsors {
      ... on SponsorBlock {
        ...Sponsor
      }
    }
  }
`);

const sponsorsPageQuery = graphql(`
  query sponsors {
    page: sponsorsPage {
      ... on SponsorsPage {
        ...SponsorsPage
      }
    }
  }
`);

export type SponsorsPageViewProps = { page: SponsorsPageFragment };

export async function loadSponsorsPageProps(overrides?: {
  pageOverride?: SponsorsPageFragment;
}): Promise<SponsorsPageViewProps> {
  if (overrides?.pageOverride) {
    return { page: overrides.pageOverride };
  }
  const { data, error } = await getClient().query(sponsorsPageQuery, {});
  if (error) throw new Error(error.message);
  const page = data?.page as SponsorsPageFragment | undefined;
  if (!page) throw new Error("Failed to load /sponsorer");
  return { page };
}

export function SponsorsPageView({ page }: SponsorsPageViewProps) {
  return (
    <main className="site-main" id="main">
      <PageHeader heading={page.title} lead={page.lead} />
      {page.body && <PageContent blocks={page.body} />}
      {page.sponsors && (
        <SponsorList sponsors={page.sponsors as SponsorFragment[]} />
      )}
    </main>
  );
}
