import { useState, useEffect, useRef, Suspense, lazy } from 'react';
import { useNavigate, useLocation, Routes, Route, Link } from 'react-router-dom';
import { Helmet } from 'react-helmet-async';
import { Header } from './components/Header';
import { Breadcrumb } from './components/Breadcrumb';
import { Footer } from './components/Footer';
import { UnifiedSearch } from './components/UnifiedSearch';
import { useGitHubAnalysis } from './hooks/useGitHubAnalysis';
import { nichePages } from './config/nichePages';
import { LazyMotion, domAnimation, motion, AnimatePresence } from 'framer-motion';
import { useProfileComparison } from './hooks/useProfileComparison';
import { LoadingState } from './components/LoadingState';
import { ProfileSkeleton } from './components/ProfileSkeleton';
import { GlowCard } from './components/ui/spotlight-card';
import { ErrorBoundary } from './components/ErrorBoundary';
import { ChevronDown, Github, Zap, Shield, BarChart3, Users, FileText, AlertCircle } from 'lucide-react';
import { AnimatedSection } from './components/ui/AnimatedSection';
import { useAuth, AuthProvider } from './contexts/AuthContext';
import { ScrollToTop } from './components/ScrollToTop';
import { LazyScene } from './components/LazyScene';
import { SEOHead } from './components/SEOHead';
import { useSearchCount } from './hooks/useSearchCount';
const SEOContentSection = lazy(() => import('./components/SEOContentSection').then(m => ({ default: m.SEOContentSection })));

// Lazy load heavy components
const HeroScene = lazy(() => import('./components/3d/HeroScene').then(m => ({ default: m.HeroScene })));
const ProfileAnalysis = lazy(() => import('./components/ProfileAnalysis').then(m => ({ default: m.ProfileAnalysis })));
const ProfileComparison = lazy(() => import('./components/ProfileComparison').then(m => ({ default: m.ProfileComparison })));
const Dashboard = lazy(() => import('./components/Dashboard').then(m => ({ default: m.Dashboard })));
import { AuthModal } from './components/AuthModal';
import { RouteFallback } from './components/RouteFallback';
import { AmbientBackground } from './components/ui/AmbientBackground';
const Settings = lazy(() => import('./components/Settings').then(m => ({ default: m.Settings })));
const FeaturesSection = lazy(() => import('./components/FeaturesSection').then(m => ({ default: m.FeaturesSection })));
const HowItWorksSection = lazy(() => import('./components/HowItWorksSection').then(m => ({ default: m.HowItWorksSection })));
const FAQSection = lazy(() => import('./components/FAQSection').then(m => ({ default: m.FAQSection })));
import { CookieConsent } from './components/CookieConsent';
import { OfflineBanner } from './components/pwa/OfflineBanner';
import { InstallPrompt } from './components/pwa/InstallPrompt';
import { UpdateNotification } from './components/pwa/UpdateNotification';
import { AdUnit } from './components/AdUnit';
import { FeaturedProfiles } from './components/FeaturedProfiles';
import { HomeToolsDock } from './components/HomeToolsDock';

