"use client";

import { useMemo, useState } from "react";
import { usePreferredSidebarDocumentTitle } from "@/components/sidebar/preferred-sidebar-snapshot-context";

function normalizePageHeadTitle(title: string | null | undefined): string {
  const normalized = String(title ?? "").trim();
  return normalized || "无标题";
}

export function usePageHeadTitle(input: { documentId: string; fallbackTitle: string }) {
  const liveSidebarTitle = usePreferredSidebarDocumentTitle(input.documentId);
  const committedTitle = useMemo(
    () => normalizePageHeadTitle(liveSidebarTitle ?? input.fallbackTitle),
    [input.fallbackTitle, liveSidebarTitle],
  );
  const [draftState, setDraftState] = useState<{
    documentId: string;
    title: string | null;
  }>({
    documentId: input.documentId,
    title: null,
  });
  const draftTitle = draftState.documentId === input.documentId ? draftState.title : null;
  const hasDraft = draftTitle != null && normalizePageHeadTitle(draftTitle) !== committedTitle;

  return {
    displayTitle: hasDraft ? draftTitle ?? committedTitle : committedTitle,
    committedTitle,
    hasDraft,
    setDraftTitle: (title: string) => {
      setDraftState({
        documentId: input.documentId,
        title,
      });
    },
    commitPersistedTitle: (title: string) => {
      setDraftState({
        documentId: input.documentId,
        title: normalizePageHeadTitle(title),
      });
    },
  };
}
