import { layout, colors, theme, transition, fontWeights, fonts } from 'theme'
import { track } from '@vercel/analytics'
import { issueUrl } from 'helpers/issue-url'
import FeatherIcon from 'components/icons/Feather'
import React, { useState, useCallback, useId } from 'react'

import IntersectionObserver from '../../elements/IntersectionObserver'
import Healthcheck from '../Healthcheck/Healthcheck'

import Choose from 'components/elements/Choose'
import Container from 'components/elements/Container'
import Caps from 'components/elements/Caps'
import Box from 'components/elements/Box'
import Email from 'components/elements/Email'
import { Button } from 'components/elements/Button/Button'
import Flex from 'components/elements/Flex'
import Input from 'components/elements/Input/Input'
import Text from 'components/elements/Text'
import { Link } from 'components/elements/Link'
import Dot from 'components/elements/Dot/Dot'
import { ChevronDown, Mail } from 'react-feather'
import styled from 'styled-components'

import { LANG_LANDINGS } from 'components/pages/screenshot/lang/registry'
import { FEATURES } from 'components/patterns/FeatureStory'

const FOOTER_COLUMNS = [
  {
    title: 'Products',
    links: [
      { label: 'Screenshot', href: '/screenshot' },
      { label: 'Link Preview', href: '/link-preview' },
      { label: 'Markdown', href: '/markdown' },
      { label: 'Metadata', href: '/metadata' },
      { label: 'Embed', href: '/embed' },
      { label: 'PDF', href: '/pdf' },
      { label: 'Logo', href: '/logo' },
      { label: 'Insights', href: '/insights' },
      { label: 'Unavatar', href: 'https://unavatar.io' }
    ],
    sections: [
      {
        // Per-language screenshot landings, generated from the shared registry
        // so a new /screenshot/<lang> spoke is linked site-wide automatically.
        title: 'Screenshot API',
        links: LANG_LANDINGS.map(({ label, href }) => ({ label, href }))
      }
    ]
  },
  {
    title: 'Resources',
    links: [
      { label: 'SDK', href: '/integrations/sdk' },
      { label: 'CLI', href: '/integrations/cli' },
      { label: 'Blog', href: '/blog' },
      { label: 'Use cases', href: '/use-cases' },
      { label: 'Extensions', href: '/extensions' },
      { label: 'Changelog', href: '/changelog' },
      { label: 'Community', href: '/community' },
      { label: 'Benchmark', href: '/benchmarks/screenshot-api' },
      { label: 'Open Source', href: '/open-source' },
      { label: 'Skills', href: '/skills' },
      { label: 'User Agents', href: '/user-agents' },
      { label: 'Geolocation', href: 'https://geolocation.microlink.io' }
    ],
    sections: [
      {
        // Feature landings, generated from the shared registry so a new
        // /features/<slug> page is linked site-wide automatically.
        title: 'Features',
        links: FEATURES.map(({ footerLabel, slug }) => ({
          label: footerLabel,
          href: `/features/${slug}`
        }))
      }
    ]
  },
  {
    title: 'Company',
    links: [
      { label: 'About', href: '/about' },
      { label: 'Bug Reports', href: issueUrl.bug() },
      { label: 'Contact', href: 'mailto:hello@microlink.io' },
      { label: 'GitHub', href: 'https://github.com/microlinkhq' },
      {
        label: 'LinkedIn',
        href: 'https://www.linkedin.com/company/microlinkhq'
      },
      { label: 'X/Twitter', href: 'https://x.com/microlinkhq' }
    ],
    groups: [
      {
        title: 'Legal',
        links: [
          { label: 'DPA', href: '/dpa' },
          { label: 'Privacy policy', href: '/privacy' },
          { label: 'Terms of service', href: '/tos' }
        ]
      }
    ]
  },
  {
    title: 'Tools',
    links: [
      { label: 'Sharing Debugger', href: '/tools/sharing-debugger' },
      { label: 'Website Screenshot', href: '/tools/website-screenshot' },
      { label: 'Embed URL', href: '/tools/embed-url' },
      { label: 'URL to Markdown', href: '/tools/url-to-markdown' },
      { label: 'Website to PDF', href: '/tools/website-to-pdf' },
      { label: 'Bulk Screenshots', href: '/tools/website-screenshot/bulk' },
      { label: 'Bulk URLs to PDFs', href: '/tools/website-to-pdf/bulk' },
      {
        label: 'Full page Screenshot',
        href: '/tools/website-screenshot/full-page'
      },
      {
        label: 'Mobile Screenshot',
        href: '/tools/website-screenshot/mobile'
      },
      {
        label: 'Animated Screenshot',
        href: '/tools/website-screenshot/animated'
      },
      { label: 'Embed Providers', href: '/embed/providers' }
    ]
  },
  {
    title: 'Comparisons',
    links: [
      { label: 'vs ApiFlash', href: '/alternative/apiflash' },
      { label: 'vs Cloudflare', href: '/alternative/cloudflare' },
      { label: 'vs Context.dev', href: '/alternative/context-dev' },
      { label: 'vs Embedly', href: '/alternative/embedly' },
      { label: 'vs Firecrawl', href: '/alternative/firecrawl' },
      { label: 'vs Iframely', href: '/alternative/iframely' },
      { label: 'vs ScreenshotAPI', href: '/alternative/screenshotapi' },
      { label: 'vs ScreenshotLayer', href: '/alternative/screenshotlayer' },
      { label: 'vs ScreenshotMachine', href: '/alternative/screenshotmachine' },
      { label: 'vs ScreenshotOne', href: '/alternative/screenshotone' },
      { label: 'vs Thum.io', href: '/alternative/thumio' },
      { label: 'vs Url2Png', href: '/alternative/url2png' },
      { label: 'vs Urlbox', href: '/alternative/urlbox' }
    ]
  }
]

