import { BrowserRouter, Routes, Route, Link, useLocation } from 'react-router-dom';
import GalpaoModule from './pages/GalpaoModule';
import CylinderModule from './pages/CylinderModule';
import VaultModule from './pages/VaultModule';
import DomeModule from './pages/DomeModule';
import SignModule from './pages/SignModule';
import IsolatedRoofModule from './pages/IsolatedRoofModule';
import BarSelectorModule from './pages/BarSelectorModule';
import BridgeModule from './pages/BridgeModule';
import DynamicsModule from './pages/DynamicsModule';
import SettingsModule from './pages/SettingsModule';
import TowerModule from './pages/TowerModule';
import {
  Wind, Home, Settings, Menu, Cylinder, Church, CircleDot,
  Square, Layers, BarChart3, Activity, Building2,
} from 'lucide-react';
import { useState } from 'react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { ThemeProvider } from '@/lib/theme';
import { useI18n } from './store/i18nStore';
import LanguageSwitcher from './components/LanguageSwitcher';
import { GlobalWindSettingsModal } from './components/GlobalWindSettingsModal';

function AppLayout({ children }: { children: React.ReactNode }) {
  const location = useLocation();
  const [isCollapsed, setIsCollapsed] = useState(false);
  const { t } = useI18n();

  const navItems = [
    { path: '/', icon: <Home className="w-5 h-5" />, labelKey: 'nav_home' as const },
    { path: '/galpao', icon: <Wind className="w-5 h-5" />, labelKey: 'nav_warehouse' as const },
    { path: '/cilindro', icon: <Cylinder className="w-5 h-5" />, labelKey: 'nav_cylinder' as const },
    { path: '/abobada', icon: <Church className="w-5 h-5" />, labelKey: 'nav_vault' as const },
    { path: '/cupula', icon: <CircleDot className="w-5 h-5" />, labelKey: 'nav_dome' as const },
    { path: '/muros', icon: <Square className="w-5 h-5" />, labelKey: 'nav_sign' as const },
    { path: '/cobertura-isolada', icon: <Layers className="w-5 h-5" />, labelKey: 'nav_isolated_roof' as const },
    { path: '/barras', icon: <BarChart3 className="w-5 h-5" />, labelKey: 'nav_bar' as const },
    { path: '/pontes', icon: <Activity className="w-5 h-5" />, labelKey: 'nav_bridge' as const },
    { path: '/torre', icon: <Building2 className="w-5 h-5" />, labelKey: 'nav_tower' as const },
    { path: '/dinamica', icon: <Activity className="w-5 h-5" />, labelKey: 'nav_dynamics' as const },
    { path: '/settings', icon: <Settings className="w-5 h-5" />, labelKey: 'nav_settings' as const },
  ];

  return (
    <div className="flex h-screen w-full bg-background overflow-hidden font-sans">
      <aside
        className={cn(
          'hidden md:flex flex-col border-r bg-sidebar transition-all duration-300',
          isCollapsed ? 'w-16' : 'w-56',
        )}
      >
        <div className="h-14 flex items-center justify-between px-4 border-b">
          {!isCollapsed && <span className="font-bold text-primary truncate tracking-tight">{t('app_title')}</span>}
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setIsCollapsed(!isCollapsed)}
            className="shrink-0 ml-auto text-muted-foreground hover:text-foreground"
            title={isCollapsed ? t('nav_expand') : t('nav_collapse')}
          >
            <Menu className="w-5 h-5" />
          </Button>
        </div>
        <nav className="flex-1 overflow-y-auto p-3 space-y-1">
          {navItems.map((item) => {
            const isActive = location.pathname === item.path;
            const label = t(item.labelKey);
            return (
              <Link
                key={item.path}
                to={item.path}
                className={cn(
                  'flex items-center gap-3 px-3 py-2 rounded-md transition-colors text-sm',
                  isActive
                    ? 'bg-primary text-primary-foreground font-medium shadow-sm'
                    : 'text-muted-foreground hover:bg-secondary/50 hover:text-secondary-foreground',
                  isCollapsed && 'justify-center px-0',
                )}
                title={isCollapsed ? label : undefined}
              >
                {item.icon}
                {!isCollapsed && <span>{label}</span>}
              </Link>
            );
          })}
        </nav>
        <div className="border-t p-2 flex flex-col gap-2 items-center justify-center">
          <GlobalWindSettingsModal />
          <LanguageSwitcher />
        </div>
      </aside>

      <main className="flex-1 flex flex-col h-full overflow-hidden pb-16 md:pb-0">
        <header className="h-14 border-b bg-card flex items-center justify-between px-4 md:hidden">
          <span className="font-bold text-primary tracking-tight">{t('app_title')}</span>
          <div className="flex items-center gap-2">
            <GlobalWindSettingsModal />
            <LanguageSwitcher />
          </div>
        </header>
        <div className="flex-1 overflow-auto">{children}</div>
      </main>

      <nav className="md:hidden fixed bottom-0 left-0 right-0 h-16 bg-card border-t flex items-center justify-around px-1 z-50 pb-safe overflow-x-auto">
        {navItems.slice(0, 6).map((item) => {
          const isActive = location.pathname === item.path;
          const label = t(item.labelKey);
          return (
            <Link
              key={item.path}
              to={item.path}
              className={cn(
                'flex flex-col items-center justify-center h-full px-1 text-xs transition-colors min-w-[3rem]',
                isActive ? 'text-primary font-medium' : 'text-muted-foreground',
              )}
            >
              <div className={cn('p-1 rounded-full transition-colors', isActive && 'bg-primary/10')}>
                {item.icon}
              </div>
              <span className="scale-90 text-[10px]">{label}</span>
            </Link>
          );
        })}
      </nav>
    </div>
  );
}

