import { motion, AnimatePresence } from 'framer-motion'
import { ChevronRight, X } from '../../lib/icons'
import {
  genreVisual,
  languageVisual,
  studioVisual,
  networkVisual,
  tileBackground,
} from '../../lib/discover-icons'
import {
  GenreRow,
  LanguageRow,
  StudioRow,
  NetworkRow,
} from '../../pages/discover/rows'
import { GENRE_ROWS, LANGUAGE_ROWS } from '../../pages/discover/helpers'
import { STUDIOS, NETWORKS } from '../../lib/studios-and-networks'

export type BrowseKey =
  | { kind: 'genre'; label: string; subtitle: string }
  | { kind: 'language'; code: string; label: string; subtitle: string }
  | { kind: 'studio'; id: number; label: string; subtitle: string }
  | { kind: 'network'; id: number; label: string; subtitle: string }

function isSameSelection(a: BrowseKey | null, b: BrowseKey | null): boolean {
  if (!a || !b) return a === b
  if (a.kind !== b.kind) return false
  if (a.kind === 'genre' && b.kind === 'genre') return a.label === b.label
  if (a.kind === 'language' && b.kind === 'language') return a.code === b.code
  if (a.kind === 'studio' && b.kind === 'studio') return a.id === b.id
  if (a.kind === 'network' && b.kind === 'network') return a.id === b.id
  return false
}

/**
 * "Browse by X" section. Renders a compact grid of tiles for genres /
 * languages / studios / networks. Picking a tile expands its full row
 * underneath the grid in place - one expansion at a time across the
 * three sections, since the parent owns the state.
 */
