import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  Accordion,
  Anchor,
  Box,
  Button,
  Container,
  Group,
  Paper,
  SimpleGrid,
  Stack,
  Text,
  ThemeIcon,
  Title,
  useMantineTheme,
} from '@mantine/core';
import {
  IconActivity,
  IconAnchor,
  IconAward,
  IconBriefcase,
  IconCertificate,
  IconClipboardCheck,
  IconGavel,
  IconLanguage,
  IconMail,
  IconMapPin,
  IconPhone,
  IconSchool,
  IconShip,
  IconShieldCheck,
  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);
      },
      // Counts a section only once it has cleared the sticky header, and only
      // while it's still in the top 30% of the viewport.
      { 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';

  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} />
        <About />
        <QuickAccess />
        <Services />
        <Roles />
        <HowItWorks />
        <SystemHighlights />
        <Faq />
        <Contact />
      </main>

      <Footer />
    </Box>
  );
}

function NavAnchor({
  href,
  active,
  children,
}: {
  href: string;
  active?: boolean;
  children: React.ReactNode;
}) {
  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"
      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);

  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>

          <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>

          <Group gap="xs" wrap="nowrap">
            <LanguageSwitcher supportedLanguages={supportedLanguages} />
            <ColorSchemeToggle />
            {isAuthed ? (
              <Button component={Link} to={primaryHref} size="sm" visibleFrom="xs">
                {t('landing.auth.dashboard')}
              </Button>
            ) : (
              <>
                {/* Login is the secondary action next to Sign Up when both
                    exist (portal) — but when there's no signup (backoffice,
                    enableSignup: false), it's the only action, so it takes
                    the filled/primary treatment instead of reading like a
                    leftover half of a pair. */}
                <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>
                )}
              </>
            )}
          </Group>
        </Group>
      </Container>
    </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 glow circles — same device as AuthShell's hero panel. */}
      <Box
        pos="absolute"
        top={-120}
        right={-100}
        w={420}
        h={420}
        style={{ borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }}
      />
      <Box
        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">
          <Text fz="sm" fw={600} style={{ opacity: 0.85, letterSpacing: 0.5 }}>
            {t('landing.hero.eyebrow')}
          </Text>
          <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.82 }}>
            {t('landing.hero.description')}
          </Text>

          <Group justify="center">
            <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>
          </Group>

          <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.12)',
                    border: '1px solid rgba(255,255,255,0.18)',
                  }}
                >
                  <Icon size={14} />
                  <Text fz="xs" fw={600}>
                    {t(`landing.hero.badges.${key}`)}
                  </Text>
                </Group>
              );
            })}
          </Group>
        </Stack>
      </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">
          {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')} />
        <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="xl">
          <Paper withBorder radius="lg" p="xl">
            <Stack gap="xs">
              <Text fw={700} c="var(--mantine-primary-color-filled)" tt="uppercase" fz="xs" style={{ letterSpacing: 0.5 }}>
                {t('landing.about.visionLabel')}
              </Text>
              <Text>{t('landing.about.vision')}</Text>
            </Stack>
          </Paper>
          <Paper withBorder radius="lg" p="xl">
            <Stack gap="xs">
              <Text fw={700} c="var(--mantine-primary-color-filled)" tt="uppercase" fz="xs" style={{ letterSpacing: 0.5 }}>
                {t('landing.about.missionLabel')}
              </Text>
              <Text>{t('landing.about.mission')}</Text>
            </Stack>
          </Paper>
        </SimpleGrid>
      </Container>
    </Box>
  );
}

function QuickAccessCard({
  icon: Icon,
  title,
  description,
  href,
}: {
  icon: typeof IconCertificate;
  title: string;
  description: string;
  href?: string;
}) {
  const body = (
    <Stack gap="sm">
      <ThemeIcon size={44} radius="md" variant="light">
        <Icon size={22} />
      </ThemeIcon>
      <Text fw={600}>{title}</Text>
      <Text c="dimmed" fz="sm">
        {description}
      </Text>
    </Stack>
  );
  const cardStyle = { display: 'block', height: '100%', textDecoration: 'none', color: 'inherit' } as const;

  return href ? (
    <Paper component={Link} to={href} withBorder radius="lg" p="lg" className="ema-landing-hover" style={cardStyle}>
      {body}
    </Paper>
  ) : (
    <Paper withBorder radius="lg" p="lg" className="ema-landing-hover" style={cardStyle}>
      {body}
    </Paper>
  );
}

