import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider, useRouter } from './router';
import { DoveJonesOpening } from './components/opening/DoveJonesOpening';
import { HomePage } from './pages/HomePage';
import { AboutPage } from './pages/AboutPage';
import { ServicesPage } from './pages/ServicesPage';
import { ProjectsPage } from './pages/ProjectsPage';
import { ProjectDetailPage } from './pages/ProjectDetailPage';
import { TradePage } from './pages/TradePage';
import { JourneyPage } from './pages/JourneyPage';
import { ProductsPage } from './pages/ProductsPage';
import { ContactPage } from './pages/ContactPage';
import { PrivacyPage } from './pages/PrivacyPage';
import { NotFoundPage } from './pages/NotFoundPage';
import './globals.css';

function AppRouter() {
  const { path } = useRouter();
  const normalizedPath = path.replace(/\/+$/, '') || '/';

  useEffect(() => {
    document.documentElement.classList.add('ready');

    // "while reloading ... its should open the opening animation only"
    let isReload = false;
    try {
      const navEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;
      isReload = navEntry?.type === 'reload' || (performance as any).navigation?.type === 1;
      if (!isReload && sessionStorage.getItem('dj_reloading') === 'true') {
        isReload = true;
      }
      sessionStorage.removeItem('dj_reloading');
    } catch (e) {}

    if (isReload && window.location.pathname !== '/') {
      window.history.replaceState(null, '', '/');
    }

    // Handle deep-link section scrolling for single-page architecture
    const sectionMap: Record<string, string> = {
      '/architecture': 'home',
      '/about': 'about',
      '/studio': 'about',
      '/services': 'services',
      '/projects': 'projects',
      '/work': 'projects',
      '/contact': 'contact',
      '/enquiries': 'contact'
    };

    const hash = window.location.hash.replace('#', '');
    const targetSection = hash || sectionMap[normalizedPath];
    if (targetSection && normalizedPath !== '/') {
      const timer = setTimeout(() => {
        const el = document.getElementById(targetSection);
        if (el) {
          const headerOffset = 80;
          const pos = el.getBoundingClientRect().top + window.scrollY - headerOffset;
          window.scrollTo({ top: targetSection === 'home' || targetSection === 'overview' ? 0 : pos, behavior: 'smooth' });
        }
      }, 150);
      return () => clearTimeout(timer);
    } else if (normalizedPath !== '/') {
      // Whenever route changes without a target hash (e.g. going to /import-export or /privacy)
      window.scrollTo(0, 0);
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    }
  }, [normalizedPath]);

  // Route 1: Full-Screen Cinematic Division Selector (Opening Experience)
  if (normalizedPath === '/') {
    return <DoveJonesOpening />;
  }

  // Route 2: Architecture & Interior Architecture Division (HomePage)
  if (
    normalizedPath === '/architecture' ||
    normalizedPath === '/home' ||
    normalizedPath === '/about' ||
    normalizedPath === '/studio' ||
    normalizedPath === '/services' ||
    normalizedPath === '/projects' ||
    normalizedPath === '/work' ||
    normalizedPath === '/contact' ||
    normalizedPath === '/enquiries'
  ) {
    return <HomePage />;
  }

  // Route 3: Architectural Materials Import & Export Division (TradePage)
  if (
    normalizedPath === '/import-export' ||
    normalizedPath.startsWith('/import-export') ||
    normalizedPath === '/trade' ||
    normalizedPath === '/voyage'
  ) {
    return <TradePage />;
  }

  // Route 3B: Dedicated Our Journey, Mission & Vision Page
  if (normalizedPath === '/our-journey' || normalizedPath === '/journey') {
    return <JourneyPage />;
  }

  // Route 3C: Dedicated Our Products Exhibition Page (Shared across Architecture & Import/Export)
  if (
    normalizedPath === '/products' ||
    normalizedPath === '/architecture/products' ||
    normalizedPath === '/import-export/products'
  ) {
    return <ProductsPage />;
  }

  if (normalizedPath.startsWith('/projects/')) {
    const slug = normalizedPath.split('/')[2];
    return <ProjectDetailPage slug={slug} />;
  }

  if (normalizedPath === '/privacy') {
    return <PrivacyPage />;
  }

  return <NotFoundPage />;
}

export function App() {
  return (
    <RouterProvider>
      <AppRouter />
    </RouterProvider>
  );
}

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
