'use client'

import { usePathname } from 'next/navigation'
import { useEffect, useRef } from 'react'
import Sidebar from './Sidebar'
import Topbar from './Topbar'
import { NimChatProvider } from '@/context/NimChat'
import TopbarWithoutLogin from './TopBarWithoutLogin'
import ChargeDrawer from '../features/charge-drawer'
import SubscribeVipDrawer from '@/app/(main)/vip/components/SubscribeVipDrawer'
import { cn } from '@/lib/utils'
import CreateReachedLimitDialog from '../features/create-reached-limit-dialog'
import { useGlobalPrefetchRoutes } from '@/hooks/useGlobalPrefetchRoutes'

interface ConditionalLayoutProps {
  children: React.ReactNode
}

export default function ConditionalLayout({ children }: ConditionalLayoutProps) {
  const pathname = usePathname()
  const mainContentRef = useRef<HTMLDivElement>(null)
  const prevPathnameRef = useRef<string>(pathname)
  useGlobalPrefetchRoutes()

  // 路由切换时重置滚动位置
  useEffect(() => {
    if (prevPathnameRef.current !== pathname) {
      if (mainContentRef.current) {
        mainContentRef.current.scrollTop = 0
      }
      prevPathnameRef.current = pathname
    }
  }, [pathname])

  // 定义不需要主布局的路由（认证相关页面）
  const authRoutes = ['/login', '/register', '/auth', '/share']
  const isAuthRoute = authRoutes.some((route) => pathname.startsWith(route))

  const isWithLoginRoute = ['/about', '/policy'].some((route) => pathname.startsWith(route))

  // 如果是认证路由，直接返回 children（会使用各自的布局）
  if (isAuthRoute) {
    return <>{children}</>
  }

  if (isWithLoginRoute) {
    return (
      <div className="flex h-screen overflow-hidden bg-[url('/common-bg.png')] bg-cover bg-fixed bg-top bg-no-repeat">
        <div
          ref={mainContentRef}
          id="main-content"
          className="relative flex min-w-0 flex-1 flex-col overflow-auto"
        >
          <TopbarWithoutLogin />
          <main className="relative min-h-0 flex-1">{children}</main>
        </div>
      </div>
    )
  }

  // 其他路由使用主布局（包括首页、main路由组等）
  return (
    <NimChatProvider>
      {/* IM重连状态条 - 全局显示 */}
      {/* <IMReconnectStatusBar /> */}

      <div className="flex h-screen bg-[url('/common-bg.png')] bg-cover bg-fixed bg-top bg-no-repeat">
        <Sidebar />
        <div
          ref={mainContentRef}
          id="main-content"
          className={cn(
            'relative flex min-w-0 flex-1 flex-col overflow-auto',
            pathname.startsWith('/chat') && 'overflow-hidden'
          )}
        >
          <Topbar />
          <main className="min-h-0 flex-1 pt-16">{children}</main>
        </div>
        <ChargeDrawer />
        <SubscribeVipDrawer />
        <CreateReachedLimitDialog />
      </div>
    </NimChatProvider>
  )
}