function QuickAccess() {
  const { t } = useTranslation();
  return (
    <Box id="quick-access" component="section" py={72} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <Container size="xl">
        <SectionHeading title={t('landing.quickAccess.title')} subtitle={t('landing.quickAccess.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="lg">
          <QuickAccessCard
            icon={IconShip}
            title={t('landing.quickAccess.vesselRegistration.title')}
            description={t('landing.quickAccess.vesselRegistration.description')}
          />
          <QuickAccessCard
            icon={IconAnchor}
            title={t('landing.quickAccess.notices.title')}
            description={t('landing.quickAccess.notices.description')}
          />
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const SERVICE_ICONS = {
  seafarerRegistration: IconUserCheck,
  vesselRegistration: IconShip,
  licensing: IconBriefcase,
  examinations: IconSchool,
  waivers: IconShieldCheck,
} 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}>
      <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">
                <Stack gap="sm">
                  <ThemeIcon size={44} radius="md" variant="light">
                    <Icon size={22} />
                  </ThemeIcon>
                  <Text fw={600}>{t(`landing.services.items.${key}.title`)}</Text>
                  <Text c="dimmed" fz="sm">
                    {t(`landing.services.items.${key}.description`)}
                  </Text>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const ROLE_ICONS = {
  seafarers: IconShip,
  vesselOwners: IconAnchor,
  agents: IconBriefcase,
  reviewers: IconGavel,
} 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} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <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 = ROLE_ICONS[key];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" ta="center">
                <Stack gap="sm" align="center">
                  <ThemeIcon size={48} radius="xl" variant="light">
                    <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 = ['selectRole', 'createAccount', 'submitApplication', 'trackStatus', 'receiveApproval'] as const;
const STEP_ICONS = [IconUsers, IconUserCheck, IconClipboardCheck, IconAward, IconCertificate];

function HowItWorks() {
  const { t } = useTranslation();
  return (
    <Box id="how-it-works" component="section" py={72}>
      <Container size="xl">
        <SectionHeading title={t('landing.howItWorks.title')} subtitle={t('landing.howItWorks.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 5 }} spacing="lg">
          {STEP_KEYS.map((key, i) => {
            const Icon = STEP_ICONS[i];
            return (
              <Stack key={key} gap="xs" align="center" ta="center">
                <ThemeIcon size={48} radius="xl" variant="filled" color="var(--mantine-primary-color-filled)">
                  <Icon size={22} />
                </ThemeIcon>
                <Text fw={600} fz="sm">
                  {i + 1}. {t(`landing.howItWorks.steps.${key}`)}
                </Text>
              </Stack>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const SYSTEM_ICONS = {
  secure: IconShieldCheck,
  bilingual: IconLanguage,
  tracking: IconActivity,
  singleAccount: IconUserCircle,
} 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} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <Container size="xl">
        <SectionHeading title={t('landing.system.title')} subtitle={t('landing.system.subtitle')} />
        <SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="lg">
          {items.map((key) => {
            const Icon = SYSTEM_ICONS[key];
            return (
              <Paper key={key} withBorder radius="lg" p="lg" ta="center">
                <Stack gap="sm" align="center">
                  <ThemeIcon size={48} radius="xl" variant="light">
                    <Icon size={24} />
                  </ThemeIcon>
                  <Text fw={600}>{t(`landing.system.items.${key}.title`)}</Text>
                  <Text c="dimmed" fz="sm">
                    {t(`landing.system.items.${key}.description`)}
                  </Text>
                </Stack>
              </Paper>
            );
          })}
        </SimpleGrid>
      </Container>
    </Box>
  );
}

const FAQ_KEYS = ['whatIsPortal', 'whoCanUse', 'howToApply', 'isFree'] as const;

function Faq() {
  const { t } = useTranslation();
  return (
    <Box component="section" py={72}>
      <Container size="sm">
        <SectionHeading title={t('landing.faq.title')} />
        <Accordion variant="separated" radius="lg">
          {FAQ_KEYS.map((key) => (
            <Accordion.Item key={key} value={key}>
              <Accordion.Control>{t(`landing.faq.items.${key}.question`)}</Accordion.Control>
              <Accordion.Panel>{t(`landing.faq.items.${key}.answer`)}</Accordion.Panel>
            </Accordion.Item>
          ))}
        </Accordion>
      </Container>
    </Box>
  );
}

function Contact() {
  const { t } = useTranslation();
  return (
    <Box id="contact" component="section" py={72} style={{ background: 'var(--mantine-color-default-hover)' }}>
      <Container size="xl">
        <SectionHeading title={t('landing.contact.title')} subtitle={t('landing.contact.subtitle')} />
        <Paper withBorder radius="lg" p="xl" maw={560} mx="auto" component="address" style={{ fontStyle: 'normal' }}>
          <Stack gap="lg">
            <Group gap="md" wrap="nowrap" align="flex-start">
              <ThemeIcon size={38} radius="md" variant="light">
                <IconMapPin size={18} />
              </ThemeIcon>
              <Stack gap={2}>
                <Text fw={600} fz="sm">
                  {t('landing.contact.addressLabel')}
                </Text>
                <Text c="dimmed" fz="sm">
                  {t('landing.contact.address')}
                </Text>
              </Stack>
            </Group>
            <Group gap="md" wrap="nowrap" align="flex-start">
              <ThemeIcon size={38} radius="md" variant="light">
                <IconPhone size={18} />
              </ThemeIcon>
              <Stack gap={2}>
                <Text fw={600} fz="sm">
                  {t('landing.contact.phoneLabel')}
                </Text>
                <Anchor href="tel:+251115150299" fz="sm">
                  +251 011 515 0299
                </Anchor>
              </Stack>
            </Group>
            <Group gap="md" wrap="nowrap" align="flex-start">
              <ThemeIcon size={38} radius="md" variant="light">
                <IconMail size={18} />
              </ThemeIcon>
              <Stack gap={2}>
                <Text fw={600} fz="sm">
                  {t('landing.contact.websiteLabel')}
                </Text>
                <Anchor href="https://etmaritime.com" target="_blank" rel="noreferrer" fz="sm">
                  etmaritime.com
                </Anchor>
              </Stack>
            </Group>
          </Stack>
        </Paper>
      </Container>
    </Box>
  );
}

function Footer() {
  const { t } = useTranslation();
  return (
    <Box component="footer" py="xl" style={{ borderTop: '1px solid var(--mantine-color-default-border)' }}>
      <Container size="xl">
        <Group justify="space-between" wrap="wrap" gap="sm">
          <Group gap="xs">
            <Box component="img" src="/ema-logo.png" alt="" w={24} h={24} style={{ objectFit: 'contain' }} />
            <Text fz="sm" c="dimmed">
              {t('landing.hero.title')}
            </Text>
          </Group>
          <Text fz="sm" c="dimmed">
            © 2026 {t('landing.hero.title')} — {t('landing.footer.rights')}
          </Text>
        </Group>
      </Container>
    </Box>
  );
}