const ToolContributionHeatmap = lazy(() => import('./pages/ToolContributionHeatmap').then(m => ({ default: m.ToolContributionHeatmap })));
const PersonalDashboard = lazy(() => import('./pages/PersonalDashboard').then(m => ({ default: m.PersonalDashboard })));
const ToolReadmeGenerator = lazy(() => import('./pages/ToolReadmeGenerator').then(m => ({ default: m.ToolReadmeGenerator })));
const ToolProfileRoast = lazy(() => import('./pages/ToolProfileRoast').then(m => ({ default: m.ToolProfileRoast })));
const ToolBadgeGenerator = lazy(() => import('./pages/ToolBadgeGenerator').then(m => ({ default: m.ToolBadgeGenerator })));
const ComparePage = lazy(() => import('./pages/ComparePage').then(m => ({ default: m.ComparePage })));
const BlogIndex = lazy(() => import('./pages/BlogIndex').then(m => ({ default: m.BlogIndex })));
const BlogPost = lazy(() => import('./pages/BlogPost').then(m => ({ default: m.BlogPost })));
const ForRecruiters = lazy(() => import('./pages/ForRecruiters').then(m => ({ default: m.ForRecruiters })));
const ForDevelopers = lazy(() => import('./pages/ForDevelopers').then(m => ({ default: m.ForDevelopers })));
const GitHubResumeAlternative = lazy(() => import('./pages/GitHubResumeAlternative').then(m => ({ default: m.GitHubResumeAlternative })));
const GitIQvsOSSInsight = lazy(() => import('./pages/GitIQvsOSSInsight').then(m => ({ default: m.GitIQvsOSSInsight })));
const GitIQvsGitAwards = lazy(() => import('./pages/GitIQvsGitAwards').then(m => ({ default: m.GitIQvsGitAwards })));
const RustDevelopers = lazy(() => import('./pages/RustDevelopers').then(m => ({ default: m.RustDevelopers })));
const TechNichePage = lazy(() => import('./pages/TechNichePage').then(m => ({ default: m.default })));
const CompareBattle = lazy(() => import('./pages/CompareBattle').then(m => ({ default: m.CompareBattle })));
const RoastShare = lazy(() => import('./pages/RoastShare').then(m => ({ default: m.RoastShare })));
const AnalysisShare = lazy(() => import('./pages/AnalysisShare').then(m => ({ default: m.AnalysisShare })));
const RepoSecurityAudit = lazy(() => import('./pages/RepoSecurityAudit').then(m => ({ default: m.RepoSecurityAudit })));
const NotFound404 = lazy(() => import('./pages/NotFound404').then(m => ({ default: m.NotFound404 })));
const GitIQvsProfileSummary = lazy(() => import('./pages/GitIQvsProfileSummary').then(m => ({ default: m.GitIQvsProfileSummary })));
const GeographicHub = lazy(() => import('./pages/GeographicHub').then(m => ({ default: m.GeographicHub })));
const DeveloperLanguageLocationHub = lazy(() => import('./pages/DeveloperLanguageLocationHub').then(m => ({ default: m.DeveloperLanguageLocationHub })));
const AlternativeToPage = lazy(() => import('./pages/AlternativeToPage').then(m => ({ default: m.AlternativeToPage })));
const AboutPage = lazy(() => import('./pages/AboutPage').then(m => ({ default: m.AboutPage })));
const PrivacyPage = lazy(() => import('./pages/PrivacyPage').then(m => ({ default: m.PrivacyPage })));
const TermsPage = lazy(() => import('./pages/TermsPage').then(m => ({ default: m.TermsPage })));
const ContactPage = lazy(() => import('./pages/ContactPage').then(m => ({ default: m.ContactPage })));
const LeaderboardPage = lazy(() => import('./pages/LeaderboardPage').then(m => ({ default: m.LeaderboardPage })));
const CareerRoadmapPage = lazy(() => import('./pages/CareerRoadmapPage').then(m => ({ default: m.CareerRoadmapPage })));
const ReadmeEditorPage = lazy(() => import('./pages/ReadmeEditorPage').then(m => ({ default: m.ReadmeEditorPage })));
const FinishSignUp = lazy(() => import('./pages/FinishSignUp').then(m => ({ default: m.FinishSignUp })));
const AdminDashboard = lazy(() => import('./pages/AdminDashboard').then(m => ({ default: m.AdminDashboard })));
const ActivityHistory = lazy(() => import('./pages/ActivityHistory').then(m => ({ default: m.ActivityHistory })));
const ToolPage = lazy(() => import('./pages/ToolPage').then(m => ({ default: m.ToolPage })));
const PricingPage = lazy(() => import('./pages/PricingPage').then(m => ({ default: m.PricingPage })));
const BestTopicPage = lazy(() => import('./pages/BestTopicPage').then(m => ({ default: m.BestTopicPage })));
const CompanyHub = lazy(() => import('./pages/CompanyHub').then(m => ({ default: m.CompanyHub })));
const TechStackComparison = lazy(() => import('./pages/TechStackComparison').then(m => ({ default: m.TechStackComparison })));
const ToolsHubPage = lazy(() => import('./pages/ToolsHubPage').then(m => ({ default: m.ToolsHubPage })));

