import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  Accordion,
  Alert,
  Anchor,
  Badge,
  Box,
  Burger,
  Button,
  Container,
  Divider,
  Drawer,
  Grid,
  Group,
  Paper,
  Select,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
  Textarea,
  ThemeIcon,
  Title,
  useMantineTheme,
} from '@mantine/core';
import {
  IconActivity,
  IconAnchor,
  IconArrowRight,
  IconAward,
  IconBriefcase,
  IconCertificate,
  IconCheck,
  IconClipboardCheck,
  IconClock,
  IconCoin,
  IconCompass,
  IconExternalLink,
  IconFileCheck,
  IconGavel,
  IconGlobe,
  IconHelpCircle,
  IconLanguage,
  IconMail,
  IconMapPin,
  IconMessage,
  IconPhone,
  IconSchool,
  IconSend,
  IconShip,
  IconShieldCheck,
  IconTarget,
  IconUserCheck,
  IconUserCircle,
  IconUsers,
} from '@tabler/icons-react';
import { LanguageSwitcher } from '../layout/LanguageSwitcher';
import { ColorSchemeToggle } from '../layout/ColorSchemeToggle';
import './landing.css';

export interface LandingPageProps {
  /** Primary CTA target. Each app passes '/dashboard' when a session token
   * exists, else '/login'. Authenticated header state is derived from this
   * (anything other than '/login' counts as signed in) rather than a
   * separate prop, since libs/ui cannot import @ema-platform/auth. */
  primaryHref: string;
  /** Renders the "Create account" CTA only when set. Portal passes '/signup'; backoffice omits it (enableSignup: false). */
  signupHref?: string;
  supportedLanguages?: readonly string[];
}

const HEADER_HEIGHT = 72;

// Sections with a nav item, in page order — drives the scrollspy underline.
const NAV_SECTION_IDS = ['home', 'about', 'services', 'system', 'contact'] as const;

/** Tracks which nav section is currently under the sticky header, so the
 * header can underline it. Native IntersectionObserver — no scroll listener. */
function useActiveSection(ids: readonly string[]) {
  const [active, setActive] = useState<string>(ids[0]);

  useEffect(() => {
    const elements = ids
      .map((id) => document.getElementById(id))
      .filter((el): el is HTMLElement => el !== null);
    if (!elements.length) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.filter((entry) => entry.isIntersecting);
        if (visible.length === 0) return;
        const topMost = visible.reduce((a, b) => (a.boundingClientRect.top <= b.boundingClientRect.top ? a : b));
        setActive(topMost.target.id);
      },
      { rootMargin: `-${HEADER_HEIGHT}px 0px -70% 0px`, threshold: 0 },
    );
    elements.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, [ids]);

  return active;
}

export function LandingPage({
  primaryHref,
  signupHref,
  supportedLanguages = ['en', 'am'],
}: LandingPageProps) {
  const { t } = useTranslation();
  const isAuthed = primaryHref !== '/login';

  useEffect(() => {
    const handleAnchorClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      const anchor = target.closest<HTMLAnchorElement>('a[href^="#"]');
      if (!anchor) return;
      const href = anchor.getAttribute('href');
      if (!href || href === '#') return;

      const targetEl = document.querySelector(href);
      if (targetEl) {
        e.preventDefault();
        targetEl.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
        });
        window.history.pushState(null, '', href);
      }
    };

    document.addEventListener('click', handleAnchorClick);
    return () => document.removeEventListener('click', handleAnchorClick);
  }, []);

  return (
    <Box className="ema-landing" style={{ minHeight: '100dvh', background: 'var(--mantine-color-body)' }}>
      <Anchor
        href="#main"
        style={{
          position: 'absolute',
          left: 8,
          top: -60,
          zIndex: 1000,
          padding: '10px 16px',
          background: 'var(--mantine-color-body)',
          border: '1px solid var(--mantine-color-default-border)',
          borderRadius: 8,
          transition: 'top 120ms ease',
        }}
        onFocus={(e) => {
          e.currentTarget.style.top = '8px';
        }}
        onBlur={(e) => {
          e.currentTarget.style.top = '-60px';
        }}
      >
        {t('landing.meta.skipToContent')}
      </Anchor>

      <Header
        isAuthed={isAuthed}
        primaryHref={primaryHref}
        signupHref={signupHref}
        supportedLanguages={supportedLanguages}
      />

      <main id="main">
        <Hero primaryHref={primaryHref} signupHref={signupHref} isAuthed={isAuthed} />
        <StatsBanner />
        <About />
        <InstitutionalMandate />
        <Services />
        <Roles />
        <HowItWorks />
        <SystemHighlights />
        <Faq />
        <Contact />
      </main>

      <Footer />
    </Box>
  );
}

