import { motion, AnimatePresence } from 'framer-motion'
import { useNavigate } from 'react-router-dom'
import { Play, Heart, Share2 } from '../../lib/icons'
import { buildShareUrl, copyToClipboard } from '../../lib/share'
import { toast } from '../../stores/toast-store'
import DetailSectionTabs, { type SectionTab } from './DetailSectionTabs'

interface Props {
  /** Controlled visibility - parent decides whether the chrome is shown.
   *  Pass `usePastSentinel(sentinelRef)` for the standard behaviour. */
  visible: boolean
  title: string
  posterUrl?: string | null
  logoUrl?: string | null
  progress?: number | null
  isFavorite?: boolean | null
  playUrl: string
  resumeUrl: string
  tmdbId?: string | number | null
  imdbId?: string | null
  itemType?: string
  onFavoriteToggle?: () => void
  /** Section tabs to render below the action row. Pass an empty array
   *  to hide the tab strip; pass a list to enable section nav. */
  tabs?: SectionTab[]
}

/**
 * Sticky top chrome for the detail page. Owns the slim action row
 * (logo / title + Share / Favorite / Play) AND the section tabs
 * underneath. Both appear together once the user has scrolled past
 * the hero, animated in as a unit so the chrome doesn't look like two
 * separate things flickering on screen.
 *
 * Visibility is fully controlled - the parent owns the sentinel + the
 * `usePastSentinel` hook. This component just renders.
 */
export default function DetailStickyBar({
  visible,
  title,
  posterUrl,
  logoUrl,
  progress,
  isFavorite,
  playUrl,
  resumeUrl,
  tmdbId,
  imdbId,
  itemType,
  onFavoriteToggle,
  tabs,
}: Props) {
  const navigate = useNavigate()
  const hasProgress = typeof progress === 'number' && progress > 0
  const hasTabs = !!tabs && tabs.length > 1

  async function onShare() {
    const url = buildShareUrl({
      tmdbId,
      imdbId,
      kind: itemType === 'Series' || itemType === 'Episode' ? 'tv' : 'movie',
    })
    if (!url) {
      toast('No shareable link for this item', 'error')
      return
    }
    const ok = await copyToClipboard(url)
    toast(ok ? 'Link copied to clipboard' : 'Could not copy link', ok ? 'success' : 'error')
  }

  return (
    <div className="sticky top-0 z-30 h-0">
      <AnimatePresence>
        {visible && (
          <motion.div
            key="sticky-chrome"
            initial={{ y: -120, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: -120, opacity: 0 }}
            transition={{ duration: 0.26, ease: [0.16, 1, 0.3, 1] }}
            className="absolute top-0 left-0 right-0 bg-void/92 backdrop-blur-xl border-b border-border/80 shadow-[0_8px_20px_-12px_rgba(0,0,0,0.6)]"
          >
            <div className="h-14 flex items-center gap-3 px-7">
              {logoUrl ? (
                <img
                  src={logoUrl}
                  alt=""
                  className="h-7 max-w-[120px] object-contain"
                  onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
                />
              ) : posterUrl ? (
                <img
                  src={posterUrl}
                  alt=""
                  className="h-8 aspect-[2/3] rounded object-cover ring-1 ring-border"
                />
              ) : null}

              <span className="flex-1 min-w-0 text-[13px] font-semibold text-text-1 tracking-tight truncate">
                {logoUrl ? '' : title}
              </span>

              <div className="shrink-0 flex items-center gap-1.5">
                <button
                  onClick={onShare}
                  aria-label="Copy share link"
                  title="Copy share link"
                  className="w-9 h-9 grid place-items-center rounded-full text-text-2 hover:text-text-1 hover:bg-white/8 transition-colors focus-ring"
                >
                  <Share2 size={15} />
                </button>
                {onFavoriteToggle && (
                  <button
                    onClick={onFavoriteToggle}
                    aria-label={isFavorite ? 'Remove favorite' : 'Add favorite'}
                    className="w-9 h-9 grid place-items-center rounded-full text-text-2 hover:text-text-1 hover:bg-white/8 transition-colors focus-ring"
                  >
                    <Heart
                      size={15}
                      className={isFavorite ? 'text-accent fill-accent' : ''}
                      fill={isFavorite ? 'currentColor' : 'none'}
                    />
                  </button>
                )}
                {playUrl && (
                  <button
                    onClick={() => navigate(hasProgress ? resumeUrl : playUrl)}
                    className="inline-flex items-center gap-1.5 h-9 px-3.5 rounded-full bg-accent hover:bg-accent-hover text-void text-[12.5px] font-semibold tracking-tight transition-all duration-150 hover:scale-[1.03] active:scale-[0.97] focus-ring"
                  >
                    <Play size={12} fill="currentColor" stroke={0} />
                    {hasProgress ? 'Resume' : 'Play'}
                  </button>
                )}
              </div>
            </div>

            {hasTabs && (
              <div className="px-7">
                <DetailSectionTabs tabs={tabs!} />
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}
