---
import BaseLayout from '../layouts/BaseLayout.astro';
import { fetchPageByPermalink, fetchSiteGlobals, fetchNavigation, fetchGeneratedArticleBySlug } from '../lib/directus/fetchers';
import BlockRenderer from '@/components/engine/BlockRenderer';

const siteId = Astro.locals.siteId;
const slug = Astro.params.slug || '';
const permalink = '/' + slug;

// Safety check for siteId
if (!siteId) {
    // If we can't determine the site (domain not found), 404 or show generic
    // Actually, middleware might have failed or domain is unknown.
    // For now, render 404.
    return Astro.redirect('/404'); 
}

// Fetch data
const [globals, navigation, page, generatedArticle] = await Promise.all([
  fetchSiteGlobals(siteId),
  fetchNavigation(siteId),
  fetchPageByPermalink(permalink, siteId),
  fetchGeneratedArticleBySlug(slug, siteId)
]);

if (!page && !generatedArticle) {
  // Try home page if slug matches site root? 
  // params.slug is '' for root? No, [...slug] matches root if configured?
  // Astro [...slug] matches undefined for root if defined as such?
  // Let's assume permalink handles root.
  return Astro.redirect('/404');
}

const activeEntity = page || generatedArticle;
const isGenerated = !!generatedArticle && !page;

// Determine blocks
const blocks = page?.blocks || [];
// If legacy content field exists and blocks are empty, maybe create a fake content block?
if (page && (!blocks || blocks.length === 0) && page.content) {
    blocks.push({
        id: 'legacy-content',
        block_type: 'content',
        block_config: { content: page.content }
    });
}
---

<BaseLayout 
  title={activeEntity.seo_title || activeEntity.title || activeEntity.headline}
  description={activeEntity.seo_description}
  image={activeEntity.seo_image}
  globals={globals}
  navigation={navigation}
  schemaJson={activeEntity.schema_json}
>
  {isGenerated ? (
    <article class="prose dark:prose-invert max-w-none container mx-auto px-4 py-8">
      <h1 class="text-4xl font-bold mb-6">{activeEntity.title}</h1>
      <div set:html={activeEntity.html_content} />
    </article>
  ) : (
    <BlockRenderer blocks={blocks} />
  )}
</BaseLayout>
