'use client'

import { useEffect, useState } from 'react'
import { Lottie } from 'lottie-react'
import backgroundAnimation from '@/app/assets/Image/Hero_BG_Animation_1.json'
import { AppleIcon, GooglePlayIcon } from '@/app/assets/svg/icon'
import { Text } from '@/components/ui'
import { cn } from '@/lib/utils'

const ANDROID_URL = 'https://play.google.com/store/apps/details?id=com.payseypay'
const WEBSITE_URL = 'https://payseypay.com'
const IOS_URL = process.env.NEXT_PUBLIC_IOS_APP_URL?.trim() || ''

const storeButtonClass = cn(
  'relative z-[1] inline-flex h-[52px] min-w-[174px] items-center justify-center gap-2 overflow-hidden rounded-full',
  'bg-secondary px-6 text-base font-semibold text-white transition-transform duration-300',
  "after:absolute after:bottom-0 after:left-0 after:z-[-2] after:h-full after:w-full after:rounded-full after:content-['']",
  "before:absolute before:bottom-0 before:left-0 before:z-[-1] before:h-full before:w-0 before:rounded-full before:bg-[#017A43] before:transition-all before:duration-300 before:content-['']",
  'hover:-translate-y-0.5 hover:before:w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/45',
)

type NavigatorWithUAData = Navigator & {
  userAgentData?: {
    platform?: string
  }
}

function getDeviceType() {
  const nav = navigator as NavigatorWithUAData
  const ua = nav.userAgent || ''
  const platform = `${nav.userAgentData?.platform || ''} ${nav.platform || ''}`
  const combined = `${ua} ${platform}`
  const touchPoints = Number(nav.maxTouchPoints || 0)

  const explicitAndroid = /Android/i.test(combined)
  // Some Android tablets present Chrome as X11/Linux desktop. Touch is the
  // differentiator that worked with the Paysey test tablet.
  const maskedAndroidTablet = !explicitAndroid && /Linux|X11/i.test(combined) && touchPoints > 0
  const isAndroid = explicitAndroid || maskedAndroidTablet
  const isIOS = /iPhone|iPad|iPod/i.test(ua) || (/Mac/i.test(platform) && touchPoints > 1)
  const isDesktop = !isAndroid && !isIOS && /Windows NT|Macintosh|MacIntel|CrOS|X11|Linux x86_64/i.test(combined)

  return { isAndroid, isIOS, isDesktop }
}

export const DownloadPage = () => {
  const [showIosNote, setShowIosNote] = useState(false)

  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    if (params.has('manual') || params.has('debug')) return

    const { isAndroid, isIOS, isDesktop } = getDeviceType()

    if (isAndroid) {
      window.location.replace(ANDROID_URL)
      return
    }

    if (isIOS && IOS_URL) {
      window.location.replace(IOS_URL)
      return
    }

    if (isDesktop) {
      window.location.replace(WEBSITE_URL)
    }
  }, [])

  const handleIos = () => {
    if (IOS_URL) {
      window.location.assign(IOS_URL)
      return
    }

    setShowIosNote(true)
  }

  return (
    <section className='relative isolate flex min-h-[calc(100dvh-70px)] items-center overflow-hidden bg-primary px-5 py-16 sm:py-20 lg:px-[50px]'>
      {/* Exact animated background used by the live Home/Solutions hero. */}
      <div aria-hidden='true' className='pointer-events-none absolute left-0 right-0 -top-50 -z-10 h-full w-full overflow-hidden'>
        <Lottie src={backgroundAnimation} autoplay loop className='h-full w-full' />
      </div>

      <div className='container relative z-10 flex w-full items-center justify-center'>
        <div className='mx-auto flex w-full max-w-[980px] flex-col items-center text-center'>
          <div className='mb-6 flex items-center justify-center gap-3 sm:mb-8'>
            <span className='h-2.5 w-2.5 rounded-full bg-secondary shadow-[0_0_18px_rgba(2,150,83,0.7)]' aria-hidden='true' />
            <Text
              size='normal'
              className='font-semibold uppercase tracking-[0.17em] text-secondary'
              textKey='Get the Paysey Pay app'
            />
          </div>

          <Text
            as='h1'
            size='h1'
            className='max-w-[950px] uppercase leading-[0.98] text-white sm:leading-[1.02] 2xl:leading-[1.08]'
          >
            <span className='block'>Your money, your way with</span>
            <span className='gradient-text mt-2 block'>Paysey Pay!</span>
          </Text>

          <Text
            size='normal'
            className='mt-7 max-w-[730px] text-center leading-7 text-white/80 sm:mt-8'
            textKey='One secure platform for your everyday payments. Open this official Paysey Pay link on any device and we will guide you to the right destination.'
          />

          <div className='mt-9 flex w-full flex-col items-center justify-center gap-3 sm:mt-10 sm:w-auto sm:flex-row sm:gap-4'>
            <button type='button' onClick={handleIos} className={cn(storeButtonClass, 'w-full sm:w-auto')}>
              <AppleIcon />
              <span>App Store</span>
            </button>

            <a href={ANDROID_URL} className={cn(storeButtonClass, 'w-full sm:w-auto')} rel='noopener noreferrer'>
              <GooglePlayIcon />
              <span>Google Play</span>
            </a>
          </div>

          <div className='mt-4 min-h-6' aria-live='polite'>
            {showIosNote && (
              <Text
                size='text'
                className='text-white/65'
                textKey='Paysey Pay for iOS is coming soon.'
              />
            )}
          </div>

        </div>
      </div>
    </section>
  )
}
