"use client"

import { useEffect } from "react"
import { useAuthReady } from "@/lib/api/use-auth-ready"
import { useLabels } from "@/lib/api/hooks/use-folder-label-queries"
import { useUnifiedFolders } from "@/lib/api/hooks/use-unified-folder-queries"
import { useImapFolders } from "@/lib/api/hooks/use-imap-folders"
import { useMailSettings } from "@/lib/api/hooks/use-mail-settings"
import { useNavStore } from "@/lib/stores/nav-store"
import { buildFolderTreeFromUnified } from "@/lib/mail-settings/unified-folder-tree"
import { buildFolderTreeFromImap } from "@/lib/mail-settings/imap-folder-tree"
import { normalizeLabelRow } from "@/lib/sidebar-nav-data"
import type { LabelRowItem } from "@/lib/sidebar-nav-maps"

/** Hydrate sidebar navigation + display settings from backend when authenticated. */
export function MailNavSync() {
  const { ready, authenticated } = useAuthReady()
  const { data: labels } = useLabels()
  const { data: globalFolders } = useUnifiedFolders("global")
  const { data: allFolders } = useUnifiedFolders("all")
  const { folders: imapFolders, isFetched: imapFoldersFetched } = useImapFolders()
  useMailSettings(authenticated)

  useEffect(() => {
    if (!ready || !authenticated || !labels) return

    const sorted = [...labels].sort(
      (a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.name.localeCompare(b.name)
    )
    const apiRows: LabelRowItem[] = sorted.map((label) =>
      normalizeLabelRow({
        id: label.id,
        label: label.name,
        color: label.color || "bg-gray-500",
        tabbed: false,
        favorite: false,
        excludeFromPrincipal: false,
        showInMessageList: true,
        enabled: true,
      })
    )
    useNavStore.getState().hydrateLabelRowsFromApi(apiRows)
  }, [ready, authenticated, labels])

  useEffect(() => {
    if (!ready || !authenticated || !allFolders || !imapFoldersFetched) return

    const global = globalFolders ?? allFolders.filter((f) => f.scope === "global")
    const tree = [
      ...buildFolderTreeFromUnified(global),
      ...buildFolderTreeFromImap(imapFolders),
    ]
    if (tree.length === 0) return

    useNavStore.getState().hydrateFolderTreeFromApi(tree)
  }, [ready, authenticated, allFolders, globalFolders, imapFolders, imapFoldersFetched])

  return null
}
