"use client"

import { useCallback, useEffect, useState, type ReactNode } from "react"
import { DocsLoadingSplash } from "@/components/drive/richtext/docs-loading-splash"
import {
  resolveDocsShellSplashPhase,
  type DocsLoadingPhase,
} from "@/lib/drive/docs-loading-phase"

export function useDocsEditorLoadingState(
  resetKey?: string | null,
  initialPhase: DocsLoadingPhase = "connecting"
) {
  const [documentLoading, setDocumentLoading] = useState(true)
  const [documentPhase, setDocumentPhase] = useState<DocsLoadingPhase>(initialPhase)

  useEffect(() => {
    setDocumentLoading(true)
    setDocumentPhase(initialPhase)
  }, [resetKey, initialPhase])

  const onDocumentLoadingChange = useCallback((loading: boolean, phase?: DocsLoadingPhase) => {
    setDocumentLoading(loading)
    if (phase) setDocumentPhase(phase)
  }, [])

  return { documentLoading, documentPhase, onDocumentLoadingChange }
}

export function DocsEditorLoadingShell({
  title,
  resolvingFile,
  awaitingSession,
  documentLoading,
  documentPhase,
  error,
  children,
}: {
  title?: string
  resolvingFile: boolean
  awaitingSession: boolean
  documentLoading: boolean
  documentPhase: DocsLoadingPhase
  error?: ReactNode
  children?: ReactNode
}) {
  const showSplash = resolvingFile || awaitingSession || documentLoading
  const splashPhase = resolveDocsShellSplashPhase({
    resolvingFile,
    awaitingSession,
    documentPhase,
  })

  return (
    <div className="relative flex h-dvh min-h-0 flex-col">
      {children}
      {showSplash && !error ? (
        <DocsLoadingSplash phase={splashPhase} title={title} overlay />
      ) : null}
      {error}
    </div>
  )
}
