import { MindmapLabClient } from './mindmap-lab-client';
import { normalizeSnapshot } from '@/lib/mindmap/snapshot';
import { DEFAULT_MINDMAP_SNAPSHOT, type MindmapSnapshot } from '@/types/mindmap';
import { createSupabaseServerClient } from '@/lib/supabase/server';

type MindmapLabPageProps = {
  searchParams?: {
    documentId?: string;
  };
};

export default async function MindmapLabPage({
  searchParams,
}: MindmapLabPageProps) {
  const documentId =
    typeof searchParams?.documentId === 'string'
      ? searchParams.documentId
      : null;

  let initialData: MindmapSnapshot = DEFAULT_MINDMAP_SNAPSHOT;
  let documentTitle: string | null = documentId ? null : '思维导图实验室';

  if (documentId) {
    try {
      const supabase = await createSupabaseServerClient();
      const { data, error } = await supabase
        .from('documents')
        .select('mindmap_data,title')
        .eq('id', documentId)
        .maybeSingle();

      if (error) {
        console.error('加载 mindmap_data 失败', error);
      } else if (data?.mindmap_data) {
        initialData = normalizeSnapshot(data.mindmap_data);
        documentTitle = data.title ?? null;
      }
    } catch (error) {
      console.error('Supabase 查询失败', error);
    }
  }

  return (
    <div className="h-screen w-full bg-background">
      <MindmapLabClient
        initialDocumentId={documentId}
        initialData={initialData}
        documentTitle={documentTitle}
      />
    </div>
  );
}
