import {
  BellRingIcon,
  CrownIcon,
  FileTextIcon,
  GlobeIcon,
  LaptopIcon,
  LogOutIcon,
  MessagesSquareIcon,
  PlusIcon,
  SearchIcon,
  ShieldCheckIcon,
  ShoppingCartIcon,
  SlidersHorizontalIcon,
  SmartphoneIcon,
  UserCogIcon,
  UserIcon,
  UsersIcon,
  type LucideIcon
} from 'lucide-react'
import type { ReactNode } from 'react'
import { nbspDash } from '@/shared/lib/typography'
import { cn } from '@/shared/lib/utils'
import { SectionHeading } from './section-heading'
import { Stagger, StaggerItem } from './motion'

const BentoCard = ({
  icon: Icon,
  title,
  description,
  className,
  children
}: {
  icon: LucideIcon
  title: string
  description: string
  className?: string
  children?: ReactNode
}) => (
  <StaggerItem
    className={cn(
      'group relative flex flex-col overflow-hidden rounded-3xl border bg-card p-6 shadow-xs transition-[translate,box-shadow] duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-primary/5 sm:p-8',
      className
    )}
  >
    <span className='flex size-11 items-center justify-center rounded-2xl bg-primary/10 text-primary ring-1 ring-primary/20'>
      <Icon className='size-5' />
    </span>
    <h3 className='mt-5 font-display text-xl font-semibold tracking-tight'>
      {nbspDash(title)}
    </h3>
    <p className='mt-2 text-muted-foreground text-pretty'>
      {nbspDash(description)}
    </p>
    {children && (
      <div aria-hidden className='mt-8 flex flex-1 flex-col justify-end'>
        {children}
      </div>
    )}
  </StaggerItem>
)

const FEED = [
  { Icon: ShoppingCartIcon, title: 'Новый заказ №46871', site: 'kzla.ru', time: 'только что' },
  { Icon: FileTextIcon, title: 'Заявка «Обратный звонок»', site: 'korzilla.ru', time: '1 мин' },
  { Icon: ShoppingCartIcon, title: 'Новый заказ №46870', site: 'kzla.ru', time: '4 мин' },
  { Icon: FileTextIcon, title: 'Заявка «Задать вопрос»', site: 'kzla.ru', time: '12 мин' },
  { Icon: ShoppingCartIcon, title: 'Новый заказ №46869', site: 'korzilla.ru', time: '20 мин' },
  { Icon: BellRingIcon, title: 'Добавлена синхронизация', site: 'korzilla.ru', time: '1 ч' }
]

// Endless vertical ticker of notifications (the list is doubled for a seamless loop)
const FeedTicker = () => (
  <div className='relative h-64 overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,black_18%,black_82%,transparent)]'>
    <ul className='space-y-2.5 motion-safe:animate-marquee-y group-hover:[animation-play-state:paused]'>
      {[...FEED, ...FEED].map(({ Icon, title, site, time }, index) => (
        <li
          key={index}
          className='flex items-center gap-3 rounded-2xl border bg-background p-3'
        >
          <span className='flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary'>
            <Icon className='size-4' />
          </span>
          <span className='min-w-0 flex-1'>
            <span className='block truncate text-sm font-medium'>{title}</span>
            <span className='block text-xs text-muted-foreground'>{site}</span>
          </span>
          <span className='shrink-0 text-xs text-muted-foreground'>{time}</span>
        </li>
      ))}
    </ul>
  </div>
)

const PushVisual = () => (
  <div className='relative flex min-h-40 flex-1 items-center justify-center'>
    {[0, 1.2, 2.4].map((delay) => (
      <span
        key={delay}
        className='absolute size-36 rounded-full border border-primary/30 opacity-0 motion-safe:animate-pulse-ring motion-reduce:opacity-40'
        style={{ animationDelay: `${delay}s` }}
      />
    ))}
    <span className='relative flex size-20 items-center justify-center rounded-3xl bg-primary text-primary-foreground shadow-lg shadow-primary/30'>
      <BellRingIcon className='size-9 origin-top motion-safe:animate-bell' />
      <span className='absolute -right-2 -top-2 flex size-7 items-center justify-center rounded-full border-2 border-card bg-destructive text-xs font-bold text-white'>
        1
      </span>
    </span>
  </div>
)

const FILTER_CHIPS = [
  { label: 'Новые заказы', active: true },
  { label: 'Заявки', active: false },
  { label: 'kzla.ru', active: true },
  { label: 'Непрочитанные', active: false },
  { label: 'Сначала новые', active: false }
]

const FiltersVisual = () => (
  <div className='space-y-3'>
    <div className='flex items-center gap-2 rounded-full border bg-background px-4 py-2.5 text-sm text-muted-foreground'>
      <SearchIcon className='size-4' />
      <span className='flex-1'>заказ №468</span>
      <span className='text-xs'>12 найдено</span>
    </div>
    <div className='flex flex-wrap gap-2'>
      {FILTER_CHIPS.map(({ label, active }) => (
        <span
          key={label}
          className={cn(
            'rounded-full border px-3 py-1 text-xs font-medium',
            active
              ? 'border-primary/40 bg-primary/10 text-primary'
              : 'bg-background text-muted-foreground'
          )}
        >
          {label}
        </span>
      ))}
    </div>
  </div>
)