function NavAnchor({
  href,
  active,
  children,
  onClick,
}: {
  href: string;
  active?: boolean;
  children: React.ReactNode;
  onClick?: () => void;
}) {
  return (
    <Anchor
      href={href}
      underline="never"
      aria-current={active ? 'true' : undefined}
      c={active ? 'var(--mantine-primary-color-filled)' : 'var(--mantine-color-text)'}
      fw={500}
      fz="sm"
      onClick={onClick}
      style={{
        whiteSpace: 'nowrap',
        paddingBottom: 4,
        borderBottom: active ? '2px solid var(--mantine-primary-color-filled)' : '2px solid transparent',
        transition: 'color 120ms ease, border-color 120ms ease',
      }}
    >
      {children}
    </Anchor>
  );
}

function Header({
  isAuthed,
  primaryHref,
  signupHref,
  supportedLanguages,
}: {
  isAuthed: boolean;
  primaryHref: string;
  signupHref?: string;
  supportedLanguages: readonly string[];
}) {
  const { t } = useTranslation();
  const activeSection = useActiveSection(NAV_SECTION_IDS);
  const [drawerOpened, setDrawerOpened] = useState(false);

  const closeDrawer = () => setDrawerOpened(false);

  return (
    <Box
      component="header"
      style={{
        position: 'sticky',
        top: 0,
        zIndex: 100,
        height: HEADER_HEIGHT,
        background: 'var(--mantine-color-body)',
        borderBottom: '1px solid var(--mantine-color-default-border)',
      }}
    >
      <Container size="xl" h="100%">
        <Group h="100%" justify="space-between" wrap="nowrap" gap="md">
          <Anchor href="#home" underline="never" c="var(--mantine-color-text)">
            <Group gap="xs" wrap="nowrap">
              <Box component="img" src="/ema-logo.png" alt="" w={34} h={34} style={{ objectFit: 'contain' }} />
              <Text fw={700} fz="sm" visibleFrom="sm">
                {t('app.name')}
              </Text>
            </Group>
          </Anchor>

          {/* Desktop Navigation Links */}
          <Group gap="lg" wrap="nowrap" visibleFrom="md" component="nav" aria-label={t('landing.nav.home')}>
            <NavAnchor href="#home" active={activeSection === 'home'}>
              {t('landing.nav.home')}
            </NavAnchor>
            <NavAnchor href="#about" active={activeSection === 'about'}>
              {t('landing.nav.about')}
            </NavAnchor>
            <NavAnchor href="#services" active={activeSection === 'services'}>
              {t('landing.nav.services')}
            </NavAnchor>
            <NavAnchor href="#system" active={activeSection === 'system'}>
              {t('landing.nav.system')}
            </NavAnchor>
            <NavAnchor href="#contact" active={activeSection === 'contact'}>
              {t('landing.nav.contact')}
            </NavAnchor>
          </Group>

          {/* Controls & Mobile Hamburger */}
          <Group gap="xs" wrap="nowrap">
            <LanguageSwitcher supportedLanguages={supportedLanguages} />
            <ColorSchemeToggle />

            {/* Desktop Auth CTAs */}
            {isAuthed ? (
              <Button component={Link} to={primaryHref} size="sm" visibleFrom="xs">
                {t('landing.auth.dashboard')}
              </Button>
            ) : (
              <>
                <Button
                  component={Link}
                  to={primaryHref}
                  variant={signupHref ? 'subtle' : 'filled'}
                  size="sm"
                  visibleFrom="xs"
                >
                  {t('landing.auth.login')}
                </Button>
                {signupHref && (
                  <Button component={Link} to={signupHref} size="sm" visibleFrom="xs">
                    {t('landing.auth.signup')}
                  </Button>
                )}
              </>
            )}

            {/* Mobile Menu Burger Icon */}
            <Burger
              opened={drawerOpened}
              onClick={() => setDrawerOpened((o) => !o)}
              hiddenFrom="md"
              size="sm"
              aria-label="Toggle Navigation Menu"
            />
          </Group>
        </Group>
      </Container>

      {/* Mobile Drawer Menu */}
      <Drawer
        opened={drawerOpened}
        onClose={closeDrawer}
        size="75%"
        padding="md"
        hiddenFrom="md"
        title={
          <Group gap="xs">
            <Box component="img" src="/ema-logo.png" alt="" w={28} h={28} style={{ objectFit: 'contain' }} />
            <Text fw={700} fz="sm">
              {t('app.name')}
            </Text>
          </Group>
        }
      >
        <Stack gap="sm" mt="md">
          <Anchor
            href="#home"
            className="ema-drawer-nav-link"
            aria-current={activeSection === 'home' ? 'true' : undefined}
            onClick={closeDrawer}
          >
            {t('landing.nav.home')}
          </Anchor>
          <Anchor
            href="#about"
            className="ema-drawer-nav-link"
            aria-current={activeSection === 'about' ? 'true' : undefined}
            onClick={closeDrawer}
          >
            {t('landing.nav.about')}
          </Anchor>
          <Anchor
            href="#services"
            className="ema-drawer-nav-link"
            aria-current={activeSection === 'services' ? 'true' : undefined}
            onClick={closeDrawer}
          >
            {t('landing.nav.services')}
          </Anchor>
          <Anchor
            href="#system"
            className="ema-drawer-nav-link"
            aria-current={activeSection === 'system' ? 'true' : undefined}
            onClick={closeDrawer}
          >
            {t('landing.nav.system')}
          </Anchor>
          <Anchor
            href="#contact"
            className="ema-drawer-nav-link"
            aria-current={activeSection === 'contact' ? 'true' : undefined}
            onClick={closeDrawer}
          >
            {t('landing.nav.contact')}
          </Anchor>

          <Divider my="sm" />

          {/* Mobile Auth Actions */}
          {isAuthed ? (
            <Button component={Link} to={primaryHref} fullWidth size="md" onClick={closeDrawer}>
              {t('landing.auth.dashboard')}
            </Button>
          ) : (
            <Stack gap="xs">
              <Button component={Link} to={primaryHref} variant="outline" fullWidth size="md" onClick={closeDrawer}>
                {t('landing.auth.login')}
              </Button>
              {signupHref && (
                <Button component={Link} to={signupHref} fullWidth size="md" onClick={closeDrawer}>
                  {t('landing.auth.signup')}
                </Button>
              )}
            </Stack>
          )}
        </Stack>
      </Drawer>
    </Box>
  );
}

