'use client'

import { AnimatePresence, m, useInView, useReducedMotion } from 'framer-motion'
import {
  BatteryFullIcon,
  BellIcon,
  FileTextIcon,
  GlobeIcon,
  HouseIcon,
  MenuIcon,
  ShieldCheckIcon,
  ShoppingCartIcon,
  SignalIcon,
  WifiIcon
} from 'lucide-react'
import Image from 'next/image'
import { useEffect, useRef, useState } from 'react'
import { APP_NAME } from '@/shared/config/app'
import { cn } from '@/shared/lib/utils'

type FeedEvent = {
  id: number
  kind: 'order' | 'form'
  title: string
  body: string
}

const KIND_ICON = { order: ShoppingCartIcon, form: FileTextIcon }

const TIME_LABELS = [
  'только что',
  '2 мин назад',
  '9 мин назад',
  '16 мин назад',
  '34 мин назад'
]

// Demo events in the same wording as real notifications of the app
const makeEvent = (id: number): FeedEvent => {
  switch (id % 4) {
    case 1:
      return {
        id,
        kind: 'form',
        title: 'Новая заявка с формы',
        body: 'korzilla.ru · «Обратный звонок»'
      }
    case 3:
      return {
        id,
        kind: 'form',
        title: 'Новая заявка с формы',
        body: 'kzla.ru · «Задать вопрос»'
      }
    default:
      return {
        id,
        kind: 'order',
        title: 'На сайте новый заказ',
        body: `kzla.ru · заказ №${46860 + id}`
      }
  }
}

const FEED_SIZE = 4
const PUSH_INTERVAL_MS = 4500

