import { graphql } from "@/gql";
import { type StudioFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { PageContent } from "@/components/general/PageContent";
import { BgPig } from "@/components/general/BgPig";
import { StudioHeader } from "@/components/studio/StudioHeader";
import styles from "@/components/studio/studioPageContent.module.scss";

const StudioFragmentDefinition = graphql(`
  fragment Studio on StudioPage {
    __typename
    id
    title
    seoTitle
    searchDescription
    lead
    pig
    logo {
      url
      width
      height
      alt
    }
    body {
      ...Blocks
    }
  }
`);

const studioPageQuery = graphql(`
  query studio {
    page: studioPage {
      ... on StudioPage {
        ...Studio
      }
    }
  }
`);

export type StudioPageViewProps = { page: StudioFragment };

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

export function StudioPageView({ page }: StudioPageViewProps) {
  return (
    <>
      <main className="site-main" id="main">
        <StudioHeader title={page.title} lead={page.lead} />
        {page.body && <PageContent blocks={page.body} className={styles.studioBody} />}
      </main>
      {page.pig && <BgPig type={page.pig} color="white" />}
    </>
  );
}
