// app/page_editor_admin/page.tsx
// Server component — loads Puck data, pre-fills dynamic component props from DB

// IMPORTANT: force-dynamic ensures the editor ALWAYS loads fresh data from the
// database on every visit. Without this, Next.js caches the page and the editor
// loads stale data after switching tabs or revisiting the URL.
export const dynamic = 'force-dynamic';
export const revalidate = 0;

import EditorClient from './editor-client';
import { getHomepageContent } from '@/lib/homepage-content';
import {
  getLatestAuthorData,
  getPrimaryAuthor,
  getAuthorInfo,
  getAllCategories,
} from '@/lib/utils/db';
import { getCustomPages } from '@/lib/custom-pages';
import { getAllNavigationItems } from '@/lib/navigation';

// Components that use DB data and need their sidebar fields pre-filled
const DYNAMIC_COMPONENTS = new Set([
  'AuthorProfile',
  'AuthorBox',
]);

/**
 * Fetch fresh DB data for dynamic components and merge into their props.
 * This ensures sidebar fields show real database values.
 */
async function prefillDynamicProps(puckData: any) {
  if (!puckData?.content) return puckData;

  // Fetch author data once (shared across author components)
  const authorData = await getLatestAuthorData();
  const primaryAuthor = await getPrimaryAuthor();
  const authorInfo = await getAuthorInfo(primaryAuthor) as Record<string, any> | null;

  const updatedContent = puckData.content.map((item: any) => {
    const { type, props } = item;

    if (type === 'AuthorProfile') {
      return {
        ...item,
        props: {
          ...props,
          authorName: authorData?.authorName || props.authorName || '',
          authorBio: authorData?.authorBio || props.authorBio || '',
          authorRole: authorData?.authorRole || props.authorRole || '',
          authorAvatar: authorData?.authorAvatar || props.authorAvatar || '',
          authorProfileUrl: authorData?.authorProfileUrl || props.authorProfileUrl || '',
          socialTwitter: authorData?.socialTwitter || props.socialTwitter || '',
          socialInstagram: authorData?.socialInstagram || props.socialInstagram || '',
          socialYoutube: authorData?.socialYoutube || props.socialYoutube || '',
          socialLinkedin: authorData?.socialLinkedin || props.socialLinkedin || '',
          socialWebsite: authorData?.socialWebsite || props.socialWebsite || '',
        },
      };
    }

    if (type === 'AuthorBox') {
      return {
        ...item,
        props: {
          ...props,
          authorSlug: primaryAuthor || props.authorSlug || '',
        },
      };
    }

    return item;
  });

  return { ...puckData, content: updatedContent };
}

export default async function EditorPage({ searchParams }: { searchParams: Promise<{ path?: string }> }) {
  const params = await searchParams;
  const currentPath = params?.path || '/';

  // Load current homepage data (always fresh from DB)
  const homepageData = await getHomepageContent(currentPath);

  // Pre-fill dynamic component sidebar fields with real DB data
  const prefilledPuckData = await prefillDynamicProps(homepageData.draftData);

  const categoriesDb = await getAllCategories();
  const categories = categoriesDb.map((c) => ({
    name: c.japanese,
    slug: c.slug,
  }));

  const customPagesDb = await getCustomPages();
  const customPagesList = customPagesDb.map((p) => ({
    id: p.id,
    title: p.title,
    path: p.slug.startsWith('/') ? p.slug : `/${p.slug}`,
    metaTitle: p.metaTitle || '',
    metaDescription: p.metaDescription || '',
    isCustom: true,
  }));

  const pages = [
    { title: 'Homepage', path: '/', isCustom: false },
    { title: 'About Us', path: '/about-us', isCustom: false },
    { title: 'Privacy Policy', path: '/privacy-policy', isCustom: false },
    ...customPagesList,
  ];

  const navigationItems = await getAllNavigationItems();

  // Render the Puck editor
  return (
    <EditorClient 
      key={currentPath}
      initialData={{ puckData: prefilledPuckData }} 
      categories={categories} 
      navigationItems={navigationItems}
      pages={pages}
      currentPath={currentPath}
    />
  );
}