function HomeMock() {
  const { t } = useI18n();
  const modules = [
    { to: '/galpao', icon: Wind, label: 'Galpão Retangular', desc: 'Paredes A/B/C/D, telhados E-J, excentricidade, atrito, alta turbulência.' },
    { to: '/cilindro', icon: Cylinder, label: 'Cilindro Vertical', desc: 'Silos, reservatórios, chaminés. Cpe por ângulo (Tab. 13), Reynolds.' },
    { to: '/abobada', icon: Church, label: 'Abóbada Cilíndrica', desc: 'Coberturas curvas em arco. Tab. 15-20, 6 zonas.' },
    { to: '/cupula', icon: CircleDot, label: 'Cúpula', desc: 'Sobre terreno (Tab. 21) ou parede cilíndrica (Tab. 22).' },
    { to: '/muros', icon: Square, label: 'Muros e Placas', desc: 'Cf para vento perpendicular e oblíquo (Tab. 23).' },
    { to: '/cobertura-isolada', icon: Layers, label: 'Coberturas Isoladas', desc: 'Uma ou duas águas, abas perpendiculares (Tab. 24-25).' },
    { to: '/barras', icon: BarChart3, label: 'Barras Prismáticas', desc: 'Faces planas (Tab. 26) ou circulares (Tab. 27).' },
    { to: '/pontes', icon: Activity, label: 'Pontes', desc: 'Pse, Cx/Cz do tabuleiro, flutter, galope (sec. 11).' },
    { to: '/dinamica', icon: Activity, label: 'Dinâmica e Conforto', desc: 'ζ, ξ, conforto humano, vórtices (sec. 9-10).' },
  ];

  return (
    <div className="p-8 max-w-6xl mx-auto space-y-8">
      <header className="text-center space-y-2">
        <h1 className="text-4xl font-extrabold tracking-tight text-foreground">{t('app_title')}</h1>
        <p className="text-muted-foreground text-lg">
          {t('app_subtitle')}
        </p>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {modules.map((m) => (
          <Link key={m.to} to={m.to} className="block p-6 rounded-xl border bg-card hover:shadow-lg hover:border-primary transition-all">
            <m.icon className="w-8 h-8 text-primary mb-3" />
            <h2 className="font-semibold text-lg mb-1">{m.label}</h2>
            <p className="text-sm text-muted-foreground">{m.desc}</p>
          </Link>
        ))}
      </div>

      <div className="rounded-lg border bg-muted/40 p-4 text-sm text-muted-foreground">
        <p className="font-medium text-foreground mb-2">{t('home_full_coverage')}</p>
        <ul className="grid grid-cols-2 md:grid-cols-4 gap-1 text-xs">
          <li>✓ Sec. 5 — V₀, S₁, S₂, S₃</li>
          <li>✓ Sec. 6.1 — Paralelepipédicas</li>
          <li>✓ Sec. 6.2 — Cilindros, abóbadas, cúpulas</li>
          <li>✓ Sec. 6.3 — Pressão interna (Cpi)</li>
          <li>✓ Sec. 6.4 — Vizinhança</li>
          <li>✓ Sec. 7 — Muros, coberturas isoladas</li>
          <li>✓ Sec. 8 — Barras e reticulados</li>
          <li>✓ Sec. 9 — Efeitos dinâmicos</li>
          <li>✓ Sec. 10 — Vórtices</li>
          <li>✓ Sec. 11 — Pontes</li>
          <li>✓ Anexo A — S₂(qualquer t)</li>
          <li>✓ Anexo B — S₃(Pₘ, vida útil)</li>
          <li>✓ Anexo C — 49 estações meteorológicas</li>
        </ul>
      </div>
    </div>
  );
}

function App() {
  return (
    <ThemeProvider>
      <BrowserRouter>
        <AppLayout>
          <Routes>
            <Route path="/" element={<HomeMock />} />
            <Route path="/galpao" element={<GalpaoModule />} />
            <Route path="/cilindro" element={<CylinderModule />} />
            <Route path="/abobada" element={<VaultModule />} />
            <Route path="/cupula" element={<DomeModule />} />
            <Route path="/muros" element={<SignModule />} />
            <Route path="/cobertura-isolada" element={<IsolatedRoofModule />} />
            <Route path="/barras" element={<BarSelectorModule />} />
            <Route path="/pontes" element={<BridgeModule />} />
            <Route path="/torre" element={<TowerModule />} />
            <Route path="/dinamica" element={<DynamicsModule />} />
            <Route path="/settings" element={<SettingsModule />} />
          </Routes>
        </AppLayout>
      </BrowserRouter>
    </ThemeProvider>
  );
}

export default App;