import { SettingsProvider, useSettings } from './contexts/SettingsContext';
import { InitialLoader } from './components/InitialLoader';

const LiveCounter = () => {
  const [count, setCount] = useState(() => {
    const saved = localStorage.getItem('gitiq_live_count');
    return saved ? parseInt(saved, 10) : 12403;
  });

  useEffect(() => {
    const interval = setInterval(() => {
      setCount(c => {
        const next = c + Math.floor(Math.random() * 3);
        localStorage.setItem('gitiq_live_count', next.toString());
        return next;
      });
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  return (
    <motion.div 
      initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.5 }}
      className="flex items-center justify-center gap-2 text-sm text-gray-400 mt-6"
    >
      <span className="relative flex h-3 w-3">
        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
        <span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
      </span>
      <span><strong className="text-white">{(count || 0).toLocaleString()}</strong> developers analyzed today</span>
    </motion.div>
  );
};

const TrendingSearches = () => {
  const trending = ['torvalds', 'gaearon', 'tj', 'yyx990803', 'sindresorhus'];
  return (
    <motion.div 
      initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.7 }}
      className="mt-8 flex flex-wrap items-center justify-center gap-3"
    >
      <span className="text-sm text-gray-400">Trending:</span>
      {trending.map(t => (
        <a key={t} href={`/?ref=${t}`} className="px-3 py-1 rounded-full text-xs font-medium bg-white/5 border border-white/10 hover:bg-white/10 hover:border-blue-500/50 transition-colors text-gray-300 hover:text-white">
          @{t}
        </a>
      ))}
    </motion.div>
  );
};

function App() {
  return (
    <LazyMotion features={domAnimation}>
      <AuthProvider>
        <SettingsProvider>
          <AppContent />
        </SettingsProvider>
      </AuthProvider>
    </LazyMotion>
  );
}