const TEAM = [
  { Icon: CrownIcon, name: 'Вы', role: 'Владелец', accent: true },
  { Icon: UserCogIcon, name: 'Сотрудник', role: 'Администратор', accent: false },
  { Icon: UserIcon, name: 'Сотрудник', role: 'Менеджер', accent: false }
]

const TeamVisual = () => (
  <ul className='space-y-2'>
    {TEAM.map(({ Icon, name, role, accent }) => (
      <li
        key={role}
        className='flex items-center gap-3 rounded-2xl border bg-background p-2.5'
      >
        <span
          className={cn(
            'flex size-8 items-center justify-center rounded-full',
            accent ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'
          )}
        >
          <Icon className='size-4' />
        </span>
        <span className='flex-1 text-sm font-medium'>{name}</span>
        <span
          className={cn(
            'rounded-full px-2.5 py-0.5 text-xs font-medium',
            accent ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'
          )}
        >
          {role}
        </span>
      </li>
    ))}
  </ul>
)

const SessionsVisual = () => (
  <div className='space-y-2'>
    <div className='flex items-center gap-3 rounded-2xl border border-primary/30 bg-primary/5 p-2.5'>
      <SmartphoneIcon className='size-4 text-primary' />
      <span className='flex-1 text-sm font-medium'>iPhone</span>
      <span className='text-xs text-primary'>это устройство</span>
    </div>
    <div className='flex items-center gap-3 rounded-2xl border bg-background p-2.5'>
      <LaptopIcon className='size-4 text-muted-foreground' />
      <span className='flex-1 text-sm font-medium'>Windows</span>
      <span className='inline-flex items-center gap-1 rounded-full bg-destructive/10 px-2 py-0.5 text-xs font-medium text-destructive'>
        Выйти
        <LogOutIcon className='size-3' />
      </span>
    </div>
  </div>
)

const SupportVisual = () => (
  <div className='space-y-2 text-sm'>
    <p className='ml-auto w-fit max-w-[85%] rounded-2xl rounded-br-md bg-primary px-3.5 py-2 text-primary-foreground'>
      Как подключить второй сайт?
    </p>
    <p className='w-fit max-w-[85%] rounded-2xl rounded-bl-md border bg-background px-3.5 py-2'>
      Добавьте его в разделе «Сайты» и введите код синхронизации в
      админ-панели сайта — это займёт минуту.
    </p>
  </div>
)

const SITES = ['kzla.ru', 'korzilla.ru']

const SitesVisual = () => (
  <div className='flex flex-wrap gap-2'>
    {SITES.map((site) => (
      <span
        key={site}
        className='inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1.5 text-sm font-medium'
      >
        <GlobeIcon className='size-4 text-primary' />
        {site}
      </span>
    ))}
    <span className='inline-flex items-center gap-1.5 rounded-full border border-dashed border-primary/50 px-3 py-1.5 text-sm font-medium text-primary'>
      <PlusIcon className='size-4' />
      Добавить сайт
    </span>
  </div>
)

export const Features = () => (
  <section id='features' className='scroll-mt-20 py-20 sm:py-28'>
    <div className='mx-auto max-w-7xl px-4 lg:px-6'>
      <SectionHeading
        eyebrow='Возможности'
        title='Всё, чтобы не пропустить ни одного заказа'
        description='Корзилла.Админ превращает смартфон в центр управления вашими сайтами — без привязки к офису и рабочему столу.'
      />

      <Stagger className='mt-14 grid gap-4 md:grid-cols-2 lg:mt-20 lg:grid-cols-6 lg:gap-5'>
        <BentoCard
          icon={GlobeIcon}
          title='Уведомления со всех сайтов'
          description='Новые заказы, заявки с форм и другие события ваших сайтов собираются в одной ленте. Не нужно заходить в админку каждого сайта.'
          className='md:col-span-2 lg:col-span-4'
        >
          <FeedTicker />
        </BentoCard>
        <BentoCard
          icon={BellRingIcon}
          title='Мгновенные push'
          description='Узнавайте о заказе в момент оформления — даже когда приложение закрыто.'
          className='lg:col-span-2'
        >
          <PushVisual />
        </BentoCard>
        <BentoCard
          icon={SlidersHorizontalIcon}
          title='Поиск и фильтры'
          description='Найдите нужное событие по тексту, типу, сайту, дате или статусу прочтения.'
          className='lg:col-span-2'
        >
          <FiltersVisual />
        </BentoCard>
        <BentoCard
          icon={UsersIcon}
          title='Доступы для команды'
          description='Пригласите сотрудников и выберите роль для каждого сайта: администратор или менеджер.'
          className='lg:col-span-2'
        >
          <TeamVisual />
        </BentoCard>
        <BentoCard
          icon={ShieldCheckIcon}
          title='Безопасность аккаунта'
          description='Список активных сессий и выход со всех чужих устройств в одно касание.'
          className='lg:col-span-2'
        >
          <SessionsVisual />
        </BentoCard>
        <BentoCard
          icon={MessagesSquareIcon}
          title='Поддержка в чате'
          description='Задайте вопрос прямо из приложения — специалисты Корзиллы помогут с подключением и настройкой.'
          className='lg:col-span-3'
        >
          <SupportVisual />
        </BentoCard>
        <BentoCard
          icon={PlusIcon}
          title='Сайтов — сколько угодно'
          description='Подключайте все свои сайты на CMS Korzilla без ограничений и без доплат.'
          className='lg:col-span-3'
        >
          <SitesVisual />
        </BentoCard>
      </Stagger>
    </div>
  </section>
)