const primaryColor = colors.black60
const secondaryColor = colors.black40

const dotStyle = theme({
  pl: 2,
  fontSize: 0,
  color: 'black50',
  transition: `color ${transition.medium}`,
  _hover: { color: 'black' }
})

const linkStyles = theme({
  color: primaryColor,
  textDecoration: 'none',
  fontSize: 1,
  display: 'inline-block',
  opacity: 1,
  _hover: {
    color: 'black',
    opacity: 1,
    '& svg': {
      stroke: 'black'
    }
  }
})

const StatusPage = () => (
  <Link
    data-event-location='Footer'
    data-event-name='Status'
    href='/status'
    css={theme({
      px: 0,
      color: primaryColor,
      textDecoration: 'none',
      opacity: 1
    })}
  >
    <Text css={theme({ fontSize: 1 })}>Status</Text>
  </Link>
)

const Health = () => (
  <Healthcheck>
    {({ isHealthy, isLoading }) => {
      if (isLoading) return <StatusPage />
      return (
        <Link
          data-event-location='Footer'
          data-event-name='Status'
          href='/status'
        >
          <Flex css={theme({ alignItems: 'center' })}>
            <Choose>
              <Choose.When condition={isHealthy}>
                <Dot.Success />
                <Text css={dotStyle}>All systems operational</Text>
              </Choose.When>
              <Choose.Otherwise>
                <Dot.Warning />
                <Text css={dotStyle}>System performance degradation</Text>
              </Choose.Otherwise>
            </Choose>
          </Flex>
        </Link>
      )
    }}
  </Healthcheck>
)

const DisclosurePanel = styled(Box)`
  opacity: 0;
  transform: translateY(-4px);
  pointer-events: none;
  visibility: hidden;
  transition: opacity ${transition.short}, transform ${transition.short};

  &[data-open='true'] {
    opacity: 1;
    transform: translateY(0);
    pointer-events: auto;
    visibility: visible;
  }
`

const DisclosureChevron = styled(ChevronDown)`
  transition: transform ${transition.short};

  &[data-open='true'] {
    transform: rotate(180deg);
  }
`

const DisclosureTrigger = styled('button')`
  appearance: none;
  border: 0;
  background: transparent;
  padding: 0;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-family: inherit;
`

const FooterLinkList = ({ links }) => (
  <Flex
    as='ul'
    css={theme({
      flexDirection: 'column',
      listStyle: 'none',
      m: 0,
      p: 0,
      gap: 2
    })}
  >
    {links.map(({ label, href }) => (
      <Box as='li' key={href}>
        <Link
          href={href}
          data-event-location='Footer'
          data-event-name={label}
          css={linkStyles}
        >
          {label}
        </Link>
      </Box>
    ))}
  </Flex>
)

const FooterGroup = ({ title, links }) => {
  const [isOpen, setIsOpen] = useState(false)
  const toggle = useCallback(() => setIsOpen(prev => !prev), [])
  const panelId = `${useId()}-footer-group`

  return (
    <Box css={{ position: 'relative' }}>
      <DisclosureTrigger
        type='button'
        onClick={toggle}
        aria-expanded={isOpen}
        aria-controls={panelId}
      >
        <Text as='span' css={linkStyles}>
          {title}
        </Text>
        <DisclosureChevron size={12} data-open={isOpen} />
      </DisclosureTrigger>
      <DisclosurePanel
        id={panelId}
        data-open={isOpen}
        css={theme({
          position: 'absolute',
          left: 0,
          mt: 2,
          background: colors.white,
          border: `1px solid ${colors.black10}`,
          borderRadius: 2,
          px: 3,
          py: 3,
          zIndex: 1,
          minWidth: '180px'
        })}
      >
        <FooterLinkList links={links} />
      </DisclosurePanel>
    </Box>
  )
}

