'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 { useMedia } from '@/hooks/tools';
import BottomBar from './BottomBar';

interface ConditionalLayoutProps {
  children: React.ReactNode;
}

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

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

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