import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { GiftIcon } from '@phosphor-icons/react'
import {
  useChangelog,
  readLastSeenVersion,
  isVersionNewer,
} from './useChangelog'
import { WhatsNewModal } from './WhatsNewModal'
import { cn } from '@/lib/utils'

/**
 * «Что нового» button в TopBar.
 *
 * <p>🎁 GiftIcon с red unread badge counter (entries newer than
 * {@code localStorage.ord-whatsnew-last-seen}). Click → {@link WhatsNewModal}.
 *
 * <p>Modal extracted в own component — также используется в
 * {@link UpdateBanner} «Что нового» button (когда новая версия detected).
 */
export function WhatsNewButton() {
  const { t } = useTranslation()
  const [open, setOpen] = useState(false)
  const entries = useChangelog()

  // useState lastSeen — re-compute unread после modal close. localStorage
  // write (внутри WhatsNewModal на open) не trigger'ит React re-render
  // отдельно, поэтому tracking через useEffect on open close в modal.
  // В button мы читаем initially — на close button перестроится через
  // обычный rerender chain.
  const lastSeen = useMemo(() => readLastSeenVersion(), [open])
  const unreadCount = useMemo(
    () => entries.filter((e) => isVersionNewer(e.version, lastSeen)).length,
    [entries, lastSeen],
  )

  const label = t('whatsnew.button', { defaultValue: 'Что нового' })

  return (
    <>
      <button
        type="button"
        title={label}
        aria-label={label}
        onClick={() => setOpen(true)}
        className={cn(
          'relative size-7 rounded-md text-ink-2 hover:text-ink hover:bg-surface-2',
          'inline-flex items-center justify-center transition-colors',
          'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
        )}
      >
        <GiftIcon size={14} weight={unreadCount > 0 ? 'fill' : 'regular'} />
        {unreadCount > 0 && (
          <span
            aria-label={t('whatsnew.unread', {
              count: unreadCount,
              defaultValue: `${unreadCount} новых`,
            })}
            className="absolute -top-0.5 -right-0.5 inline-flex items-center justify-center min-w-[14px] h-3.5 px-1 rounded-full bg-mars text-on-mars text-[9px] font-semibold leading-none"
          >
            {unreadCount > 9 ? '9+' : unreadCount}
          </span>
        )}
      </button>

      <WhatsNewModal open={open} onClose={() => setOpen(false)} />
    </>
  )
}