const FooterColumnTitle = ({ children, css }) => (
  <Caps
    css={theme({
      fontSize: 0,
      color: secondaryColor,
      mb: 3,
      letterSpacing: 3,
      ...css
    })}
  >
    {children}
  </Caps>
)

const FooterColumn = ({ title, links, groups, sections }) => (
  <Box>
    <FooterColumnTitle>{title}</FooterColumnTitle>
    <Flex
      css={theme({
        flexDirection: 'column',
        gap: 2
      })}
    >
      <FooterLinkList links={links} />
      {sections &&
        sections.map(section => (
          <Box key={section.title} css={theme({ pt: 3 })}>
            <FooterColumnTitle>{section.title}</FooterColumnTitle>
            <FooterLinkList links={section.links} />
          </Box>
        ))}
      {groups &&
        groups.map(group => <FooterGroup key={group.title} {...group} />)}
    </Flex>
  </Box>
)

const activeColumns = FOOTER_COLUMNS.filter(
  col => col.links.length > 0 || (col.groups && col.groups.length > 0)
)

const GiantEmail = () => (
  <Box
    as='a'
    href='mailto:hello@microlink.io'
    aria-label='hello@microlink.io'
    onClick={() => track('Email', { location: 'Footer' })}
    css={theme({
      display: 'block',
      opacity: 0.08,
      transition: `opacity ${transition.medium}`,
      _hover: { opacity: 0.16 }
    })}
  >
    <Box
      as='svg'
      viewBox='0 0 1000 128'
      preserveAspectRatio='xMinYMax meet'
      css={theme({
        display: 'block',
        width: '100%'
      })}
    >
      <Email
        as='text'
        x='0'
        y='100'
        textLength='1000'
        lengthAdjust='spacingAndGlyphs'
        fontFamily={fonts.sans}
        fontSize='130'
        fontWeight={fontWeights.bold}
        fill={colors.black}
      >
        hello@microlink.io
      </Email>
    </Box>
  </Box>
)

const Footer = ({ ...props }) => {
  return (
    <Container
      css={theme({
        px: 0,
        maxWidth: layout.large,
        pb: 5
      })}
    >
      <Box
        css={theme({
          background: colors.white,
          borderRadius: 3,
          px: 3,
          pt: [4, 4, 5, 5],
          pb: [4, 4, 4, 4]
        })}
        {...props}
      >
        <Box
          css={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, 1fr)',
            gap: '32px 24px',
            '@media (min-width: 768px)': {
              gridTemplateColumns: `repeat(${activeColumns.length}, 1fr)`
            }
          }}
        >
          {activeColumns.map(column => (
            <FooterColumn key={column.title} {...column} />
          ))}
        </Box>

        <Flex
          css={theme({
            mt: [3, 3, 4, 4],
            pt: [3, 3, 4, 4],
            borderTop: `1px solid ${colors.black05}`,
            flexDirection: ['column', 'column', 'row', 'row'],
            justifyContent: 'space-between',
            alignItems: ['flex-start', 'flex-start', 'center', 'center'],
            gap: 3
          })}
        >
          <Flex
            css={theme({
              alignItems: 'center',
              flexWrap: 'wrap'
            })}
          >
            <Text
              css={theme({
                color: 'black50',
                fontSize: 0,
                pr: 2
              })}
            >
              &copy; {new Date().getFullYear()} Microlink
            </Text>
            <IntersectionObserver
              placeholder={() => <StatusPage />}
              onView={() => <Health />}
            />
          </Flex>

          <form
            action='https://microlink.us17.list-manage.com/subscribe/post?u=13504896341022a643b87c538&id=0d0978d452'
            method='post'
          >
            <input type='hidden' name='tags' value='50279' />
            <Flex css={theme({ alignItems: 'center' })}>
              <Input
                type='email'
                name='EMAIL'
                placeholder='you@domain.com'
                iconComponent={
                  <FeatherIcon
                    icon={Mail}
                    color={secondaryColor}
                    size={[0, 0, 1, 1]}
                  />
                }
                css={theme({ fontSize: 0, width: '8rem' })}
                labelCss={{
                  borderColor: colors.black10,
                  '&:hover': { borderColor: secondaryColor },
                  '&:focus-within': {
                    borderColor: colors.black80,
                    boxShadow: 'none'
                  }
                }}
                required
              />
              <Button
                data-event-location='Footer'
                data-event-name='Be Notified'
                variant='black'
                css={theme({ ml: 2 })}
              >
                <Caps css={theme({ fontSize: 0 })}>Be Notified</Caps>
              </Button>
            </Flex>
          </form>
        </Flex>

        <Box css={theme({ mt: [4, 4, 5, 5] })}>
          <GiantEmail />
        </Box>
      </Box>
    </Container>
  )
}

export default Footer