const HERO_BADGE_ICONS = {
  secure: IconShieldCheck,
  bilingual: IconLanguage,
  tracking: IconActivity,
} as const;

function Hero({
  primaryHref,
  signupHref,
  isAuthed,
}: {
  primaryHref: string;
  signupHref?: string;
  isAuthed: boolean;
}) {
  const { t } = useTranslation();
  const theme = useMantineTheme();
  const badgeKeys = Object.keys(HERO_BADGE_ICONS) as (keyof typeof HERO_BADGE_ICONS)[];

  return (
    <Box
      id="home"
      component="section"
      pos="relative"
      style={{
        background: theme.other?.heroGradient as string,
        color: 'white',
        overflow: 'hidden',
      }}
    >
      {/* Decorative pulse circles */}
      <Box
        className="ema-hero-pulse"
        pos="absolute"
        top={-120}
        right={-100}
        w={420}
        h={420}
        style={{ borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }}
      />
      <Box
        className="ema-hero-pulse"
        pos="absolute"
        bottom={-160}
        left={-120}
        w={380}
        h={380}
        style={{ borderRadius: '50%', background: 'rgba(255,255,255,0.06)' }}
      />
      <Box
        pos="absolute"
        top="30%"
        left="8%"
        w={140}
        h={140}
        visibleFrom="md"
        style={{ borderRadius: '50%', background: 'rgba(255,255,255,0.05)' }}
      />

      <Container size="xl" py={{ base: 88, sm: 120, lg: 148 }} pos="relative">
        <Stack gap="lg" align="center" ta="center" className="ema-landing-fade">
          {/* Floating live status pill */}
          <Badge
            size="lg"
            variant="light"
            color="white"
            radius="xl"
            leftSection={<span className="ema-live-dot" style={{ marginRight: 4 }} />}
            style={{ textTransform: 'none', fontWeight: 600, backdropFilter: 'blur(6px)' }}
          >
            {t('landing.hero.livePill')}
          </Badge>

          <Title order={1} fz={{ base: 34, sm: 48, lg: 56 }} lh={1.1} maw={860}>
            {t('landing.hero.title')}
          </Title>
          <Text fz={{ base: 'md', sm: 'xl' }} fw={500} maw={680} style={{ opacity: 0.95 }}>
            {t('landing.hero.subtitle')}
          </Text>
          <Text fz={{ base: 'sm', sm: 'md' }} maw={600} style={{ opacity: 0.84 }}>
            {t('landing.hero.description')}
          </Text>

          {/* Dual CTAs */}
          <Group justify="center" gap="md" mt="xs">
            <Button
              component={Link}
              to={isAuthed ? primaryHref : (signupHref ?? '/login')}
              size="lg"
              variant="white"
              color="dark"
              leftSection={<IconShip size={20} />}
              style={{ boxShadow: '0 8px 24px rgba(0,0,0,0.18)' }}
            >
              {isAuthed ? t('landing.auth.dashboard') : t('landing.cta.getStarted')}
            </Button>
            <Button
              component="a"
              href="#services"
              size="lg"
              variant="outline"
              color="white"
              leftSection={<IconBriefcase size={20} />}
              style={{ backdropFilter: 'blur(8px)', backgroundColor: 'rgba(255,255,255,0.12)' }}
            >
              {t('landing.cta.exploreServices')}
            </Button>
          </Group>

          {/* Feature Badges */}
          <Group gap="xs" mt="xl" justify="center" wrap="wrap">
            {badgeKeys.map((key) => {
              const Icon = HERO_BADGE_ICONS[key];
              return (
                <Group
                  key={key}
                  gap={6}
                  wrap="nowrap"
                  px="sm"
                  py={6}
                  style={{
                    borderRadius: 999,
                    background: 'rgba(255,255,255,0.14)',
                    border: '1px solid rgba(255,255,255,0.22)',
                  }}
                >
                  <Icon size={14} />
                  <Text fz="xs" fw={600}>
                    {t(`landing.hero.badges.${key}`)}
                  </Text>
                </Group>
              );
            })}
          </Group>
        </Stack>
      </Container>
    </Box>
  );
}

