'use client';

import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';
import Sidebar from './Sidebar';
import Topbar from './Topbar';
// import ChargeDrawer from '../components/features/charge-drawer';
// import SubscribeVipDrawer from '@/app/(main)/vip/components/SubscribeVipDrawer';
import { cn } from '@/lib/utils';
// import CreateReachedLimitDialog from '../components/features/create-reached-limit-dialog';
import BottomBar from './BottomBar';
import { useStreamChatStore } from '@/app/(main)/chat/[id]/stream-chat';
import { useCurrentUser } from '@/hooks/auth';
import { useLayoutStore } from '@/stores';

interface ConditionalLayoutProps {
  children: React.ReactNode;
}

// 初始化聊天
const useInitChat = () => {
  const { data } = useCurrentUser();
  const connect = useStreamChatStore((state) => state.connect);

  useEffect(() => {
    if (data) {
      connect({
        userId: data.userId + '',
        userName: data.nickname,
      });
    }
  }, [data]);
};

// 路由切换时重置滚动位置
const useAutoScrollOnRouteChange = (ref: React.RefObject<HTMLDivElement | null>) => {
  const pathname = usePathname();
  const prevPathnameRef = useRef<string>(pathname);
  // 路由切换时重置滚动位置
  useEffect(() => {
    if (prevPathnameRef.current !== pathname) {
      if (ref.current) {
        ref.current.scrollTop = 0;
      }
      prevPathnameRef.current = pathname;
    }
  }, [pathname]);
};

export default function ConditionalLayout({ children }: ConditionalLayoutProps) {
  const mainContentRef = useRef<HTMLDivElement>(null);
  const response = useLayoutStore((s) => s.response);

  useInitChat();
  useAutoScrollOnRouteChange(mainContentRef);

  return (
    <div className="flex h-screen w-screen bg-[url('/common-bg.png')] bg-[length:100%_30%] bg-top bg-no-repeat overflow-hidden">
      {response?.isPC && <Sidebar />}
      <div ref={mainContentRef} className={cn('relative flex w-full flex-1 flex-col min-w-0')}>
        <Topbar />
        <main id="main-content" className="overflow-auto w-full flex-1 min-w-0">
          {children}
        </main>
        {response?.isMobile && <BottomBar />}
      </div>
      {/* <ChargeDrawer /> */}
      {/* <SubscribeVipDrawer /> */}
      {/* <CreateReachedLimitDialog /> */}
    </div>
  );
}
