"use client"

import { useEffect } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { useMailRoute } from "@/hooks/use-mail-route"
import { useMessage } from "@/lib/api/hooks/use-mail-queries"
import type { ApiMessageSummary } from "@/lib/api/types"
import { mailDocumentTitle } from "@/lib/suite/page-metadata"

function subjectFromListCache(
  queryClient: ReturnType<typeof useQueryClient>,
  messageId: string
): string | null {
  const entries = queryClient.getQueriesData<{ data?: ApiMessageSummary[] }>({
    queryKey: ["messages"],
  })
  for (const [, payload] of entries) {
    const hit = payload?.data?.find((m) => m.id === messageId)
    if (hit?.subject?.trim()) return hit.subject
  }
  return null
}

/** Sync tab title: « Boîte mail - Ultimail » or « Sujet… - Ultimail » when a message is open. */
export function MailDocumentTitle() {
  const { route } = useMailRoute()
  const queryClient = useQueryClient()
  const { data: message } = useMessage(route.mailId)

  useEffect(() => {
    const cachedSubject = route.mailId
      ? subjectFromListCache(queryClient, route.mailId)
      : null
    const subject = message?.subject ?? cachedSubject
    document.title = mailDocumentTitle(route.mailId ? subject : null)
  }, [route.mailId, message?.subject, queryClient])

  return null
}
