---
import Layout from "../../layouts/Layout.astro";
import ContentRows from "../../components/ContentRows.svelte";
import Tag from "../../components/Tag.svelte";
import Tags from "../../components/Tags.svelte";
import EventBadges from "../../components/EventBadges.svelte";
import EventMap from "../../components/EventMap.svelte";
import Accordion from "../../components/Accordion.svelte";
import {
  getPostSlugs,
  getPostBySlug,
  getPageConfigBySlug,
  getPageConfigs,
} from "../../lib/cms";
import type { PostEntry } from "../../lib/cms";
import {
  resolveContentImages,
  resolveBodyContent,
  ensureTransformedImage,
} from "../../lib/rusty-image";
import {
  resolvePostTagsInPost,
  resolvePostOverviewBlocks,
  resolveSearchableTextBlocks,
  getPostImageUrl,
  formatPostDate,
} from "../../lib/blog-utils";
import { POST_RESOLVE } from "../../lib/constants";
import { T, t } from "../../lib/translations";

export const prerender = true;

export async function getStaticPaths() {
  try {
    const postSlugs = await getPostSlugs();
    const paths = (postSlugs ?? [])
      .map((s) => (s ?? "").trim())
      .filter(Boolean)
      .filter((slug, i, arr) => arr.indexOf(slug) === i)
      .map((slug) => ({ params: { slug } }));
    return paths;
  } catch (e) {
    console.error("getStaticPaths (post/[slug]):", e);
    return [];
  }
}

const { slug } = Astro.params as { slug: string };
const post = await getPostBySlug(slug, {
  locale: "de",
  resolve: POST_RESOLVE,
});

if (!post) {
  return Astro.redirect("/404");
}

await resolveContentImages(post);
const tagsMap = await resolvePostOverviewBlocks(post);
await resolveSearchableTextBlocks(post, tagsMap);
resolvePostTagsInPost(post, tagsMap);

const rawPostImageUrl = getPostImageUrl(post.postImage);
const postImageUrl = rawPostImageUrl
  ? await ensureTransformedImage(rawPostImageUrl, {
      width: 150,
      height: 200,
      fit: "cover",
    })
  : null;

const postDate = formatPostDate(post.created ?? post.date);

const isEvent = !!(post as { isEvent?: boolean }).isEvent;
const eventDateRaw = (post as { eventDate?: string }).eventDate;
const eventDateLabel =
  isEvent && eventDateRaw
    ? new Date(eventDateRaw).toLocaleDateString("de-DE", {
        weekday: "long",
        day: "2-digit",
        month: "long",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      })
    : null;
const eventLocation = isEvent
  ? (post as { eventLocation?: { text?: string; lat?: number; lng?: number } })
      .eventLocation
  : null;

const hasCoords = !!(eventLocation?.lat && eventLocation?.lng);
const _lat = eventLocation?.lat ?? 0;
const _lng = eventLocation?.lng ?? 0;
const mapEmbedUrl = hasCoords
  ? `https://www.openstreetmap.org/export/embed.html?bbox=${_lng - 0.01},${_lat - 0.007},${_lng + 0.01},${_lat + 0.007}&layer=mapnik&marker=${_lat},${_lng}`
  : null;
const mapLinkUrl = hasCoords
  ? `https://www.openstreetmap.org/?mlat=${eventLocation!.lat}&mlon=${eventLocation!.lng}#map=15/${eventLocation!.lat}/${eventLocation!.lng}`
  : eventLocation?.text
    ? `https://www.openstreetmap.org/search?query=${encodeURIComponent(eventLocation.text)}`
    : null;

const contentHtml = await resolveBodyContent(post as { content?: unknown });
const hasRowContent =
  ((post as { row1Content?: unknown[] }).row1Content?.length ?? 0) > 0 ||
  ((post as { row2Content?: unknown[] }).row2Content?.length ?? 0) > 0 ||
  ((post as { row3Content?: unknown[] }).row3Content?.length ?? 0) > 0;
const translations = Astro.locals.translations ?? {};

const pageConfig =
  (await getPageConfigBySlug("page-config-default", { locale: "de" })) ??
  (await getPageConfigs({ locale: "de", per_page: 1 }))[0] ??
  null;
const commentSlotRaw =
  (pageConfig as { postCommentSlot?: string } | null)?.postCommentSlot ?? "";
const commentSlot = commentSlotRaw
  .replace(/\{\{PAGE_ID\}\}/g, slug)
  .replace(/\{\{PAGE_URL\}\}/g, Astro.url.href)
  .replace(/\{\{PAGE_TITLE\}\}/g, post.headline ?? post.linkName ?? slug);
---

<Layout
  title={post.seoTitle ?? post.headline ?? post.linkName ?? slug}
  description={post.seoDescription ?? post.subheadline ?? post.excerpt}
  headline={post.headline ?? post.linkName ?? post.slug ?? post._slug}
  subheadline={post.subheadline}
  topFullwidthBanner={undefined}
  showBannerInLayout={false}
  image={postImageUrl ?? undefined}
  breadcrumbItems={[
    { href: "/", translationKey: T.nav_start },
    { href: "/posts/", translationKey: T.nav_posts },
    {
      label: post.headline ?? post.linkName ?? post.slug ?? post._slug ?? slug,
    },
  ]}
>
  {
    isEvent && (eventDateLabel || eventLocation?.text) && (
      <div class="mb-6">
        <EventBadges
          eventDate={eventDateRaw ?? null}
          locationText={eventLocation?.text ?? null}
          locationHref={(mapEmbedUrl || mapLinkUrl) ? "#map-section" : null}
        />
      </div>
    )
  }
  <div class="md:flex gap-2 items-end">
    {
      postImageUrl && (
        <div class="overflow-hidden inline-block my-4 border border-white self-start ring-1 ring-black/50 shadow-lg">
          <img
            src={postImageUrl}
            alt=""
            class="block object-cover"
            width="150"
            height="200"
            style="aspect-ratio: 1.3333"
            loading="eager"
          />
        </div>
      )
    }
    <div class="mt-2 mb-4! md:mb-1 min-w-0 gap-2">
      {
        postDate && (
          <div class="flex flex-nowrap gap-2 items-center shrink-0 mb-2">
            <Tag label={postDate} variant="date" />
          </div>
        )
      }
      <div
        class="flex flex-nowrap gap-2 items-center shrink-0 p-1 pb-4 -ml-1 overflow-x-auto overflow-y-hidden"
      >
        <Tags tags={post.postTag ?? []} variant="green" tagBase="/posts/tag" />
      </div>
    </div>
  </div>

  <article class="mt-8">
    {
      contentHtml && (
        <div
          class="content markdown max-w-none prose prose-zinc"
          set:html={contentHtml}
        />
      )
    }
    {
      hasRowContent && (
        <ContentRows client:load layout={post} translations={translations} />
      )
    }
  </article>

  {
    isEvent && (mapEmbedUrl || mapLinkUrl) && (
      <EventMap
        client:load
        embedUrl={mapEmbedUrl}
        linkUrl={mapLinkUrl}
        locationText={eventLocation?.text ?? null}
        label={t(translations, T.post_map)}
        translations={translations}
      />
    )
  }

  {
    (post as { showCommentSection?: boolean }).showCommentSection !== false &&
      commentSlot && (
        <Accordion label={t(translations, T.post_comments)} class="mt-6">
          <div
            class="p-8 border border-zinc-200 rounded-lg"
            set:html={commentSlot}
          />
        </Accordion>
      )
  }
</Layout>