export const HeroPhone = () => {
  const rootRef = useRef<HTMLDivElement>(null)
  const inView = useInView(rootRef, { margin: '-15% 0px' })
  const reduceMotion = useReducedMotion()
  const [items, setItems] = useState(() => [4, 3, 2, 1].map(makeEvent))
  const [banner, setBanner] = useState<FeedEvent | null>(null)
  const [unread, setUnread] = useState(3)
  const nextId = useRef(5)

  // A new "push" every few seconds, only while the phone is on screen
  useEffect(() => {
    if (!inView || reduceMotion) return

    const timers: ReturnType<typeof setTimeout>[] = []
    const push = () => {
      const event = makeEvent(nextId.current++)
      setBanner(event)
      timers.push(
        setTimeout(() => {
          setItems((prev) => [event, ...prev].slice(0, FEED_SIZE))
          setUnread((count) => count + 1)
        }, 900),
        setTimeout(() => setBanner(null), 2600)
      )
    }
    timers.push(setTimeout(push, 1200))
    const interval = setInterval(push, PUSH_INTERVAL_MS)

    return () => {
      clearInterval(interval)
      timers.forEach(clearTimeout)
    }
  }, [inView, reduceMotion])

  const unreadLabel = unread > 9 ? '9+' : String(unread)

  return (
    <div
      ref={rootRef}
      role='img'
      aria-label={`Пример ленты уведомлений в приложении ${APP_NAME}`}
      className='relative mx-auto w-fit'
    >
      {/* "Signal" rings and glow behind the phone */}
      <div
        aria-hidden
        className='absolute left-1/2 top-1/2 -z-10 size-[34rem] -translate-x-1/2 -translate-y-1/2'
      >
        {[0, 1.5, 3].map((delay) => (
          <span
            key={delay}
            className='absolute inset-0 rounded-full border border-primary/30 opacity-0 motion-safe:animate-pulse-ring motion-reduce:opacity-40'
            style={{ animationDelay: `${delay}s` }}
          />
        ))}
        <span className='absolute inset-[22%] rounded-full bg-primary/25 blur-3xl' />
      </div>

      {/* Floating chips */}
      <div
        aria-hidden
        className='absolute -left-48 top-52 z-10 hidden items-center gap-3 rounded-2xl border bg-background/80 p-3 pr-4 shadow-xl backdrop-blur-md md:flex lg:hidden xl:flex motion-safe:animate-float'
      >
        <span className='flex size-9 items-center justify-center rounded-xl bg-primary/10 text-primary'>
          <GlobeIcon className='size-4' />
        </span>
        <span className='text-sm leading-tight'>
          <span className='block font-semibold'>Все сайты в одной ленте</span>
          <span className='block text-xs text-muted-foreground'>
            kzla.ru, korzilla.ru и другие
          </span>
        </span>
      </div>
      <div
        aria-hidden
        className='absolute -right-44 bottom-24 z-10 hidden items-center gap-3 rounded-2xl border bg-background/80 p-3 pr-4 shadow-xl backdrop-blur-md md:flex lg:hidden xl:flex motion-safe:animate-float'
        style={{ animationDelay: '-3.5s' }}
      >
        <span className='flex size-9 items-center justify-center rounded-xl bg-primary/10 text-primary'>
          <ShieldCheckIcon className='size-4' />
        </span>
        <span className='text-sm leading-tight'>
          <span className='block font-semibold'>Доступ для команды</span>
          <span className='block text-xs text-muted-foreground'>
            Администратор · Менеджер
          </span>
        </span>
      </div>

      {/* Phone */}
      <div
        aria-hidden
        className='relative w-[17.5rem] rounded-[2.9rem] bg-neutral-950 p-2.5 shadow-2xl shadow-primary/25 ring-1 ring-black/10 sm:w-[18.75rem] dark:ring-white/15'
      >
        <span className='absolute -left-[3px] top-28 h-12 w-[3px] rounded-l bg-neutral-800' />
        <span className='absolute -right-[3px] top-36 h-16 w-[3px] rounded-r bg-neutral-800' />

        <div className='relative h-[36rem] overflow-hidden rounded-[2.35rem] bg-background sm:h-[38rem]'>
          <div className='absolute left-1/2 top-2.5 z-30 h-7 w-24 -translate-x-1/2 rounded-full bg-neutral-950' />

          <div className='flex items-center justify-between px-7 pt-3.5 text-[11px] font-semibold'>
            <span>9:41</span>
            <span className='flex items-center gap-1'>
              <SignalIcon className='size-3.5' />
              <WifiIcon className='size-3.5' />
              <BatteryFullIcon className='size-4' />
            </span>
          </div>

          <AnimatePresence>
            {banner && (
              <m.div
                key={banner.id}
                initial={{ y: -96, opacity: 0, scale: 0.96 }}
                animate={{ y: 0, opacity: 1, scale: 1 }}
                exit={{ y: -96, opacity: 0 }}
                transition={{ type: 'spring', stiffness: 380, damping: 30 }}
                className='absolute inset-x-2.5 top-11 z-20 flex items-start gap-2.5 rounded-2xl bg-neutral-900/90 p-3 text-white shadow-xl backdrop-blur-md'
              >
                <Image
                  src='/web-app-manifest-192x192.png'
                  alt=''
                  width={36}
                  height={36}
                  className='size-9 rounded-xl'
                />
                <div className='min-w-0 flex-1'>
                  <div className='flex items-center justify-between gap-2 text-[10px] text-white/60'>
                    <span className='font-semibold uppercase tracking-wide'>
                      {APP_NAME}
                    </span>
                    <span>сейчас</span>
                  </div>
                  <p className='truncate text-[13px] font-semibold'>
                    {banner.title}
                  </p>
                  <p className='truncate text-xs text-white/75'>
                    {banner.body}
                  </p>
                </div>
              </m.div>
            )}
          </AnimatePresence>

          <div className='mt-5 flex items-center justify-between px-5'>
            <Image
              src='/logo/Logo_Normal.svg'
              alt=''
              width={90}
              height={28}
              unoptimized
              className='h-7 w-auto dark:hidden'
            />
            <Image
              src='/logo/Logo_Black.svg'
              alt=''
              width={90}
              height={28}
              unoptimized
              className='hidden h-7 w-auto dark:block'
            />
            <span className='rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground'>
              Все сайты
            </span>
          </div>

          <div className='mt-4 flex items-center justify-between px-5'>
            <p className='font-display text-xl font-semibold'>Уведомления</p>
            <span className='rounded-full bg-primary px-2 py-0.5 text-[11px] font-semibold text-primary-foreground'>
              {unreadLabel} новых
            </span>
          </div>

          <ul className='mt-3 px-3'>
            <AnimatePresence initial={false}>
              {items.map((item, index) => {
                const Icon = KIND_ICON[item.kind]
                return (
                  <m.li
                    key={item.id}
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    transition={{ duration: 0.45, ease: [0.21, 0.47, 0.32, 0.98] }}
                    className='overflow-hidden'
                  >
                    <div
                      className={cn(
                        'mb-2 flex items-start gap-3 rounded-2xl border bg-card p-3 transition-colors duration-700',
                        index === 0 && 'border-primary/40 bg-primary/5'
                      )}
                    >
                      <span className='flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary'>
                        <Icon className='size-4' />
                      </span>
                      <div className='min-w-0 flex-1'>
                        <p className='truncate text-[13px] font-semibold'>
                          {item.title}
                        </p>
                        <p className='truncate text-xs text-muted-foreground'>
                          {item.body}
                        </p>
                        <p className='mt-1 text-[11px] text-muted-foreground/80'>
                          {TIME_LABELS[index]}
                        </p>
                      </div>
                      {index === 0 && (
                        <span className='mt-1.5 size-2 shrink-0 rounded-full bg-primary' />
                      )}
                    </div>
                  </m.li>
                )
              })}
            </AnimatePresence>
          </ul>

          <div className='absolute inset-x-3 bottom-3 flex justify-around rounded-2xl border bg-muted/80 py-2 text-[10px] font-medium backdrop-blur'>
            <span className='flex flex-col items-center gap-0.5 text-muted-foreground'>
              <HouseIcon className='size-4' />
              Главная
            </span>
            <span className='relative flex flex-col items-center gap-0.5 text-primary'>
              <BellIcon className='size-4' />
              Уведомления
              <span className='absolute -top-1.5 left-1/2 ml-1.5 rounded-full bg-primary px-1.5 text-[9px] font-semibold leading-4 text-primary-foreground'>
                {unreadLabel}
              </span>
            </span>
            <span className='flex flex-col items-center gap-0.5 text-muted-foreground'>
              <MenuIcon className='size-4' />
              Меню
            </span>
          </div>
        </div>
      </div>
    </div>
  )
}
