import React, { useState, useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { useFullscreen } from '@/hooks/useFullscreen';
import { useIsDesktop } from '@/hooks/useIsDesktop';
import { useActiveSection } from '@/hooks/useActiveSection';
import { useShortcuts } from '@/hooks/useShortcuts';
import { CommandPalette } from '@/components/CommandPalette';
import { PageHeader } from '@/components/PageHeader';
import { BottomNav } from '@/components/nav/BottomNav';
import { FAB } from '@/components/FAB';
import SubmenuBar from '@/components/nav/SubmenuBar';
import DashboardSubmenuBar from '@/components/nav/DashboardSubmenuBar';
import { AppProvider } from '@/contexts/AppContext';
import { Header } from './Header';
import { Sidebar } from './Sidebar';
import { TopNav } from './TopNav';
import { AppRoutes } from './AppRoutes';

function ShortcutsBinder({ onToggle }: { onToggle: () => void }) {
  useShortcuts({ toggleFullscreen: onToggle });
  return null;
}

export function Shell() {
  const { on, setOn } = useFullscreen();
  const { main } = useActiveSection();
  const toggle = () => setOn(v => !v);
  const exitFullscreen = () => setOn(false);
  const isDesktop = useIsDesktop();
  const location = useLocation();
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  // Sidebar collapsed state with localStorage persistence
  const [sidebarCollapsed, setSidebarCollapsed] = useState<boolean>(() => {
    try { return localStorage.getItem('wnwSidebarCollapsed') === '1'; } catch { return false; }
  });
  const [wasAutoCollapsed, setWasAutoCollapsed] = useState(false);

  // Save sidebar state to localStorage
  useEffect(() => {
    try { localStorage.setItem('wnwSidebarCollapsed', sidebarCollapsed ? '1' : '0'); } catch { /* ignore */ }
  }, [sidebarCollapsed]);

  // Check if current route is Page Editor (auto-collapse route)
  const isPageEditorRoute = location.pathname === '/appearance/pages';

  // Auto-collapse/expand sidebar based on route
  useEffect(() => {
    if (isPageEditorRoute) {
      // Auto-collapse when entering Page Editor (if not already collapsed)
      if (!sidebarCollapsed) {
        setSidebarCollapsed(true);
        setWasAutoCollapsed(true);
      }
    } else {
      // Auto-expand when leaving Page Editor (only if we auto-collapsed it)
      if (wasAutoCollapsed && sidebarCollapsed) {
        setSidebarCollapsed(false);
        setWasAutoCollapsed(false);
      }
    }
  }, [isPageEditorRoute]);

  const toggleSidebar = () => {
    setSidebarCollapsed(v => !v);
    setWasAutoCollapsed(false); // Manual toggle clears auto state
  };

  // Check if standalone mode - force fullscreen and hide toggle
  const isStandalone = window.WNW_CONFIG?.standaloneMode ?? false;
  const fullscreen = isStandalone ? true : on;

  // Check if current route is dashboard
  const isDashboardRoute = location.pathname === '/' || location.pathname.startsWith('/dashboard');

  // Check if current route is More page (no submenu needed)
  const isMorePage = location.pathname === '/more';

  const submenuTopClass = fullscreen ? 'top-0' : 'top-[calc(7rem+32px)]';
  const submenuZIndex = fullscreen ? 'z-50' : 'z-40';

  // Check if current route is setup/onboarding
  const isSetup = location.pathname === '/setup';

  if (isSetup) {
    return (
      <AppProvider isStandalone={isStandalone} exitFullscreen={exitFullscreen}>
        <div className="min-h-screen bg-background text-foreground flex flex-col">
          <AppRoutes />
        </div>
      </AppProvider>
    );
  }

  return (
    <AppProvider isStandalone={isStandalone} exitFullscreen={exitFullscreen}>
      {!isStandalone && <ShortcutsBinder onToggle={toggle} />}
      {!isStandalone && <CommandPalette toggleFullscreen={toggle} />}
      <div className={`flex flex-col min-h-screen ${fullscreen ? 'woonoow-fullscreen-root' : ''}`}>
        <Header onFullscreen={toggle} fullscreen={fullscreen} showToggle={!isStandalone} scrollContainerRef={scrollContainerRef} />
        {fullscreen ? (
          isDesktop ? (
            <div className="flex flex-1 min-h-0">
              <Sidebar collapsed={sidebarCollapsed} onToggle={toggleSidebar} />
              <main className="flex-1 flex flex-col min-h-0 min-w-0">
                {/* Flex wrapper: desktop = col-reverse (SubmenuBar first, PageHeader second) */}
                <div className="flex flex-col-reverse">
                  <PageHeader fullscreen={true} />
                  {isDashboardRoute ? (
                    <DashboardSubmenuBar items={main.children} fullscreen={true} />
                  ) : (
                    <SubmenuBar items={main.children} fullscreen={true} />
                  )}
                </div>
                <div className="flex-1 overflow-auto p-4 min-w-0">
                  <AppRoutes />
                </div>
              </main>
            </div>
          ) : (
            <div className="flex flex-1 flex-col min-h-0">
              {/* Flex wrapper: mobile = col (PageHeader first), desktop = col-reverse (SubmenuBar first) */}
              <div className={`flex flex-col md:flex-col-reverse sticky ${submenuTopClass} ${submenuZIndex}`}>
                <PageHeader fullscreen={true} />
                {!isMorePage && (isDashboardRoute ? (
                  <DashboardSubmenuBar items={main.children} fullscreen={true} />
                ) : (
                  <SubmenuBar items={main.children} fullscreen={true} />
                ))}
              </div>
              <main className="flex-1 flex flex-col min-h-0 min-w-0 pb-14">
                <div ref={scrollContainerRef} className="flex-1 overflow-auto p-4 min-w-0">
                  <AppRoutes />
                </div>
              </main>
              <BottomNav />
              <FAB />
            </div>
          )
        ) : (
          <div className="flex flex-1 flex-col min-h-0">
            <TopNav fullscreen={false} />
            {/* Flex wrapper: mobile = col (PageHeader first), desktop = col-reverse (SubmenuBar first) */}
            <div className={`flex flex-col md:flex-col-reverse sticky ${submenuTopClass} ${submenuZIndex}`}>
              <PageHeader fullscreen={false} />
              {isDashboardRoute ? (
                <DashboardSubmenuBar items={main.children} fullscreen={false} />
              ) : (
                <SubmenuBar items={main.children} fullscreen={false} />
              )}
            </div>
            <main className="flex-1 flex flex-col min-h-0 min-w-0">
              <div className="flex-1 overflow-auto p-4 min-w-0">
                <AppRoutes />
              </div>
            </main>
          </div>
        )}
      </div>
    </AppProvider>
  );
}