export function BrowseSection({
  eyebrow,
  title,
  subtitle,
  tiles,
  expanded,
  onSelect,
}: {
  eyebrow: string
  title: string
  subtitle: string
  tiles: BrowseKey[]
  expanded: BrowseKey | null
  onSelect: (key: BrowseKey | null) => void
}) {
  const hasMine = tiles.some(t => isSameSelection(t, expanded))
  return (
    <section className="px-7 pt-6 mb-8">
      <header className="mb-4">
        <div className="flex items-center gap-2 mb-1">
          <span className="w-1 h-3.5 rounded-full bg-accent" />
          <span className="text-[10.5px] font-semibold text-text-3 uppercase tracking-[0.18em]">
            {eyebrow}
          </span>
        </div>
        <h2 className="font-display text-[20px] font-bold tracking-tight text-text-1 leading-tight">
          {title}
        </h2>
        <p className="text-[12px] text-text-3 mt-0.5">{subtitle}</p>
      </header>

      <ul className="grid gap-2.5 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
        {tiles.map(t => {
          const active = isSameSelection(t, expanded)
          return (
            <li key={tileKey(t)}>
              <Tile tile={t} active={active} onClick={() => onSelect(active ? null : t)} />
            </li>
          )
        })}
      </ul>

      <AnimatePresence initial={false}>
        {hasMine && expanded && (
          <motion.div
            key={tileKey(expanded)}
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            className="-mx-7 mt-6 overflow-hidden"
          >
            <div className="px-7 pt-4 pb-2 flex items-center justify-between">
              <p className="text-[10.5px] uppercase tracking-[0.18em] font-semibold text-accent">
                Now showing - {labelOf(expanded)}
              </p>
              <button
                onClick={() => onSelect(null)}
                className="inline-flex items-center gap-1.5 h-8 px-3 rounded-full text-[11.5px] font-medium bg-elevated/50 text-text-2 border border-border hover:text-text-1 hover:border-border-strong transition-colors focus-ring"
              >
                <X size={11} stroke={2.25} />
                Collapse
              </button>
            </div>
            <ExpansionContent tile={expanded} />
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  )
}

function tileKey(t: BrowseKey): string {
  switch (t.kind) {
    case 'genre': return `g:${t.label}`
    case 'language': return `l:${t.code}`
    case 'studio': return `s:${t.id}`
    case 'network': return `n:${t.id}`
  }
}

function labelOf(t: BrowseKey): string {
  return t.label
}

function Tile({
  tile,
  active,
  onClick,
}: {
  tile: BrowseKey
  active: boolean
  onClick: () => void
}) {
  const v =
    tile.kind === 'genre' ? genreVisual(tile.label)
    : tile.kind === 'language' ? languageVisual(tile.code)
    : tile.kind === 'studio' ? studioVisual()
    : networkVisual()
  const Icon = v.icon
  return (
    <motion.button
      onClick={onClick}
      whileHover={{ y: -2 }}
      whileTap={{ scale: 0.98 }}
      transition={{ duration: 0.18, ease: [0.16, 1, 0.3, 1] }}
      aria-pressed={active}
      className={`group relative w-full min-h-[136px] rounded-xl border text-left focus-ring transition-colors ${
        active ? 'border-accent/55' : 'border-border hover:border-border-strong'
      }`}
      style={{ background: tileBackground(v.hue) }}
    >
      <div className="absolute inset-0 bg-gradient-to-tr from-black/35 via-transparent to-transparent" />
      <Icon
        size={28}
        stroke={1.5}
        className={`absolute right-3 bottom-3 transition-all duration-200 ${
          active ? 'text-accent opacity-100 scale-105' : 'text-text-1/70 opacity-65 group-hover:opacity-90'
        }`}
      />
      <div className="absolute inset-0 p-3.5 flex flex-col">
        <p className="text-[10.5px] uppercase tracking-[0.16em] font-semibold text-white/55 mb-auto">
          {kindLabel(tile.kind)}
        </p>
        <p className="font-display text-[15px] font-bold tracking-tight text-text-1 leading-tight pr-8">
          {tile.label}
        </p>
        <p className="text-[10.5px] text-text-3 mt-1 pr-8 leading-snug">
          {tile.subtitle}
        </p>
      </div>
      {active && (
        <span
          className="absolute top-2 left-2 w-1.5 h-1.5 rounded-full bg-accent shadow-[0_0_6px_rgba(245,182,66,0.7)]"
          aria-hidden
        />
      )}
      <ChevronRight
        size={12}
        className={`absolute top-2 right-2 text-text-3 transition-opacity ${
          active ? 'opacity-0' : 'opacity-0 group-hover:opacity-100'
        }`}
      />
    </motion.button>
  )
}

function kindLabel(k: BrowseKey['kind']): string {
  switch (k) {
    case 'genre': return 'Genre'
    case 'language': return 'Language'
    case 'studio': return 'Studio'
    case 'network': return 'Network'
  }
}

function ExpansionContent({ tile }: { tile: BrowseKey }) {
  switch (tile.kind) {
    case 'genre':
      return <GenreRow genre={{ label: tile.label, subtitle: tile.subtitle }} />
    case 'language':
      return <LanguageRow lang={{ code: tile.code, label: tile.label, subtitle: tile.subtitle }} />
    case 'studio':
      return <StudioRow brandId={tile.id} label={tile.label} subtitle={tile.subtitle} />
    case 'network':
      return <NetworkRow brandId={tile.id} label={tile.label} subtitle={tile.subtitle} />
  }
}

/**
 * Helpers that produce the tile lists for each browse section.
 */

export function genreTiles(): BrowseKey[] {
  return GENRE_ROWS.map(g => ({ kind: 'genre', label: g.label, subtitle: g.subtitle }))
}

export function languageTiles(): BrowseKey[] {
  return LANGUAGE_ROWS.map(l => ({ kind: 'language', code: l.code, label: l.label, subtitle: l.subtitle }))
}

export function studioTiles(): BrowseKey[] {
  return STUDIOS.map(s => ({ kind: 'studio', id: s.id, label: s.label, subtitle: s.blurb || '' }))
}

export function networkTiles(): BrowseKey[] {
  return NETWORKS.map(n => ({ kind: 'network', id: n.id, label: n.label, subtitle: n.blurb || '' }))
}