/** Institutional Impact Statistics Counter Banner */
function StatsBanner() {
  const { t } = useTranslation();
  return (
    <Box className="ema-stats-banner" py={36}>
      <Container size="xl">
        <SimpleGrid cols={{ base: 2, sm: 4 }} spacing="lg">
          <Stack gap={2} align="center" ta="center">
            <Group gap={6} align="center">
              <ThemeIcon size={36} radius="xl" variant="light" color="emaPrimary">
                <IconUsers size={18} />
              </ThemeIcon>
              <Text fz={{ base: 26, sm: 32 }} fw={800} className="ema-text-gradient">
                {t('landing.stats.seafarersVal')}
              </Text>
            </Group>
            <Text fz="xs" fw={600} c="dimmed">
              {t('landing.stats.seafarers')}
            </Text>
          </Stack>

          <Stack gap={2} align="center" ta="center">
            <Group gap={6} align="center">
              <ThemeIcon size={36} radius="xl" variant="light" color="emaTeal">
                <IconShip size={18} />
              </ThemeIcon>
              <Text fz={{ base: 26, sm: 32 }} fw={800} className="ema-text-gradient">
                {t('landing.stats.vesselsVal')}
              </Text>
            </Group>
            <Text fz="xs" fw={600} c="dimmed">
              {t('landing.stats.vessels')}
            </Text>
          </Stack>

          <Stack gap={2} align="center" ta="center">
            <Group gap={6} align="center">
              <ThemeIcon size={36} radius="xl" variant="light" color="emaPrimary">
                <IconShieldCheck size={18} />
              </ThemeIcon>
              <Text fz={{ base: 26, sm: 32 }} fw={800} className="ema-text-gradient">
                {t('landing.stats.efficiencyVal')}
              </Text>
            </Group>
            <Text fz="xs" fw={600} c="dimmed">
              {t('landing.stats.efficiency')}
            </Text>
          </Stack>

          <Stack gap={2} align="center" ta="center">
            <Group gap={6} align="center">
              <ThemeIcon size={36} radius="xl" variant="light" color="emaTeal">
                <IconClock size={18} />
              </ThemeIcon>
              <Text fz={{ base: 26, sm: 32 }} fw={800} className="ema-text-gradient">
                {t('landing.stats.availabilityVal')}
              </Text>
            </Group>
            <Text fz="xs" fw={600} c="dimmed">
              {t('landing.stats.availability')}
            </Text>
          </Stack>
        </SimpleGrid>
      </Container>
    </Box>
  );
}

function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) {
  return (
    <Stack gap={6} align="center" ta="center" mb="xl" maw={640} mx="auto">
      <Title order={2} fz={{ base: 24, sm: 30 }}>
        {title}
      </Title>
      {subtitle && (
        <Text c="dimmed" fz="md" fw={500}>
          {subtitle}
        </Text>
      )}
    </Stack>
  );
}

