import React from 'react';
import { Outlet } from 'react-router-dom';
import { useAuth } from '@/contexts/useAuth';
import { useIsMobile } from '@/hooks/use-mobile';
import { useAppShell } from '@/business/app-shell/hooks';
import { GuestBanner } from '@/components/app-shell/GuestBanner';
import { AppFooter } from '@/components/app-shell/AppFooter';

import Sidebar from '@/components/frameworks/Sidebar';
import TopBar from '@/components/frameworks/TopBar';
import SignInModal from '@/components/frameworks/SignInModal';

import { Loader2 } from 'lucide-react';

const AppLayout: React.FC = () => {
  const { isAuthenticated, profile, loading: authLoading } = useAuth();
  const isMobile = useIsMobile();
  const {
    mobileOverlayVisible,
    sidebarProps,
    topBarProps,
    shellOutletContext,
    guestBannerProps,
    footerProps,
    signInModalProps,
    setMobileSidebarOpen,
  } = useAppShell({ isAuthenticated, profile, isMobile });

  // Loading state
  if (authLoading) {
    return (
      <div className="h-screen w-full flex items-center justify-center bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950">
        <div className="text-center">
          <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-violet-500 to-amber-400 flex items-center justify-center mx-auto mb-4 shadow-lg shadow-violet-500/30 animate-pulse">
            <span className="text-white font-bold text-2xl">F</span>
          </div>
          <Loader2 size={24} className="animate-spin text-violet-400 mx-auto mb-3" />
          <p className="text-slate-400 text-sm">Loading FRAMEworks...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen w-full flex bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 overflow-hidden">
      {/* Mobile sidebar overlay */}
      {mobileOverlayVisible && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-30" onClick={() => setMobileSidebarOpen(false)} />
      )}

      {/* Sidebar */}
      <div className={`${isMobile ? `fixed left-0 top-0 h-full z-40 transform transition-transform duration-300 ${mobileOverlayVisible ? 'translate-x-0' : '-translate-x-full'}` : 'relative'}`}>
        <Sidebar {...sidebarProps} />
      </div>


      {/* Main content area */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        <TopBar {...topBarProps} />

        <main className="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
          {!isAuthenticated && (
            <GuestBanner {...guestBannerProps} />
          )}

          <div className="max-w-7xl mx-auto">
            <Outlet context={shellOutletContext} />
          </div>

          <AppFooter {...footerProps} />
        </main>
      </div>

      {/* Sign In Modal */}
      <SignInModal {...signInModalProps} />
    </div>
  );
};

export default AppLayout;
