import React, { useState, useEffect } from 'react';
import { Layout } from './components/Layout';
import { HomePage } from './pages/HomePage';
import { ProgrammesPage } from './pages/ProgrammesPage';
import { CourseDetailPage } from './pages/CourseDetailPage';
import { OrganisationsPage } from './pages/OrganisationsPage';
import { AboutPage } from './pages/AboutPage';
import { CareerSupportPage } from './pages/CareerSupportPage';
import { LearningPage } from './pages/LearningPage';
import { ServicesPage } from './pages/ServicesPage';
import { LearnerAccessPage } from './pages/LearnerAccessPage';
import { LegalPage } from './pages/LegalPage';
import { WorkshopsPage, PartnershipsPage } from './pages/Pages';
import { ContactPage, EnquiryMode } from './pages/ContactPage';
import { NotFoundPage } from './pages/NotFoundPage';
import { findCourseBySlug } from './data/courses';
import { ComparisonProvider } from './context/ComparisonContext';
import { ComparisonDock } from './components/ComparisonDock';
import { ComparisonDrawer } from './components/ComparisonDrawer';
import { QuickWhatsAppDesk } from './components/QuickWhatsAppDesk';

export default function App() {
  const getHashPath = () => {
    const hash = window.location.hash.replace(/^#/, '');
    if (!hash || hash === '') return '/';
    return hash;
  };

  const [currentRoute, setCurrentRoute] = useState<string>(getHashPath());

  useEffect(() => {
    const handleHashChange = () => {
      setCurrentRoute(getHashPath());
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  const navigate = (path: string) => {
    window.location.hash = path;
    setCurrentRoute(path);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Extract path and search params from currentRoute
  const [pathname, queryString] = currentRoute.split('?');
  const searchParams = new URLSearchParams(queryString || '');

  // Dynamic SEO metadata updates on client route change
  useEffect(() => {
    let title = 'PANIA Digital Academy | Online Skills Training in Nairobi, Kenya';
    let description =
      'Building skills. Advancing careers. Strengthening workplaces. Explore 22 fully online programmes in Cloud, AI, Cybersecurity, and Work Readiness with PANIA.';

    if (pathname === '' || pathname === '/') {
      title = 'PANIA Digital Academy | Online Skills Training in Nairobi, Kenya';
      description =
        'Building skills. Advancing careers. Strengthening workplaces. Explore 22 fully online programmes in Cloud, AI, Cybersecurity, and Work Readiness with PANIA.';
    } else if (pathname === '/programmes') {
      title = 'Online Programmes & Certifications | PANIA Digital Academy';
      description =
        'Explore 22 industry-aligned online programmes in AWS, Google Cloud, Microsoft Azure, AI, Cybersecurity, and Work Readiness in Nairobi.';
    } else if (pathname.startsWith('/programmes/')) {
      const slug = pathname.replace('/programmes/', '').replace(/^\//, '');
      const course = findCourseBySlug(slug);
      if (course) {
        title = `${course.title} | PANIA Digital Academy`;
        description = `${course.headline[0]} ${course.headline[1]} Target audience: ${course.who} Delivered 100% online via live video & WhatsApp.`;
      } else {
        title = 'Programme Not Found | PANIA Digital Academy';
        description = 'The requested training programme could not be found. Explore our 22 online programmes in cloud and AI.';
      }
    } else if (pathname === '/organisations') {
      title = 'Enterprise Upskilling & Corporate Training | PANIA Digital Academy';
      description =
        'Customized technical upskilling, corporate workshops, and workforce transformation for businesses and engineering teams in Kenya and East Africa.';
    } else if (pathname === '/organisations/aws-workshops') {
      title = 'AWS Workshops for Organizations | PANIA Digital Academy';
      description =
        'Intensive, tailored AWS cloud and architecture workshops designed for corporate engineering teams and tech leads.';
    } else if (pathname === '/organisations/partnerships') {
      title = 'Institutional & Community Partnerships | PANIA Digital Academy';
      description =
        'Partner with PANIA Digital Academy for digital skills capacity building, tech talent development, and community impact.';
    } else if (pathname === '/career-support') {
      title = 'Career Support & Work Readiness | PANIA Digital Academy';
      description =
        'Bridge the gap between training and employment with CV reviews, portfolio coaching, interview preparation, and freelance readiness.';
    } else if (pathname === '/about') {
      title = 'About PANIA Digital Academy | Mission, Leadership & Online Model';
      description =
        'Learn about PANIA Digital Academy\'s mission to bridge Africa\'s digital skills gap with accessible, live online tech education.';
    } else if (pathname === '/learning') {
      title = 'How Online Learning Works | PANIA Digital Academy';
      description =
        'Experience flexible, live online learning delivered via Zoom, Google Meet, and dedicated WhatsApp cohort groups.';
    } else if (pathname === '/services') {
      title = 'Digital Services & Advisory | PANIA Digital Academy';
      description =
        'Technology consulting, cloud architecture advisory, corporate digital training, and workforce enablement services.';
    } else if (pathname === '/contact') {
      title = 'Contact Admissions & Enquiries | PANIA Digital Academy';
      description =
        'Get in touch with PANIA Digital Academy admissions. Request course fee guides, cohort schedules, or custom team training proposals.';
    } else if (pathname === '/learner-access') {
      title = 'Learner Access & LMS Portal | PANIA Digital Academy';
      description =
        'Access the PANIA Learning Management System (LMS), live Zoom session schedules, lab environments, and course materials.';
    } else if (pathname === '/privacy') {
      title = 'Privacy Notice & Data Protection | PANIA Digital Academy';
      description =
        'PANIA Digital Academy privacy policy, student data protection guidelines, and online enquiry processing commitments.';
    } else if (pathname === '/terms') {
      title = 'Terms of Service & Operational Policies | PANIA Digital Academy';
      description =
        'Terms of service, cohort admissions policies, curriculum alignment standards, and code of conduct for PANIA Digital Academy.';
    } else {
      title = 'Page Not Found | PANIA Digital Academy';
      description =
        'The page you are looking for does not exist. Browse our programmes or return to the homepage.';
    }

    // Apply title
    document.title = title;

    // Apply description meta tag
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) {
      metaDesc.setAttribute('content', description);
    }

    // Apply OpenGraph and Twitter tags
    const ogTitle = document.querySelector('meta[property="og:title"]');
    if (ogTitle) ogTitle.setAttribute('content', title);

    const ogDesc = document.querySelector('meta[property="og:description"]');
    if (ogDesc) ogDesc.setAttribute('content', description);

    const twitterTitle = document.querySelector('meta[name="twitter:title"]');
    if (twitterTitle) twitterTitle.setAttribute('content', title);

    const twitterDesc = document.querySelector('meta[name="twitter:description"]');
    if (twitterDesc) twitterDesc.setAttribute('content', description);
  }, [pathname]);

  const renderRoute = () => {
    // 1. Home
    if (pathname === '' || pathname === '/') {
      return <HomePage onNavigate={navigate} />;
    }

    // 2. Canonical Course Detail: /programmes/:slug
    if (pathname.startsWith('/programmes/')) {
      const slug = pathname.replace('/programmes/', '').replace(/^\//, '');
      const course = findCourseBySlug(slug);
      if (course) {
        return <CourseDetailPage course={course} onNavigate={navigate} />;
      }
      return <NotFoundPage onNavigate={navigate} onSearch={(q) => navigate(`/programmes?q=${encodeURIComponent(q)}`)} />;
    }

    // 3. Programmes Catalogue: /programmes
    if (pathname === '/programmes') {
      return (
        <ProgrammesPage
          onNavigateCourse={(slug) => navigate(`/programmes/${slug}`)}
          initialQuery={searchParams.get('q') || ''}
          initialSubject={searchParams.get('subject') || ''}
          initialProvider={searchParams.get('provider') || ''}
          initialCompare={searchParams.get('compare') || ''}
        />
      );
    }

    // 4. Organisations
    if (pathname === '/organisations') {
      return <OrganisationsPage onNavigate={navigate} />;
    }

    // 5. AWS Workshops: /organisations/aws-workshops
    if (pathname === '/organisations/aws-workshops') {
      return <WorkshopsPage onNavigate={navigate} />;
    }

    // 6. Partnerships: /organisations/partnerships
    if (pathname === '/organisations/partnerships') {
      return <PartnershipsPage onNavigate={navigate} />;
    }

    // 7. Career Support: /career-support
    if (pathname === '/career-support') {
      return (
        <CareerSupportPage
          onNavigate={navigate}
          onOpenEnquiry={(m) => navigate(`/contact?mode=${m || 'learner'}`)}
        />
      );
    }

    // 8. About: /about
    if (pathname === '/about') {
      return (
        <AboutPage
          onNavigate={navigate}
          onOpenEnquiry={(m) => navigate(`/contact?mode=${m || 'learner'}`)}
        />
      );
    }

    // 9. Learning Online: /learning
    if (pathname === '/learning') {
      return (
        <LearningPage
          onNavigate={navigate}
          onOpenEnquiry={(m) => navigate(`/contact?mode=${m || 'learner'}`)}
        />
      );
    }

    // 10. Services: /services
    if (pathname === '/services') {
      return (
        <ServicesPage
          onNavigate={navigate}
          onOpenEnquiry={(m) => navigate(`/contact?mode=${m || 'learner'}`)}
        />
      );
    }

    // 11. Learner Access & LMS: /learner-access
    if (pathname === '/learner-access') {
      return (
        <LearnerAccessPage
          onNavigate={navigate}
          onOpenEnquiry={(m) => navigate(`/contact?mode=${m || 'learner'}`)}
        />
      );
    }

    // 12. Privacy Notice: /privacy
    if (pathname === '/privacy') {
      return <LegalPage type="privacy" onNavigate={navigate} />;
    }

    // 13. Terms of Service: /terms
    if (pathname === '/terms') {
      return <LegalPage type="terms" onNavigate={navigate} />;
    }

    // 14. Contact: /contact
    if (pathname === '/contact') {
      const mode = (searchParams.get('mode') as EnquiryMode) || 'learner';
      const courseSlug = searchParams.get('course') || '';
      const topic = searchParams.get('topic') || '';
      const plan = searchParams.get('plan') || '';
      const currency = searchParams.get('currency') || '';
      return (
        <ContactPage
          onNavigate={navigate}
          initialMode={mode}
          initialCourse={courseSlug}
          initialTopic={topic}
          initialPlan={plan}
          initialCurrency={currency}
        />
      );
    }

    // Default 404
    return <NotFoundPage onNavigate={navigate} onSearch={(q) => navigate(`/programmes?q=${encodeURIComponent(q)}`)} />;
  };

  return (
    <ComparisonProvider>
      <Layout currentPath={pathname} onNavigate={navigate}>
        {renderRoute()}
      </Layout>
      <ComparisonDock />
      <ComparisonDrawer onNavigate={navigate} />
      <QuickWhatsAppDesk />
    </ComparisonProvider>
  );
}