function AppContent() {
  const navigate = useNavigate();
  const location = useLocation();
  const [githubUrl, setGithubUrl] = useState('');
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
  const isFirstLoad = useRef(!sessionStorage.getItem('gitiq_intro_played'));
  const [showIntro, setShowIntro] = useState(isFirstLoad.current);


  const { user, loading: authLoading, logout, isAdmin } = useAuth();
  const { analysis, loading, error, analyzeProfile, resetAnalysis } = useGitHubAnalysis();
  const { dataSaver, globalFlags } = useSettings();
  const { canSearch, incrementSearch, resetSearchCount } = useSearchCount();

  // Reset search count when user logs in (authenticated users get unlimited)
  useEffect(() => {
    if (user) {
      resetSearchCount();
    }
  }, [user, resetSearchCount]);

  const {
    profiles,
    addProfile,
    removeProfile,
    clearComparison
  } = useProfileComparison();

  // Auto-analyze for /analyze/:username routes
  const abortRef = useRef<AbortController | null>(null);
  useEffect(() => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    const match = location.pathname.match(/^\/analyze\/(.+)/);
    const staticNicheSlugs = nichePages.map(n => n.slug);
    
    if (match) {
      const username = match[1];
      if (!staticNicheSlugs.includes(username) && !githubUrl && !analysis) {
        if (!canSearch) {
          setIsAuthModalOpen(true);
          return;
        }
        setGithubUrl(username);
        analyzeProfile(username, controller.signal);
        incrementSearch();
      }
    }
    return () => controller.abort();
  }, [location.pathname, analysis, analyzeProfile, githubUrl, canSearch, incrementSearch]);

  // Handle ?ref= query parameter changes
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const ref = params.get('ref');
    if (ref && ref !== githubUrl) {
      if (!canSearch) {
        setIsAuthModalOpen(true);
        return;
      }
      setGithubUrl(ref);
      analyzeProfile(ref);
      incrementSearch();
    }
  }, [location.search, analyzeProfile, githubUrl, canSearch, incrementSearch]);

  const handleAnalyze = async (url: string) => {
    if (!canSearch) {
      setIsAuthModalOpen(true);
      return;
    }
    setGithubUrl(url);
    navigate('/');
    await analyzeProfile(url);
    incrementSearch();

    setTimeout(() => {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }, 500);
  };

  const handleAddToComparison = () => {
    if (analysis) {
      addProfile(analysis);
    }
  };

  const handleClearHistory = () => {
    localStorage.removeItem('gitiq_recent_searches');
  };

  const handleNavigate = (view: string) => {
    if (view === 'home') navigate('/');
    else if (view === 'dashboard') navigate('/dashboard');
    else if (view === 'settings') navigate('/settings');
  };

  const handleIntroComplete = () => {
    setShowIntro(false);
    sessionStorage.setItem('gitiq_intro_played', 'true');
  };

  const isMaintenanceMode = globalFlags?.maintenanceMode && !isAdmin && !authLoading;

  if (isMaintenanceMode && location.pathname !== '/admin') {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center p-4">
        <Helmet><title>Maintenance | GitIQ</title></Helmet>
        <div className="max-w-md w-full p-8 rounded-3xl bg-[#0a0a0a]/90 backdrop-blur-3xl border border-white/[0.08] text-center shadow-[0_0_80px_rgba(0,0,0,0.8),inset_0_1px_0_rgba(255,255,255,0.1)]">
          <Settings className="w-16 h-16 text-yellow-500 mx-auto mb-6 animate-[spin_4s_linear_infinite]" />
          <h2 className="text-2xl font-bold text-white mb-4">Under Maintenance</h2>
          <p className="text-gray-400 mb-8 leading-relaxed">We are currently upgrading our systems to bring you new features. Please check back shortly.</p>
          <button onClick={() => window.location.reload()} className="px-6 py-2.5 bg-white/10 hover:bg-white/20 text-white font-medium rounded-xl transition-colors">
            Refresh Page
          </button>
        </div>
      </div>
    );
  }

  return (
    <>
      <SEOHead path={location.pathname} />
      <ScrollToTop />
      
      <AnimatePresence>
        {showIntro && <InitialLoader onComplete={handleIntroComplete} />}
      </AnimatePresence>
      
      <div className={`min-h-screen transition-colors duration-300 text-white ${showIntro ? 'h-screen overflow-hidden' : ''}`}>
        <AmbientBackground />
        {!dataSaver && location.pathname === '/' && (
          <LazyScene rootMargin="100px">
            <div className="fixed inset-0 z-0">
              <ErrorBoundary>
                <Suspense fallback={null}>
                  <HeroScene />
                </Suspense>
              </ErrorBoundary>
            </div>
          </LazyScene>
        )}

      <div className="relative z-10">
        <Header
          isDark={true}
          user={user}
          authLoading={authLoading}
          onLoginClick={() => setIsAuthModalOpen(true)}
          onLogoutClick={logout}
          onNavigate={handleNavigate}
          onAnalyze={handleAnalyze}
        />

        <Breadcrumb />
        <main id="main-content" className="flex-1 w-full relative z-10">
          <ErrorBoundary>
          <Suspense fallback={<RouteFallback />}>
          <Routes>
            <Route path="/" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                {!analysis && !loading && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.8, ease: "easeOut", delay: isFirstLoad.current ? 3.5 : 0.3 }}
                    className="text-center mb-12"
                  >
                    <motion.div
                      initial={{ scale: 0.9, opacity: 0 }}
                      animate={{ scale: 1, opacity: 1 }}
                      transition={{ delay: 0.2 }}
                      className="inline-block mb-4 px-4 py-1.5 rounded-full border border-blue-500/30 bg-blue-500/10 backdrop-blur-sm"
                    >
                      <span className="text-blue-400 text-sm font-medium tracking-wide">
                        ✨ AI-Powered GitHub Analysis
                      </span>
                    </motion.div>

                    <h1 className="text-5xl md:text-7xl font-bold mb-6 tracking-tight">
                      <span className="bg-clip-text text-transparent bg-gradient-to-r from-white via-blue-100 to-white drop-shadow-[0_0_15px_rgba(255,255,255,0.3)]">
                        Unlock Your
                      </span>
                      <br />
                      <span className="bg-clip-text text-transparent bg-gradient-to-r from-blue-400 via-purple-500 to-pink-500 font-extrabold drop-shadow-[0_0_30px_rgba(59,130,246,0.5)]">
                        Coding Potential with GitIQ
                      </span>
                    </h1>

                    <p className="text-xl md:text-2xl mb-12 max-w-3xl mx-auto leading-relaxed text-gray-400">
                      The Free GitHub Profile Analyzer. Turn your repositories into a professional developer resume, visualize your tech stack, and prove your impact to recruiters.
                    </p>

                    <Link
                      to="/pricing"
                      className="inline-flex items-center gap-2 px-5 py-2.5 mb-8 rounded-full bg-gradient-to-r from-amber-500/20 to-orange-500/20 border border-amber-500/30 hover:bg-amber-500/30 transition-all text-amber-300 text-sm font-medium"
                    >
                      <span className="relative flex h-2 w-2">
                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"></span>
                        <span className="relative inline-flex rounded-full h-2 w-2 bg-amber-500"></span>
                      </span>
                      Upgrade to Pro — Unlock unlimited analyses, AI insights & more
                    </Link>

                    <UnifiedSearch
                      onAnalyze={handleAnalyze}
                      loading={loading}
                      isDark={true}
                      value={githubUrl}
                    />
                    
                    <LiveCounter />
                    <TrendingSearches />
                    
                    {/* MacOS Dock for Tools Selection */}
                    <motion.div
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.5, duration: 0.8 }}
                    >
                      <HomeToolsDock />
                    </motion.div>
                  </motion.div>
                )}

                {error && !loading && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="max-w-2xl mx-auto mb-12"
                  >
                    <GlowCard className={`p-8 ${(error || '').toLowerCase().includes('rate limit') ? 'border-yellow-500/30 bg-yellow-500/10' : 'border-red-500/30 bg-red-500/10'}`}>
                      <div className="flex items-start space-x-4">
                        <div className="flex-shrink-0">
                          <div className={`w-12 h-12 rounded-full flex items-center justify-center ${(error || '').toLowerCase().includes('rate limit') ? 'bg-yellow-500/20' : 'bg-red-500/20'}`}>
                            <AlertCircle className={`w-6 h-6 ${(error || '').toLowerCase().includes('rate limit') ? 'text-yellow-400' : 'text-red-400'}`} />
                          </div>
                        </div>
                        <div className="flex-1">
                          <h3 className="text-xl font-semibold text-white mb-2">
                            {(error || '').toLowerCase().includes('rate limit') ? 'API Rate Limit Exceeded' : (error || '').toLowerCase().includes('not found') ? 'Profile Not Found' : 'Analysis Error'}
                          </h3>
                          <p className="text-gray-300 mb-4">
                            {error}
                          </p>
                          <div className="flex space-x-3">
                            <button
                              onClick={() => resetAnalysis()}
                              className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
                            >
                              Try Another Profile
                            </button>
                          </div>
                        </div>
                      </div>
                    </GlowCard>
                  </motion.div>
                )}

                {!analysis && !loading && !error && (
                  <>
                    <FeaturedProfiles isDark={true} />
                    <div className="max-w-4xl mx-auto mb-16 px-4">
                      <AdUnit slotId="home_bottom" label="Advertisement" />
                    </div>
                    <FeaturesSection />
                    <HowItWorksSection />
                    <FAQSection />

                    {/* Testimonials */}
                    <motion.div
                      initial={{ opacity: 0, y: 20 }}
                      whileInView={{ opacity: 1, y: 0 }}
                      viewport={{ once: true }}
                      className="mb-24"
                    >
                      <GlowCard className="p-10 md:p-14 relative overflow-hidden">
                        <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-blue-500/10 blur-[120px] rounded-full pointer-events-none" />
                        <h2 className="text-3xl md:text-4xl font-bold text-white mb-12 text-center relative z-10">Loved By The Community</h2>
                        <div className="grid md:grid-cols-3 gap-8 relative z-10">
                          {[
                            { quote: "GitIQ helped me identify huge gaps in my open source portfolio. I improved my score from 45 to 82 and landed 3 interviews!", author: "Frontend Engineer", initials: "FE", color: "from-blue-500 to-cyan-500" },
                            { quote: "The README generator is absolute magic. It gave my profile a premium look instantly without me writing a single line of markdown.", author: "Full Stack Dev", initials: "FS", color: "from-purple-500 to-pink-500" },
                            { quote: "I use the comparison tool to benchmark against senior devs in my field. The insights are incredibly motivating and precise.", author: "Backend Lead", initials: "BL", color: "from-emerald-500 to-teal-500" }
                          ].map((t, i) => (
                            <div key={i} className="p-8 bg-black/40 backdrop-blur-md border border-white/5 rounded-2xl relative group hover:border-white/20 transition-colors duration-300">
                              <div className="absolute -top-6 -left-2 text-7xl text-white/5 font-serif group-hover:text-white/10 transition-colors">"</div>
                              <p className="text-gray-300 mb-8 relative z-10 leading-relaxed text-lg">{t.quote}</p>
                              <div className="flex items-center gap-4">
                                <div className={`w-12 h-12 rounded-full bg-gradient-to-br ${t.color} flex items-center justify-center text-white font-bold shadow-lg`}>
                                  {t.initials}
                                </div>
                                <div>
                                  <p className="text-white font-bold">{t.author}</p>
                                  <p className="text-gray-400 text-sm">GitIQ User</p>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </GlowCard>
                    </motion.div>

                    {/* As Seen In */}
                    <motion.div
                      initial={{ opacity: 0, y: 20 }}
                      whileInView={{ opacity: 1, y: 0 }}
                      viewport={{ once: true }}
                      className="mb-24 text-center"
                    >
                      <GlowCard className="p-10 md:p-14 relative overflow-hidden">
                        <div className="absolute top-0 left-0 w-[400px] h-[400px] bg-purple-500/10 blur-[120px] rounded-full pointer-events-none" />
                        <div className="relative z-10">
                          <h2 className="text-2xl font-bold text-white mb-10">As Seen In</h2>
                          <div className="flex flex-wrap items-center justify-center gap-8 md:gap-16 opacity-60">
                            {[
                              { name: "GitHub", icon: "M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" },
                              { name: "Product Hunt", icon: "M12 0C5.373 0 0 5.373 0 12c0 6.627 5.373 12 12 12 6.628 0 12-5.373 12-12 0-6.627-5.372-12-12-12zm4.247 14.06a3.246 3.246 0 01-3.247 3.247H8.466V9.646h4.534a3.246 3.246 0 013.247 3.247v1.167z" },
                              { name: "Hacker News", icon: "M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zM7.5 6h2.25l2.25 6.75L14.25 6h2.25l-3.75 11.25h-1.5L7.5 6z" },
                              { name: "Dev.to", icon: "M7.45 2.48c-1.63 0-3.16.63-4.29 1.76A6.01 6.01 0 001.4 8.55v6.87c0 1.64.63 3.18 1.76 4.31a6.03 6.03 0 004.3 1.79h9.17c1.64 0 3.18-.64 4.31-1.79a6.03 6.03 0 001.79-4.31V8.56c0-1.64-.64-3.18-1.79-4.31a6.06 6.06 0 00-4.3-1.77H7.45zm.04 5.1c.21 0 .42.04.62.12.39.16.7.46.87.85l2.46 5.89 2.45-5.89c.16-.39.48-.7.88-.86.39-.15.84-.15 1.23.01.4.16.7.48.85.87l-3.75 8.97c-.16.39-.48.7-.88.86H12.6c-.39.15-.84.14-1.23-.02-.39-.16-.7-.48-.85-.87l-3.75-8.97a1.38 1.38 0 01.84-1.76c.21-.09.43-.13.65-.13h.01z" },
                              { name: "Reddit", icon: "M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498 0c0-.688.562-1.249 1.25-1.249zm-2.5 2.918c-.18 0-.36.025-.53.077C13.134 7.59 12.56 7.75 12 7.93c-.56-.18-1.134-.34-1.98-.19-.17-.052-.35-.077-.53-.077-.662 0-1.198.536-1.198 1.198 0 .51.323.937.775 1.107-.208.373-.322.8-.322 1.245 0 2.037 2.351 3.688 5.255 3.688 2.903 0 5.254-1.65 5.254-3.688 0-.445-.113-.872-.321-1.245.452-.17.775-.597.775-1.107 0-.662-.536-1.198-1.198-1.198z" },
                            ].map((brand) => (
                              <div key={brand.name} className="flex flex-col items-center gap-2 group hover:opacity-100 transition-opacity">
                                <svg className="w-10 h-10 text-gray-400 group-hover:text-white transition-colors" fill="currentColor" viewBox="0 0 24 24">
                                  <path d={brand.icon} />
                                </svg>
                                <span className="text-sm text-gray-500">{brand.name}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      </GlowCard>
                    </motion.div>
                  </>
                )}

                <AnimatePresence>
                  {profiles.length > 0 && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      exit={{ opacity: 0, height: 0 }}
                      className="mb-16"
                    >
                      <Suspense fallback={<LoadingState />}>
                        <ProfileComparison
                          profiles={profiles}
                          isDark={true}
                          onRemove={removeProfile}
                          onClear={clearComparison}
                          onAddMore={() => {
                            const input = document.querySelector('input[type="text"]') as HTMLInputElement;
                            if (input) input.focus();
                          }}
                        />
                      </Suspense>
                    </motion.div>
                  )}
                </AnimatePresence>

                <AnimatePresence mode="wait">
                  {loading && (
                    <motion.div
                      key="loading"
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      exit={{ opacity: 0 }}
                      className="flex justify-center py-20 w-full"
                    >
                      <ProfileSkeleton />
                    </motion.div>
                  )}

                  {analysis && !loading && (
                    <motion.div
                      key="analysis"
                      initial={{ opacity: 0, y: 50 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -50 }}
                      transition={{ duration: 0.6 }}
                    >
                      <Suspense fallback={<LoadingState />}>
                        <ProfileAnalysis
                          analysis={analysis}
                          githubUrl={githubUrl}
                          isDark={true}
                          onAddToComparison={handleAddToComparison}
                          onNewSearch={() => {
                            resetAnalysis();
                            setGithubUrl('');
                            navigate('/');
                            window.scrollTo({ top: 0, behavior: 'smooth' });
                          }}
                        />
                      </Suspense>
                    </motion.div>
                  )}
                </AnimatePresence>

                {!analysis && !loading && (
                  <Suspense fallback={null}>
                    <SEOContentSection />
                  </Suspense>
                )}
              </div>
            } />
            <Route path="/analyze/rust-developers" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <RustDevelopers isDark={true} />
              </div>
            } />
            <Route path="/analyze/:slug" element={
              <Suspense fallback={<div className="container mx-auto px-4 pt-32 pb-12 flex justify-center py-20"><ProfileSkeleton /></div>}>
                <TechNichePage
                  isDark={true}
                  analysis={analysis}
                  loading={loading}
                  error={error}
                  githubUrl={githubUrl}
                  resetAnalysis={resetAnalysis}
                  setGithubUrl={setGithubUrl}
                  navigate={navigate}
                />
              </Suspense>
            } />
            <Route path="/dashboard" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <Dashboard onAnalyze={handleAnalyze} onClearHistory={handleClearHistory} />
              </div>
            } />
            <Route path="/history" element={
              <ActivityHistory />
            } />
            <Route path="/settings" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <Settings onClearData={handleClearHistory} />
              </div>
            } />
            <Route path="/tools/readme-generator" element={
              <ToolReadmeGenerator />
            } />
            <Route path="/tools/profile-roast" element={
              <ToolProfileRoast />
            } />
            <Route path="/tools/badge-generator" element={
              <ToolBadgeGenerator />
            } />
            <Route path="/tools/contribution-heatmap" element={
              <ToolContributionHeatmap />
            } />
            <Route path="/tools/repo-security-audit" element={
              <RepoSecurityAudit isDark={true} />
            } />
            <Route path="/compare/:user1/vs/:user2" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <CompareBattle />
              </div>
            } />
            <Route path="/compare" element={
              <ComparePage />
            } />
            <Route path="/github-resume-alternative" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <GitHubResumeAlternative />
              </div>
            } />
            <Route path="/roast/:username" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <RoastShare />
              </div>
            } />
            <Route path="/share/:username" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <AnalysisShare />
              </div>
            } />
            <Route path="/compare/gitiq-vs-ossinsight" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <GitIQvsOSSInsight />
              </div>
            } />
            <Route path="/compare/gitiq-vs-gitawards" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <GitIQvsGitAwards />
              </div>
            } />
            <Route path="/compare/gitiq-vs-profile-summary" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <GitIQvsProfileSummary />
              </div>
            } />
            <Route path="/compare/gitiq-vs-gitroll" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <AlternativeToPage competitorKey="gitroll" isDark={true} />
              </div>
            } />
            <Route path="/compare/gitiq-vs-valyfy" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <AlternativeToPage competitorKey="valyfy" isDark={true} />
              </div>
            } />
            <Route path="/compare/gitiq-vs-gitlyser" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <AlternativeToPage competitorKey="gitlyser" isDark={true} />
              </div>
            } />
            <Route path="/compare/gitiq-vs-claritycode" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <AlternativeToPage competitorKey="claritycode" isDark={true} />
              </div>
            } />
            <Route path="/for-recruiters" element={
              <ForRecruiters />
            } />
            <Route path="/for-developers" element={
              <ForDevelopers />
            } />
            <Route path="/blog" element={
              <BlogIndex />
            } />
            <Route path="/blog/:slug" element={
              <BlogPost />
            } />
            <Route path="/top-developers" element={
              <GeographicHub isDark={true} />
            } />
            <Route path="/top-developers/:city" element={
              <GeographicHub isDark={true} />
            } />
            <Route path="/developers/:language/:location" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <DeveloperLanguageLocationHub isDark={true} />
              </div>
            } />
            <Route path="/companies/:company" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <CompanyHub isDark={true} />
              </div>
            } />
            <Route path="/compare-tech/:lang1-vs-:lang2" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <TechStackComparison isDark={true} />
              </div>
            } />
            <Route path="/404" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <NotFound404 />
              </div>
            } />
            <Route path="/about" element={
              <AboutPage isDark={true} />
            } />
            <Route path="/privacy" element={
              <PrivacyPage isDark={true} />
            } />
            <Route path="/terms" element={
              <TermsPage isDark={true} />
            } />
            <Route path="/contact" element={
              <ContactPage />
            } />
            <Route path="/leaderboard" element={<LeaderboardPage />} />
            <Route path="/admin" element={<AdminDashboard />} />
            <Route path="/me" element={<PersonalDashboard />} />
            <Route path="/tools" element={<ToolsHubPage />} />
            <Route path="/tools/career-roadmap" element={<CareerRoadmapPage />} />
            <Route path="/tools/readme-editor" element={<ReadmeEditorPage />} />
            <Route path="/tools/:toolName" element={<ToolPage />} />
            <Route path="/pricing" element={<PricingPage />} />
            <Route path="/best/:topic" element={<BestTopicPage />} />
            <Route path="/finishSignUp" element={<FinishSignUp />} />
            <Route path="*" element={
              <div className="container mx-auto px-4 pt-32 pb-12">
                <NotFound404 />
              </div>
            } />
          </Routes>
          </Suspense>
          </ErrorBoundary>
        </main>

        <Footer isDark={true} />

        <AuthModal
          isOpen={isAuthModalOpen}
          onClose={() => setIsAuthModalOpen(false)}
          isDark={true}
        />
        <CookieConsent />
        <OfflineBanner />
        <InstallPrompt />
        <UpdateNotification />
      </div>
    </div>
    </>
  );
}

export default App;
