'use client';

import { useState, type ReactNode } from 'react';

import { cn } from '@/lib/utils';
import { MobileLayoutProvider } from './mobile-layout-provider';
import { MobileTopbar } from './mobile-topbar';
import { MobileBottomTabs } from './mobile-bottom-tabs';
import { MoreSheet } from './more-sheet';
import { MobileSearchOverlay } from '@/components/search/mobile-search-overlay';

/**
 * Mobile shell: fixed compact topbar + scrollable content + fixed bottom tab
 * bar. Mounted by AppShell when the viewport classifies as mobile - never
 * concurrent with the desktop tree. The bottom tabs and More sheet derive
 * the active port slug from the URL themselves, so this layout takes no
 * portSlug prop.
 */
export function MobileLayout({ children }: { children: ReactNode }) {
  const [moreOpen, setMoreOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  return (
    <div className="min-h-[100dvh] bg-background">
      <MobileLayoutProvider>
        <MobileTopbar />
        <main
          className={cn(
            'px-4 min-h-[100dvh]',
            // 56px topbar + safe-area + 16px breathing room
            'pt-[calc(56px+env(safe-area-inset-top)+1rem)]',
            // 56px tab bar + safe-area + 32px breathing room
            'pb-[calc(56px+env(safe-area-inset-bottom)+2rem)]',
          )}
        >
          {children}
        </main>
        <MobileBottomTabs
          onMoreClick={() => setMoreOpen(true)}
          onSearchClick={() => setSearchOpen(true)}
        />
        <MoreSheet open={moreOpen} onOpenChange={setMoreOpen} />
        <MobileSearchOverlay open={searchOpen} onOpenChange={setSearchOpen} />
      </MobileLayoutProvider>
    </div>
  );
}
