"use client"

import { useLayoutEffect } from "react"
import { useQueryClient } from "@tanstack/react-query"
import {
  DEMO_MAIL_ACCOUNT,
  DEMO_MAIL_ACCOUNT_ID,
} from "@/lib/demo/demo-mail-api-data"
import { DEMO_EMAILS, DEMO_USER } from "@/components/demo/demo-mail-data"
import { useDemoMailStore } from "@/lib/demo/demo-mail-store"
import { useAccountStore } from "@/lib/stores/account-store"
import { useComposeIdentitiesStore } from "@/lib/stores/compose-identities-store"
import { useNavStore } from "@/lib/stores/nav-store"
import { useMailStore } from "@/lib/stores/mail-store"
import {
  DEMO_MAIL_FOLDER_TREE,
  DEMO_MAIL_LABEL_ROWS,
} from "@/lib/demo/demo-mail-nav-data"
import { useSessionGuardStore } from "@/lib/auth/session-guard-store"
import { DEMO_MAIL_MESSAGES_QUERY_ROOT } from "@/lib/api/hooks/use-mail-queries"

const DEMO_EMAIL_IDS = new Set(DEMO_EMAILS.map((email) => email.id))

/** Hydrate local stores for the interactive mail demo (no backend). */
export function DemoMailBootstrap() {
  const queryClient = useQueryClient()

  useLayoutEffect(() => {
    useSessionGuardStore.getState().clear()
    useDemoMailStore.getState().reset()

    const seenEmailIds = useMailStore.getState().seenEmailIds
    if (seenEmailIds.some((id) => DEMO_EMAIL_IDS.has(id))) {
      useMailStore.setState({
        seenEmailIds: seenEmailIds.filter((id) => !DEMO_EMAIL_IDS.has(id)),
      })
    }

    queryClient.removeQueries({ queryKey: DEMO_MAIL_MESSAGES_QUERY_ROOT })
    queryClient.removeQueries({ queryKey: ['demo', 'mail-search'] })
    queryClient.removeQueries({ queryKey: ['demo', 'message'] })
    queryClient.removeQueries({ queryKey: ['demo', 'thread'] })

    useAccountStore.getState().setActiveAccountId(DEMO_MAIL_ACCOUNT_ID)
    useComposeIdentitiesStore.getState().hydrateFromApi([
      {
        id: "demo-compose-identity",
        accountId: DEMO_MAIL_ACCOUNT_ID,
        name: DEMO_USER.name,
        email: DEMO_USER.email,
        defaultSignatureId: null,
        signatureHtml: null,
        isDefault: true,
      },
    ])
    useNavStore.getState().hydrateFolderTreeFromApi(DEMO_MAIL_FOLDER_TREE)
    useNavStore.getState().hydrateLabelRowsFromApi(DEMO_MAIL_LABEL_ROWS)
  }, [queryClient])

  return null
}

export { DEMO_MAIL_ACCOUNT, DEMO_MAIL_ACCOUNT_ID }