function About() {
  const { t } = useTranslation();
  return (
    <Box id="about" component="section" py={72}>
      <Container size="xl">
        <SectionHeading title={t('landing.about.title')} subtitle={t('landing.about.eyebrow')} />
        <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="xl">
          <Paper withBorder radius="lg" p="xl" className="ema-landing-hover ema-vision-card">
            <Stack gap="sm">
              <Group gap="xs">
                <ThemeIcon size={32} radius="md" variant="light" color="emaPrimary">
                  <IconCompass size={18} />
                </ThemeIcon>
                <Text fw={700} c="var(--mantine-primary-color-filled)" tt="uppercase" fz="xs" style={{ letterSpacing: 0.8 }}>
                  {t('landing.about.visionLabel')}
                </Text>
              </Group>
              <Text fz="sm" style={{ lineHeight: 1.6 }}>
                {t('landing.about.vision')}
              </Text>
            </Stack>
          </Paper>

          <Paper withBorder radius="lg" p="xl" className="ema-landing-hover ema-mission-card">
            <Stack gap="sm">
              <Group gap="xs">
                <ThemeIcon size={32} radius="md" variant="light" color="emaTeal">
                  <IconTarget size={18} />
                </ThemeIcon>
                <Text fw={700} c="#009879" tt="uppercase" fz="xs" style={{ letterSpacing: 0.8 }}>
                  {t('landing.about.missionLabel')}
                </Text>
              </Group>
              <Text fz="sm" style={{ lineHeight: 1.6 }}>
                {t('landing.about.mission')}
              </Text>
            </Stack>
          </Paper>
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const MANDATE_ICONS = {
  safety: { icon: IconShieldCheck, color: 'blue' },
  logistics: { icon: IconShip, color: 'emaTeal' },
  stcw: { icon: IconSchool, color: 'emaPrimary' },
  flagState: { icon: IconAnchor, color: 'indigo' },
} as const;

function InstitutionalMandate() {
  const { t } = useTranslation();
  const items = Object.keys(MANDATE_ICONS) as (keyof typeof MANDATE_ICONS)[];
  return (
    <Box id="mandate" component="section" py={72}>
      <Container size="xl">
        <SectionHeading title={t('landing.mandate.title')} subtitle={t('landing.mandate.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="lg">
          {items.map((key) => {
            const { icon: Icon, color } = MANDATE_ICONS[key];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" className="ema-landing-hover ema-landing-card-accent">
                <Stack gap="sm" align="flex-start" justify="space-between" h="100%">
                  <Stack gap="xs">
                    <ThemeIcon size={44} radius="lg" variant="light" color={color}>
                      <Icon size={22} />
                    </ThemeIcon>
                    <Text fw={700} fz="md">
                      {t(`landing.mandate.items.${key}.title`)}
                    </Text>
                    <Text c="dimmed" fz="sm" style={{ lineHeight: 1.6 }}>
                      {t(`landing.mandate.items.${key}.description`)}
                    </Text>
                  </Stack>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const SERVICE_ICONS = {
  seafarerRegistration: IconUserCheck,
  vesselRegistration: IconShip,
  licensing: IconBriefcase,
  examinations: IconSchool,
  medical: IconActivity,
  waivers: IconGavel,
} as const;

function Services() {
  const { t } = useTranslation();
  const items = Object.keys(SERVICE_ICONS) as (keyof typeof SERVICE_ICONS)[];
  return (
    <Box id="services" component="section" py={72} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <Container size="xl">
        <SectionHeading title={t('landing.services.title')} subtitle={t('landing.services.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="lg">
          {items.map((key) => {
            const Icon = SERVICE_ICONS[key];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" className="ema-landing-hover ema-landing-card-accent">
                <Stack gap="sm" justify="space-between" h="100%">
                  <Stack gap="xs">
                    <ThemeIcon size={44} radius="md" variant="light" color="emaPrimary">
                      <Icon size={22} />
                    </ThemeIcon>
                    <Text fw={700} fz="md">
                      {t(`landing.services.items.${key}.title`)}
                    </Text>
                    <Text c="dimmed" fz="sm" style={{ lineHeight: 1.6 }}>
                      {t(`landing.services.items.${key}.description`)}
                    </Text>
                  </Stack>
                  <Group justify="space-between" align="center" mt="xs" pt="xs" style={{ borderTop: '1px solid var(--mantine-color-default-border)' }}>
                    <Text fz="xs" fw={600} c="var(--mantine-primary-color-filled)">
                      {t('landing.cta.exploreServices')}
                    </Text>
                    <IconArrowRight size={16} className="ema-card-arrow" />
                  </Group>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const ROLE_ICONS = {
  seafarers: { icon: IconShip, color: 'emaTeal' },
  vesselOwners: { icon: IconAnchor, color: 'emaPrimary' },
  agents: { icon: IconBriefcase, color: 'indigo' },
  reviewers: { icon: IconGavel, color: 'yellow' },
} as const;

function Roles() {
  const { t } = useTranslation();
  const items = Object.keys(ROLE_ICONS) as (keyof typeof ROLE_ICONS)[];
  return (
    <Box id="roles" component="section" py={72}>
      <Container size="xl">
        <SectionHeading title={t('landing.roles.title')} subtitle={t('landing.roles.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="lg">
          {items.map((key) => {
            const { icon: Icon, color } = ROLE_ICONS[key];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" ta="center" className="ema-landing-hover ema-landing-card-accent">
                <Stack gap="sm" align="center">
                  <ThemeIcon size={48} radius="xl" variant="light" color={color}>
                    <Icon size={24} />
                  </ThemeIcon>
                  <Text fw={600}>{t(`landing.roles.${key}.title`)}</Text>
                  <Text c="dimmed" fz="sm">
                    {t(`landing.roles.${key}.description`)}
                  </Text>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const STEP_KEYS = ['createAccount', 'submitApplication', 'fulfillRequirements', 'payFees', 'receiveCertificate'] as const;
const STEP_ICONS = [IconUserCheck, IconClipboardCheck, IconActivity, IconCoin, IconCertificate];

function HowItWorks() {
  const { t } = useTranslation();
  return (
    <Box id="how-it-works" component="section" py={72} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <Container size="xl">
        <SectionHeading title={t('landing.howItWorks.title')} subtitle={t('landing.howItWorks.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2, lg: 5 }} spacing="lg">
          {STEP_KEYS.map((key, i) => {
            const Icon = STEP_ICONS[i];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" className="ema-landing-hover ema-landing-card-accent" ta="center">
                <Stack gap="xs" align="center" justify="space-between" h="100%">
                  <Stack gap="xs" align="center">
                    <Badge size="xs" variant="filled" radius="xl" color="emaPrimary">
                      Step 0{i + 1}
                    </Badge>
                    <ThemeIcon size={48} radius="xl" variant="light" color="emaPrimary">
                      <Icon size={24} />
                    </ThemeIcon>
                    <Text fw={700} fz="sm">
                      {t(`landing.howItWorks.steps.${key}.title`)}
                    </Text>
                    <Text c="dimmed" fz="xs" style={{ lineHeight: 1.5 }}>
                      {t(`landing.howItWorks.steps.${key}.description`)}
                    </Text>
                  </Stack>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const SYSTEM_ICONS = {
  secure: IconShieldCheck,
  bilingual: IconLanguage,
  tracking: IconActivity,
  singleAccount: IconUserCircle,
  payments: IconCoin,
  framework: IconClipboardCheck,
} as const;

function SystemHighlights() {
  const { t } = useTranslation();
  const items = Object.keys(SYSTEM_ICONS) as (keyof typeof SYSTEM_ICONS)[];
  return (
    <Box id="system" component="section" py={72}>
      <Container size="xl">
        <SectionHeading title={t('landing.system.title')} subtitle={t('landing.system.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="lg">
          {items.map((key) => {
            const Icon = SYSTEM_ICONS[key];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" className="ema-landing-hover ema-landing-card-accent">
                <Stack gap="sm" align="flex-start">
                  <ThemeIcon size={44} radius="xl" variant="light" color="emaPrimary">
                    <Icon size={22} />
                  </ThemeIcon>
                  <Text fw={700} fz="md">
                    {t(`landing.system.items.${key}.title`)}
                  </Text>
                  <Text c="dimmed" fz="sm" style={{ lineHeight: 1.6 }}>
                    {t(`landing.system.items.${key}.description`)}
                  </Text>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const FAQ_KEYS = ['whatIsPortal', 'whoCanUse', 'howToApply', 'isFree'] as const;
const FAQ_ICONS = {
  whatIsPortal: IconHelpCircle,
  whoCanUse: IconUsers,
  howToApply: IconFileCheck,
  isFree: IconCoin,
} as const;

function Faq() {
  const { t } = useTranslation();
  return (
    <Box id="faq" component="section" py={72} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <Container size="xl">
        <SectionHeading title={t('landing.faq.title')} subtitle={t('landing.faq.eyebrow')} />
        <Grid gutter="xl">
          {/* Left Column: Direct Support Box */}
          <Grid.Col span={{ base: 12, md: 4 }}>
            <Paper
              component={Stack}
              gap="md"
              p="xl"
              radius="lg"
              withBorder
              className="ema-landing-hover ema-contact-hq-card"
            >
              <ThemeIcon size={44} radius="lg" variant="light" color="emaPrimary">
                <IconHelpCircle size={24} />
              </ThemeIcon>

              <Stack gap={4}>
                <Text fw={700} fz="lg">
                  {t('landing.faq.eyebrow')}
                </Text>
                <Text fz="sm" c="dimmed" style={{ lineHeight: 1.6 }}>
                  {t('landing.faq.supportPrompt')}
                </Text>
              </Stack>

              <Button
                component="a"
                href="#contact"
                variant="filled"
                color="emaPrimary"
                leftSection={<IconMessage size={18} />}
                radius="md"
              >
                {t('landing.faq.contactSupport')}
              </Button>

              <Divider my={4} />

              <Group gap="xs" align="center">
                <ThemeIcon size={28} radius="xl" variant="light" color="emaTeal">
                  <IconPhone size={14} />
                </ThemeIcon>
                <Stack gap={0}>
                  <Text fz="xs" fw={700}>
                    {t('landing.footer.emergencyLabel')}
                  </Text>
                  <Text fz="xs" c="dimmed" fw={600}>
                    {t('landing.footer.emergencyValue')}
                  </Text>
                </Stack>
              </Group>
            </Paper>
          </Grid.Col>

          {/* Right Column: Accordion Cards */}
          <Grid.Col span={{ base: 12, md: 8 }}>
            <Accordion variant="separated" radius="lg" className="ema-faq-accordion">
              {FAQ_KEYS.map((key) => {
                const Icon = FAQ_ICONS[key];
                return (
                  <Accordion.Item key={key} value={key}>
                    <Accordion.Control
                      icon={
                        <ThemeIcon size={32} radius="md" variant="light" color="emaPrimary">
                          <Icon size={18} />
                        </ThemeIcon>
                      }
                    >
                      <Text fw={600} fz="md">
                        {t(`landing.faq.items.${key}.question`)}
                      </Text>
                    </Accordion.Control>
                    <Accordion.Panel>
                      <Text fz="sm" c="dimmed" style={{ lineHeight: 1.6 }} pl={42}>
                        {t(`landing.faq.items.${key}.answer`)}
                      </Text>
                    </Accordion.Panel>
                  </Accordion.Item>
                );
              })}
            </Accordion>
          </Grid.Col>
        </Grid>
      </Container>
    </Box>
  );
}

function Contact() {
  const { t } = useTranslation();

  return (
    <Box id="contact" component="section" py={72}>
      <Container size="xl">
        <SectionHeading title={t('landing.contact.title')} subtitle={t('landing.contact.subtitle')} />

        <SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing="lg" maw={1080} mx="auto">
          {/* Address Card */}
          <Paper
            withBorder
            radius="lg"
            p="xl"
            className="ema-landing-hover ema-contact-hq-card"
            style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}
          >
            <Stack gap="md">
              <ThemeIcon size={44} radius="lg" variant="light" color="emaPrimary">
                <IconMapPin size={24} />
              </ThemeIcon>
              <Stack gap={4}>
                <Text fw={700} fz="sm">
                  {t('landing.contact.addressLabel')}
                </Text>
                <Text c="dimmed" fz="sm" style={{ lineHeight: 1.6 }}>
                  {t('landing.contact.address')}
                </Text>
              </Stack>
            </Stack>
            <Button
              component="a"
              href="https://maps.google.com/?q=Sunshine+Building+Addis+Ababa"
              target="_blank"
              rel="noreferrer"
              variant="light"
              color="emaPrimary"
              size="xs"
              leftSection={<IconExternalLink size={14} />}
              w="fit-content"
              mt="lg"
            >
              {t('landing.contact.getDirections')}
            </Button>
          </Paper>

          {/* Direct Phone & Website Card */}
          <Paper
            withBorder
            radius="lg"
            p="xl"
            className="ema-landing-hover"
            style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}
          >
            <Stack gap="md">
              <Group gap="sm" align="center" wrap="nowrap">
                <ThemeIcon size={38} radius="md" variant="light" color="emaTeal">
                  <IconPhone size={18} />
                </ThemeIcon>
                <Stack gap={2}>
                  <Text fw={600} fz="xs" c="dimmed">
                    {t('landing.contact.phoneLabel')}
                  </Text>
                  <Anchor href="tel:+251115150299" fw={700} fz="sm">
                    +251 011 515 0299
                  </Anchor>
                </Stack>
              </Group>

              <Divider />

              <Group gap="sm" align="center" wrap="nowrap">
                <ThemeIcon size={38} radius="md" variant="light" color="emaPrimary">
                  <IconGlobe size={18} />
                </ThemeIcon>
                <Stack gap={2}>
                  <Text fw={600} fz="xs" c="dimmed">
                    {t('landing.contact.websiteLabel')}
                  </Text>
                  <Anchor href="https://etmaritime.com" target="_blank" rel="noreferrer" fw={700} fz="sm">
                    etmaritime.com
                  </Anchor>
                </Stack>
              </Group>

              <Divider />

              <Group gap="sm" align="center" wrap="nowrap">
                <ThemeIcon size={38} radius="md" variant="light" color="emaTeal">
                  <IconClock size={18} />
                </ThemeIcon>
                <Stack gap={2}>
                  <Text fw={600} fz="xs" c="dimmed">
                    {t('landing.footer.hoursLabel')}
                  </Text>
                  <Text fz="xs" fw={600}>
                    {t('landing.footer.hoursValue')}
                  </Text>
                </Stack>
              </Group>
            </Stack>
          </Paper>

          {/* Emergency Hotline Banner */}
          <Paper
            radius="lg"
            p="xl"
            style={{
              background: 'linear-gradient(135deg, #1e3a8a 0%, #0d9488 100%)',
              color: '#ffffff',
              display: 'flex',
              flexDirection: 'column',
              justify: 'center',
            }}
          >
            <Stack gap="md" align="flex-start">
              <ThemeIcon size={48} radius="xl" color="white" variant="white" c="blue.9">
                <IconShieldCheck size={26} />
              </ThemeIcon>
              <Stack gap={4}>
                <Text fz="xs" fw={700} tt="uppercase" style={{ letterSpacing: 0.5, opacity: 0.9 }}>
                  {t('landing.footer.emergencyLabel')}
                </Text>
                <Text fz="xl" fw={800}>
                  {t('landing.footer.emergencyValue')}
                </Text>
                <Text fz="xs" style={{ opacity: 0.85, lineHeight: 1.5 }}>
                  24/7 Operational assistance for maritime safety, vessel incidents, and urgent operational support.
                </Text>
              </Stack>
            </Stack>
          </Paper>
        </SimpleGrid>
      </Container>
    </Box>
  );
}

function Footer() {
  const { t } = useTranslation();
  return (
    <Box component="footer" py={48} style={{ borderTop: '1px solid var(--mantine-color-default-border)', background: 'var(--mantine-color-body)' }}>
      <Container size="xl">
        <SimpleGrid cols={{ base: 1, sm: 2, md: 4 }} spacing="xl" mb="xl">
          {/* Col 1: Brand & Overview */}
          <Stack gap="sm">
            <Group gap="xs">
              <Box component="img" src="/ema-logo.png" alt="" w={32} h={32} style={{ objectFit: 'contain' }} />
              <Text fw={700} fz="sm">
                {t('landing.hero.title')}
              </Text>
            </Group>
            <Text fz="xs" c="dimmed" style={{ lineHeight: 1.6 }}>
              {t('landing.footer.tagline')}
            </Text>
          </Stack>

          {/* Col 2: Quick Links */}
          <Stack gap="xs">
            <Text fw={600} fz="sm">
              {t('landing.footer.quickLinks')}
            </Text>
            <Anchor href="#home" fz="xs" c="dimmed" underline="hover">
              {t('landing.nav.home')}
            </Anchor>
            <Anchor href="#about" fz="xs" c="dimmed" underline="hover">
              {t('landing.nav.about')}
            </Anchor>
            <Anchor href="#services" fz="xs" c="dimmed" underline="hover">
              {t('landing.nav.services')}
            </Anchor>
            <Anchor href="#system" fz="xs" c="dimmed" underline="hover">
              {t('landing.nav.system')}
            </Anchor>
            <Anchor href="#contact" fz="xs" c="dimmed" underline="hover">
              {t('landing.nav.contact')}
            </Anchor>
          </Stack>

          {/* Col 3: Core Services */}
          <Stack gap="xs">
            <Text fw={600} fz="sm">
              {t('landing.footer.servicesHeading')}
            </Text>
            <Text fz="xs" c="dimmed">
              {t('landing.services.items.seafarerRegistration.title')}
            </Text>
            <Text fz="xs" c="dimmed">
              {t('landing.services.items.vesselRegistration.title')}
            </Text>
            <Text fz="xs" c="dimmed">
              {t('landing.services.items.licensing.title')}
            </Text>
            <Text fz="xs" c="dimmed">
              {t('landing.services.items.examinations.title')}
            </Text>
          </Stack>

          {/* Col 4: Support & Hotline */}
          <Stack gap="xs">
            <Text fw={600} fz="sm">
              {t('landing.footer.contactHeading')}
            </Text>
            <Text fz="xs" c="dimmed">
              <strong>{t('landing.footer.hoursLabel')}:</strong> {t('landing.footer.hoursValue')}
            </Text>
            <Text fz="xs" c="dimmed">
              <strong>{t('landing.footer.emergencyLabel')}:</strong> {t('landing.footer.emergencyValue')}
            </Text>
          </Stack>
        </SimpleGrid>

        <Divider my="md" />

        <Group justify="space-between" wrap="wrap" gap="sm">
          <Text fz="xs" c="dimmed">
            © 2026 {t('landing.hero.title')} — {t('landing.footer.rights')}
          </Text>
          <Group gap="md">
            <Anchor href="https://etmaritime.com" target="_blank" rel="noreferrer" fz="xs" c="dimmed">
              etmaritime.com
            </Anchor>
          </Group>
        </Group>
      </Container>
    </Box>
  );
}
