---
import Layout from "../layouts/Layout.astro";
import ContentRows from "../components/ContentRows.svelte";
import {
  getPageBySlug,
  getPages,
  fetchOpenApi,
  getHomePageSlugFromConfig,
} from "../lib/cms";
import type { PageEntry } from "../lib/cms";
import { resolveContentImages } from "../lib/rusty-image";
import {
  resolvePostOverviewBlocks,
  resolveSearchableTextBlocks,
  resolveCalendarBlocks,
} from "../lib/blog-utils";
import {
  DEFAULT_HOME_PAGE_SLUG,
  PAGE_RESOLVE,
} from "../lib/constants";

let page: PageEntry | null = null;
let cmsError: string | null = null;
let openApiTitle = "RustyCMS API";
let pages: PageEntry[] = [];

try {
  const homeSlug =
    (await getHomePageSlugFromConfig({ locale: "de" })) ??
    DEFAULT_HOME_PAGE_SLUG;
  const [spec, homePage, allPages] = await Promise.all([
    fetchOpenApi().catch(() => ({ info: { title: openApiTitle } })),
    getPageBySlug(homeSlug, { locale: "de", resolve: PAGE_RESOLVE }),
    getPages(),
  ]);
  openApiTitle = (spec.info?.title as string) ?? openApiTitle;
  page = homePage;
  pages = allPages ?? [];
  if (page) {
    await resolveContentImages(page);
    const tagsMap = await resolvePostOverviewBlocks(page);
    await resolveSearchableTextBlocks(page, tagsMap);
    await resolveCalendarBlocks(page);
  }
} catch (e) {
  cmsError = e instanceof Error ? e.message : String(e);
}
const translations = Astro.locals.translations ?? {};
---

{
  page ? (
    <Layout
      title={page.seoTitle ?? page.headline ?? page.linkName ?? "Startseite"}
      description={page.seoDescription ?? page.subheadline}
      headline={page.headline ?? page.linkName ?? page.slug ?? page._slug}
      subheadline={page.subheadline}
      topFullwidthBanner={page.topFullwidthBanner}
      showBannerInLayout={!!page.topFullwidthBanner}
    >
      <article>
        <ContentRows client:load layout={page} class="mt-8" translations={translations} />
      </article>
    </Layout>
  ) : (
    <Layout title="RustyAstro – Pages" description="Pages aus RustyCMS">
      <div class="mb-6 pt-10 pageTitle">
        <h1>Pages</h1>
        <h2>
          Schema von <strong>{openApiTitle}</strong> (OpenAPI).
        </h2>
      </div>
      <div class="content mt-8">
        {cmsError && (
          <div class="mt-6 rounded-sm border border-amber-200 bg-amber-50 p-4 text-amber-800">
            <strong>CMS nicht erreichbar:</strong> {cmsError}
          </div>
        )}
        {!cmsError && (
          <p class="mt-6 text-zinc-600">
            Startseite „{DEFAULT_HOME_PAGE_SLUG}“ nicht gefunden. RustyCMS unter{" "}
            <code class="rounded bg-zinc-200 px-1">PUBLIC_CMS_URL</code> starten
            und{" "}
            <code class="rounded bg-zinc-200 px-1">
              content/page/{DEFAULT_HOME_PAGE_SLUG}.json5
            </code>{" "}
            anlegen – oder eine der folgenden Pages verwenden:
          </p>
        )}
        <ul class="space-y-3 mt-4">
          {pages.map((p) => (
            <li>
              <a
                href={`/${encodeURIComponent((p.slug ?? p._slug ?? "").replace(/^\//, "").trim() || "")}`}
                class="block rounded-sm border border-zinc-200 bg-white px-4 py-3 shadow-sm transition hover:border-green-700/30 hover:shadow"
              >
                <span class="font-medium text-zinc-900">
                  {p.linkName ?? p.name ?? p.slug ?? p._slug}
                </span>
                {p.headline && (
                  <span class="mt-1 block text-sm text-zinc-500">
                    {p.headline}
                  </span>
                )}
              </a>
            </li>
          ))}
        </ul>
      </div>
    </Layout>
  )
}
