"use client";

import { createContext, useContext, useMemo, type ReactNode } from "react";
import type { DocumentRecord } from "@/lib/documents";
import type { SidebarInitialData } from "@/components/sidebar/types";

const PreferredSidebarSnapshotContext = createContext<SidebarInitialData | null>(null);

interface PreferredSidebarSnapshotProviderProps {
  data: SidebarInitialData;
  children: ReactNode;
}

export function PreferredSidebarSnapshotProvider({
  data,
  children,
}: PreferredSidebarSnapshotProviderProps) {
  return (
    <PreferredSidebarSnapshotContext.Provider value={data}>
      {children}
    </PreferredSidebarSnapshotContext.Provider>
  );
}

export function useOptionalPreferredSidebarSnapshotData() {
  return useContext(PreferredSidebarSnapshotContext);
}

export function usePreferredSidebarSnapshotData() {
  const context = useOptionalPreferredSidebarSnapshotData();
  if (!context) {
    throw new Error("usePreferredSidebarSnapshotData 必须在 PreferredSidebarSnapshotProvider 中使用");
  }
  return context;
}

export function usePreferredSidebarDocument(documentId: string): DocumentRecord | null {
  const snapshot = useOptionalPreferredSidebarSnapshotData();

  return useMemo(() => {
    if (!snapshot) {
      return null;
    }
    return snapshot.documents.find((item) => item.id === documentId) ?? null;
  }, [documentId, snapshot]);
}

export function usePreferredSidebarDocumentTitle(documentId: string): string | null {
  const document = usePreferredSidebarDocument(documentId);
  const title = document?.title?.trim();
  return title ? title : null;
}
