import { useState, useRef, useEffect, useCallback } from 'react'
import { useLang } from '@/context/LangContext'
import { Headphones, ChevronLeft, ChevronRight, PlayCircle, Play, Pause, Volume2, VolumeX } from 'lucide-react'
import { podcasts as PODCASTS, videos as VIDEOS } from '@/data/media'
import FeaturedReportBanner from '../Home/sections/FeaturedReportBanner'

const NAVY = '#032340'
const GOLD = '#CD9E53'
const CARD = '#0d2137'

const T = {
  fa: { listen: 'پخش', watch: 'تماشا', allVids: 'همه ویدیوها', videocast: 'ویدیوکست', podcast: 'پادکست اندیشکده', episodes: 'اپیزودها' },
  en: { listen: 'Play', watch: 'Watch', allVids: 'All Videos', videocast: 'Videocast', podcast: 'Institute Podcast', episodes: 'Episodes' },
}

/* ══ CSS keyframes injected once ══ */
const STYLE = `
@keyframes gradSpin {
  0%   { background-position: 0% 50% }
  50%  { background-position: 100% 50% }
  100% { background-position: 0% 50% }
}
@keyframes borderRotate {
  0%   { --angle: 0deg }
  100% { --angle: 360deg }
}
@property --angle {
  syntax: '<angle>';
  initial-value: 0deg;
  inherits: false;
}
@keyframes pulse-bar {
  0%, 100% { transform: scaleY(0.3) }
  50%       { transform: scaleY(1) }
}
.cover-border-wrap {
  --angle: 0deg;
  animation: borderRotate 3s linear infinite;
  padding: 3px;
  border-radius: 4px;
  background: conic-gradient(from var(--angle), #7a4f00, #CD9E53, #f0d080, #fff8e1, #CD9E53, #7a4f00);
  box-shadow: 0 0 24px #CD9E5366, 0 0 48px #CD9E5322;
}
`

/* ══ Real waveform audio player ══ */
function WavePlayer({ episodeKey }: { episodeKey: string | number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const animRef   = useRef<number>(0)
  const audioCtxRef = useRef<AudioContext | null>(null)
  const analyserRef = useRef<AnalyserNode | null>(null)
  const sourcesRef  = useRef<OscillatorNode[]>([])
  const gainRef     = useRef<GainNode | null>(null)

  const [playing, setPlaying]   = useState(false)
  const [muted, setMuted]       = useState(false)
  const [progress, setProgress] = useState(0)   // 0-1
  const [elapsed, setElapsed]   = useState(0)   // seconds
  const startTimeRef = useRef(0)
  const pausedAtRef  = useRef(0)
  const TOTAL = 180 // demo: 3 min

  /* draw waveform from analyser */
  const draw = useCallback(() => {
    const canvas  = canvasRef.current
    const analyser = analyserRef.current
    if (!canvas || !analyser) return
    const ctx  = canvas.getContext('2d')!
    const data = new Uint8Array(analyser.frequencyBinCount)
    analyser.getByteFrequencyData(data)

    const W = canvas.width, H = canvas.height
    ctx.clearRect(0, 0, W, H)

    const bars = 80
    const step = Math.floor(data.length / bars)
    const bw   = W / bars

    for (let i = 0; i < bars; i++) {
      const val  = data[i * step] / 255
      const bh   = Math.max(3, val * H * 0.9)
      const x    = i * bw
      const y    = (H - bh) / 2

      // gradient per bar
      const g = ctx.createLinearGradient(0, y, 0, y + bh)
      g.addColorStop(0,   `${GOLD}cc`)
      g.addColorStop(0.5, GOLD)
      g.addColorStop(1,   `${GOLD}44`)
      ctx.fillStyle = g
      ctx.beginPath()
      ctx.roundRect(x + 1, y, bw - 2, bh, 2)
      ctx.fill()
    }

    animRef.current = requestAnimationFrame(draw)
  }, [])

  /* idle waveform (decorative) when paused */
  const drawIdle = useCallback(() => {
    const canvas = canvasRef.current
    if (!canvas) return
    const ctx = canvas.getContext('2d')!
    const W = canvas.width, H = canvas.height
    ctx.clearRect(0, 0, W, H)
    const bars = 80
    const bw   = W / bars
    for (let i = 0; i < bars; i++) {
      const val = 0.08 + 0.12 * Math.sin(i * 0.4)
      const bh  = Math.max(3, val * H)
      const x   = i * bw
      const y   = (H - bh) / 2
      ctx.fillStyle = 'rgba(205,158,83,0.25)'
      ctx.beginPath()
      ctx.roundRect(x + 1, y, bw - 2, bh, 2)
      ctx.fill()
    }
  }, [])

  /* stop engine */
  const stop = useCallback(() => {
    cancelAnimationFrame(animRef.current)
    sourcesRef.current.forEach(o => { try { o.stop(); o.disconnect() } catch { /* already stopped */ } })
    sourcesRef.current = []
    gainRef.current?.disconnect()
    gainRef.current = null
    analyserRef.current?.disconnect()
    analyserRef.current = null
    drawIdle()
  }, [drawIdle])

  /* start engine — synthesised audio (no file needed) */
  const start = useCallback(() => {
    if (!audioCtxRef.current) audioCtxRef.current = new AudioContext()
    const actx = audioCtxRef.current
    if (actx.state === 'suspended') actx.resume()

    const analyser = actx.createAnalyser()
    analyser.fftSize = 256
    analyserRef.current = analyser

    const gain = actx.createGain()
    gain.gain.value = muted ? 0 : 0.04
    gainRef.current = gain

    /* layered oscillators for a richer "voice" look */
    const freqs = [120, 240, 480, 960]
    const oscs: OscillatorNode[] = freqs.map(f => {
      const osc = actx.createOscillator()
      osc.type = 'sine'
      osc.frequency.value = f + Math.random() * 40
      osc.connect(gain)
      osc.start()
      return osc
    })
    sourcesRef.current = oscs

    gain.connect(analyser)
    analyser.connect(actx.destination)

    startTimeRef.current = actx.currentTime - pausedAtRef.current
    draw()
  }, [draw, muted])

  /* toggle play */
  const toggle = () => {
    if (playing) {
      pausedAtRef.current = (audioCtxRef.current?.currentTime ?? 0) - startTimeRef.current
      stop()
      setPlaying(false)
    } else {
      start()
      setPlaying(true)
    }
  }

  /* progress ticker */
  useEffect(() => {
    if (!playing) return
    const id = setInterval(() => {
      const t = (audioCtxRef.current?.currentTime ?? 0) - startTimeRef.current
      setElapsed(t)
      setProgress(Math.min(t / TOTAL, 1))
      if (t >= TOTAL) { stop(); setPlaying(false); setProgress(1) }
    }, 200)
    return () => clearInterval(id)
  }, [playing, stop])

  /* reset when episode changes */
  useEffect(() => {
    stop()
    setPlaying(false)
    setProgress(0)
    setElapsed(0)
    pausedAtRef.current = 0
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [episodeKey])

  /* mute toggle */
  useEffect(() => {
    if (gainRef.current) gainRef.current.gain.value = muted ? 0 : 0.04
  }, [muted])

  /* initial idle draw */
  useEffect(() => { drawIdle() }, [drawIdle, episodeKey])

  /* canvas resize */
  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return
    const ro = new ResizeObserver(() => {
      canvas.width  = canvas.offsetWidth  * devicePixelRatio
      canvas.height = canvas.offsetHeight * devicePixelRatio
      const ctx = canvas.getContext('2d')!
      ctx.scale(devicePixelRatio, devicePixelRatio)
      drawIdle()
    })
    ro.observe(canvas)
    return () => ro.disconnect()
  }, [drawIdle])

  const fmt = (s: number) => {
    const m = Math.floor(s / 60), sec = Math.floor(s % 60)
    return `${m}:${String(sec).padStart(2, '0')}`
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {/* waveform canvas */}
      <div
        style={{ position: 'relative', height: 56, cursor: 'pointer', borderRadius: 10, overflow: 'hidden' }}
        onClick={(e) => {
          const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect()
          const ratio = (e.clientX - rect.left) / rect.width
          pausedAtRef.current = ratio * TOTAL
          setProgress(ratio)
          setElapsed(ratio * TOTAL)
          if (playing) { stop(); start() }
        }}
      >
        <canvas
          ref={canvasRef}
          style={{ width: '100%', height: '100%', display: 'block' }}
        />
        {/* progress overlay */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: `linear-gradient(to right, rgba(13,33,55,0) ${progress * 100}%, rgba(13,33,55,0.55) ${progress * 100}%)`,
        }} />
        {/* playhead */}
        <div style={{
          position: 'absolute', top: 0, bottom: 0,
          left: `${progress * 100}%`, width: 2,
          background: '#fff', opacity: 0.7,
          transform: 'translateX(-1px)',
          transition: 'left .2s linear',
        }} />
      </div>

      {/* controls */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, direction: 'ltr' }}>
        <button onClick={toggle} style={{
          width: 40, height: 40, borderRadius: '50%', border: 'none', cursor: 'pointer',
          background: GOLD, display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: playing ? `0 0 18px ${GOLD}88` : 'none',
          transition: 'box-shadow .3s', flexShrink: 0,
        }}>
          {playing
            ? <Pause size={16} color={NAVY} fill={NAVY} />
            : <Play  size={16} color={NAVY} fill={NAVY} style={{ marginLeft: 2 }} />
          }
        </button>

        <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', fontWeight: 700, minWidth: 34 }}>{fmt(elapsed)}</span>

        {/* track bar */}
        <div style={{ flex: 1, position: 'relative', height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.1)', cursor: 'pointer' }}
          onClick={(e) => {
            const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect()
            const ratio = (e.clientX - rect.left) / rect.width
            pausedAtRef.current = ratio * TOTAL
            setProgress(ratio)
            setElapsed(ratio * TOTAL)
            if (playing) { stop(); start() }
          }}>
          <div style={{ width: `${progress * 100}%`, height: '100%', borderRadius: 2, background: GOLD, transition: 'width .2s linear' }} />
          <div style={{
            position: 'absolute', top: '50%', left: `${progress * 100}%`,
            transform: 'translate(-50%,-50%)',
            width: 12, height: 12, borderRadius: '50%', background: '#fff',
            boxShadow: `0 0 6px ${GOLD}`,
          }} />
        </div>

        <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.25)', fontWeight: 700, minWidth: 34 }}>{fmt(TOTAL)}</span>

        <button onClick={() => setMuted(m => !m)} style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: 4,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {muted
            ? <VolumeX size={15} color="rgba(255,255,255,0.35)" />
            : <Volume2 size={15} color="rgba(255,255,255,0.35)" />
          }
        </button>
      </div>
    </div>
  )
}

/* ─── active glow pill ─── */
function ActivePill({ active }: { active: boolean }) {
  return active ? (
    <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: GOLD, boxShadow: `0 0 8px ${GOLD}`, flexShrink: 0 }} />
  ) : null
}

/* ─── episode sidebar item ─── */
function EpItem({ pod, active, onClick, lang }: {
  pod: typeof PODCASTS[0]; active: boolean; onClick: () => void; lang: 'fa' | 'en'
}) {
  const isFa = lang === 'fa'
  return (
    <button onClick={onClick} style={{
      all: 'unset', display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 12px', borderRadius: 12, cursor: 'pointer',
      background: active ? 'rgba(205,158,83,0.10)' : 'transparent',
      border: active ? `1px solid rgba(205,158,83,0.25)` : '1px solid transparent',
      transition: 'all .2s', width: '100%', boxSizing: 'border-box',
      flexDirection: isFa ? 'row-reverse' : 'row',
    }}>
      <div style={{ position: 'relative', flexShrink: 0 }}>
        <img src={pod.cover} alt="" style={{
          width: 48, height: 48, borderRadius: 10, objectFit: 'cover', display: 'block',
          border: active ? `2px solid ${GOLD}` : '2px solid rgba(255,255,255,0.08)',
          transition: 'border-color .2s',
        }} />
        {active && (
          <div style={{ position: 'absolute', inset: 0, borderRadius: 10, background: 'rgba(205,158,83,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent', borderLeft: `8px solid ${GOLD}`, marginLeft: 2 }} />
          </div>
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0, textAlign: isFa ? 'right' : 'left' }}>
        <div style={{
          fontSize: 11.5, fontWeight: 800, color: active ? '#fff' : 'rgba(255,255,255,0.65)',
          lineHeight: 1.4, marginBottom: 3,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
          transition: 'color .2s',
        }}>{pod[lang].title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, direction: 'ltr', justifyContent: isFa ? 'flex-end' : 'flex-start' }}>
          <ActivePill active={active} />
          <span style={{ fontSize: 10, color: active ? GOLD : 'rgba(255,255,255,0.25)', fontWeight: 700 }}>{pod.epNum}</span>
          <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.2)' }}>·</span>
          <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.25)' }}>{pod.duration}</span>
        </div>
      </div>
    </button>
  )
}

/* ══ MAIN ══ */
export default function Podcast() {
  const { lang } = useLang()
  const t = T[lang]
  const isFa = lang === 'fa'
  const [active, setActive]     = useState(0)
  const [activeVid, setActiveVid] = useState(0)
  const [vidPlaying, setVidPlaying] = useState(false)
  const pod = PODCASTS[active]
  const vid = VIDEOS[activeVid]

  return (
    <div dir={isFa ? 'rtl' : 'ltr'} style={{ background: '#fff', minHeight: '100vh', color: '#fff', ['--paper' as string]: '#fff', ['--page-bg' as string]: '#fff' }}>
      <style>{STYLE}</style>

      {/* ══ PODCAST SECTION ══ */}
      <div style={{ background: 'transparent' }}>
        <div className="max-w-7xl mx-auto px-8 max-md:px-4" style={{ paddingTop: 56, paddingBottom: 64 }}>

          {/* label */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            background: 'rgba(205,158,83,0.12)', border: '1px solid rgba(205,158,83,0.25)',
            borderRadius: 20, padding: '5px 14px', marginBottom: 32,
          }}>
            <Headphones size={13} color={GOLD} strokeWidth={2} />
            <span style={{ fontSize: 12, fontWeight: 800, color: GOLD, letterSpacing: '0.04em' }}>{t.podcast}</span>
          </div>

          {/* main grid */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: isFa ? '1fr 300px' : '300px 1fr',
            gap: 0,
            background: CARD,
            borderRadius: 28,
            overflow: 'hidden',
            boxShadow: '0 32px 80px -24px rgba(0,0,0,0.7)',
            minHeight: 560,
          }} className="max-lg:!grid-cols-1">

            {/* sidebar */}
            <div style={{
              borderRight: isFa ? 'none' : '1px solid rgba(255,255,255,0.06)',
              borderLeft:  isFa ? '1px solid rgba(255,255,255,0.06)' : 'none',
              display: 'flex', flexDirection: 'column',
              order: isFa ? 2 : 1,
            }}>
              <div style={{ padding: '20px 16px 14px', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
                <div style={{ fontSize: 11, fontWeight: 900, color: 'rgba(255,255,255,0.3)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{t.episodes}</div>
              </div>
              <div style={{ flex: 1, overflowY: 'auto', padding: '10px 8px', display: 'flex', flexDirection: 'column', gap: 2 }}>
                {PODCASTS.map((p, i) => (
                  <EpItem key={p.id} pod={p} active={active === i} onClick={() => setActive(i)} lang={lang} />
                ))}
              </div>
            </div>

            {/* hero */}
            <div style={{ display: 'flex', flexDirection: 'column', order: isFa ? 1 : 2, position: 'relative', overflow: 'hidden' }}>

              {/* blurred bg */}
              <div style={{
                position: 'absolute', inset: 0,
                backgroundImage: `url(${pod.cover})`,
                backgroundSize: 'cover', backgroundPosition: 'center',
                filter: 'blur(48px) saturate(0.3)', opacity: 0.2, transform: 'scale(1.15)',
              }} />
              <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(135deg, ${CARD} 35%, rgba(13,33,55,0.6) 100%)` }} />

              {/* inner grid: text | cover-image */}
              <div style={{
                position: 'relative', zIndex: 1,
                display: 'grid',
                gridTemplateColumns: isFa ? '300px 1fr' : '1fr 300px',
                height: '100%',
              }} className="max-lg:!flex max-lg:!flex-col">

                {/* ── COVER image column ── */}
                {/* outer: spinning gradient border */}
                <div style={{
                  order: isFa ? 1 : 2,
                  margin: 10,
                  borderRadius: 16,
                  padding: 3,
                  background: 'conic-gradient(from var(--angle,0deg), #7a4f00, #CD9E53, #f0d080, #fff8e1, #CD9E53, #7a4f00)',
                  animation: 'borderRotate 3s linear infinite',
                  boxShadow: `0 0 28px ${GOLD}55, 0 0 56px ${GOLD}22`,
                  flexShrink: 0,
                  alignSelf: 'stretch',
                }} className="max-lg:!order-first max-lg:!my-4 max-lg:!h-56 max-lg:!self-auto">

                  {/* inner: clips image to rounded rect */}
                  <div style={{ borderRadius: 13, overflow: 'hidden', height: '100%', position: 'relative' }}>
                    <img
                      src={pod.cover}
                      alt={pod[lang].title}
                      style={{
                        position: 'absolute', inset: 0,
                        width: '100%', height: '100%',
                        objectFit: 'cover',
                        objectPosition: 'center',
                        display: 'block',
                      }}
                    />
                    <div style={{
                      position: 'absolute', inset: 0, pointerEvents: 'none',
                      background: isFa
                        ? 'linear-gradient(to left, rgba(13,33,55,0) 50%, rgba(13,33,55,0.85) 100%)'
                        : 'linear-gradient(to right, rgba(13,33,55,0) 50%, rgba(13,33,55,0.85) 100%)',
                    }} />
                  </div>
                </div>

                {/* ── text column ── */}
                <div style={{
                  order: isFa ? 2 : 1,
                  display: 'flex', flexDirection: 'column',
                  padding: '36px 36px 28px',
                }} className="max-lg:!px-6 max-lg:!py-6">

                  {/* ep badge */}
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.12)',
                    borderRadius: 8, padding: '4px 10px', marginBottom: 20, width: 'fit-content',
                  }}>
                    <span style={{ fontSize: 11, fontWeight: 900, color: GOLD }}>{pod.epNum}</span>
                    <span style={{ width: 1, height: 10, background: 'rgba(255,255,255,0.15)' }} />
                    <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', fontWeight: 600 }}>{pod.date}</span>
                  </div>

                  {/* title */}
                  <h1 style={{
                    fontSize: 'clamp(17px,1.8vw,24px)', fontWeight: 900, color: '#fff',
                    lineHeight: 1.4, margin: '0 0 10px', letterSpacing: '-0.3px',
                    textAlign: isFa ? 'right' : 'left',
                  }}>{pod[lang].title}</h1>

                  {/* guest */}
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    background: 'rgba(205,158,83,0.12)', borderRadius: 6, padding: '4px 10px',
                    marginBottom: 16, width: 'fit-content',
                  }}>
                    <div style={{ width: 5, height: 5, borderRadius: '50%', background: GOLD }} />
                    <span style={{ fontSize: 12, color: GOLD, fontWeight: 700 }}>{pod[lang].guest}</span>
                  </div>

                  {/* body */}
                  <p style={{
                    fontSize: 12.5, lineHeight: 1.9, color: 'rgba(255,255,255,0.45)',
                    margin: '0 0 20px', textAlign: 'justify', flex: 1,
                    display: '-webkit-box', WebkitLineClamp: 4, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                  }}>{pod[lang].body}</p>

                  {/* ── AUDIO PLAYER ── */}
                  <div style={{
                    background: 'rgba(0,0,0,0.25)', borderRadius: 16,
                    padding: '14px 16px', marginBottom: 20,
                    border: '1px solid rgba(255,255,255,0.07)',
                  }}>
                    {pod.mediaUrl
                      ? <audio controls preload="none" src={pod.mediaUrl} style={{ width: '100%', display: 'block' }} />
                      : <WavePlayer episodeKey={pod.id} />}
                  </div>

                  {/* bottom: rating only */}
                  <div style={{ paddingTop: 16, borderTop: '1px solid rgba(255,255,255,0.07)' }}>
                    <span style={{ fontSize: 12, color: GOLD, fontWeight: 800, background: 'rgba(205,158,83,0.1)', padding: '3px 10px', borderRadius: 6 }}>
                      ★ {pod.rating}
                    </span>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ══ VIDEOCAST SECTION ══ */}
      <div style={{ background: 'transparent', paddingTop: 64, paddingBottom: 80 }}>
        <div className="max-w-7xl mx-auto px-8 max-md:px-4">

          {/* header */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 40, flexDirection: isFa ? 'row-reverse' : 'row',
          }}>
            <div style={{ textAlign: isFa ? 'right' : 'left' }}>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 8,
                background: 'rgba(205,158,83,0.12)', border: '1px solid rgba(205,158,83,0.25)',
                borderRadius: 20, padding: '5px 14px',
              }}>
                <PlayCircle size={13} color={GOLD} strokeWidth={2} />
                <span style={{ fontSize: 12, fontWeight: 800, color: GOLD, letterSpacing: '0.06em' }}>{t.videocast}</span>
              </div>
            </div>
            <button style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, direction: 'ltr',
              background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
              borderRadius: 20, padding: '7px 16px', cursor: 'pointer',
              color: 'rgba(255,255,255,0.6)', fontSize: 11.5, fontWeight: 700, fontFamily: 'inherit',
              transition: 'all .2s',
            }}>
              {isFa ? <ChevronRight size={11} /> : <ChevronLeft size={11} />}{t.allVids}
            </button>
          </div>

          {/* featured hero video */}
          <div style={{
            position: 'relative', borderRadius: 24, overflow: 'hidden',
            aspectRatio: '21/9', marginBottom: 32, cursor: vid.mediaUrl ? 'pointer' : 'default',
            boxShadow: '0 40px 80px -20px rgba(0,0,0,0.8)', background: '#000',
          }}
            onClick={() => { if (vid.mediaUrl && !vidPlaying) setVidPlaying(true) }}
            onMouseEnter={e => {
              const el = e.currentTarget as HTMLDivElement
              const img = el.querySelector('img'); if (img) (img as HTMLElement).style.transform = 'scale(1.04)'
              const pb = el.querySelector('.play-btn') as HTMLElement | null; if (pb) pb.style.transform = 'translate(-50%,-50%) scale(1.12)'
            }}
            onMouseLeave={e => {
              const el = e.currentTarget as HTMLDivElement
              const img = el.querySelector('img'); if (img) (img as HTMLElement).style.transform = 'scale(1)'
              const pb = el.querySelector('.play-btn') as HTMLElement | null; if (pb) pb.style.transform = 'translate(-50%,-50%) scale(1)'
            }}
          >
            {vidPlaying && vid.mediaUrl ? (
              <video src={vid.mediaUrl} controls autoPlay
                style={{ width: '100%', height: '100%', objectFit: 'contain', background: '#000', display: 'block' }} />
            ) : (
            <>
            <img src={vid.thumb} alt="" style={{
              width: '100%', height: '100%', objectFit: 'cover', display: 'block',
              transition: 'transform .5s ease',
            }} />
            {/* cinematic gradient */}
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(3,10,25,0.92) 0%, rgba(3,10,25,0.3) 50%, transparent 100%)' }} />
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to right, rgba(3,10,25,0.5) 0%, transparent 60%)' }} />

            {/* play button */}
            <div className="play-btn" style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%,-50%)',
              width: 72, height: 72, borderRadius: '50%',
              background: `${GOLD}ee`,
              border: '3px solid rgba(255,255,255,0.35)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: `0 0 0 12px ${GOLD}22, 0 16px 40px -8px ${GOLD}88`,
              transition: 'transform .3s ease',
            }}>
              <div style={{ width: 0, height: 0, borderTop: '13px solid transparent', borderBottom: '13px solid transparent', borderLeft: `22px solid ${NAVY}`, marginLeft: 4 }} />
            </div>

            {/* bottom info overlay */}
            <div style={{
              position: 'absolute', bottom: 0, left: 0, right: 0,
              padding: '32px 32px 28px',
              display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
              flexDirection: isFa ? 'row-reverse' : 'row',
            }}>
              <div style={{ textAlign: isFa ? 'right' : 'left' }}>
                <div style={{ display: 'flex', gap: 8, marginBottom: 10, flexDirection: isFa ? 'row-reverse' : 'row' }}>
                  <span style={{ fontSize: 11, fontWeight: 800, color: '#fff', background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(8px)', padding: '4px 12px', borderRadius: 8 }}>{vid.ep}</span>
                  <span style={{ fontSize: 11, fontWeight: 700, color: GOLD, background: 'rgba(205,158,83,0.2)', backdropFilter: 'blur(8px)', padding: '4px 12px', borderRadius: 8 }}>{vid.duration}</span>
                </div>
                <h2 style={{ fontSize: 'clamp(16px,2vw,26px)', fontWeight: 900, color: '#fff', lineHeight: 1.3, margin: '0 0 6px', letterSpacing: '-0.3px' }}>{vid[lang].title}</h2>
                <div style={{ fontSize: 13, color: `${GOLD}cc`, fontWeight: 600 }}>{vid[lang].guest}</div>
              </div>
            </div>
            </>
            )}
          </div>

          {/* video grid */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(5, 1fr)',
            gap: 14,
          }} className="max-lg:!grid-cols-3 max-md:!grid-cols-2">
            {VIDEOS.map((v, i) => (
              <button key={v.id} onClick={() => { setActiveVid(i); setVidPlaying(false) }} style={{
                all: 'unset', cursor: 'pointer', display: 'flex', flexDirection: 'column',
                borderRadius: 16, overflow: 'hidden',
                background: activeVid === i ? 'rgba(205,158,83,0.08)' : 'rgba(255,255,255,0.03)',
                border: activeVid === i ? `1px solid ${GOLD}55` : '1px solid rgba(255,255,255,0.07)',
                transition: 'all .25s', boxSizing: 'border-box',
              }}
                onMouseEnter={e => {
                  const el = e.currentTarget as HTMLButtonElement
                  if (activeVid !== i) el.style.background = 'rgba(255,255,255,0.06)'
                  el.style.transform = 'translateY(-4px)'
                  el.style.boxShadow = '0 12px 32px -8px rgba(0,0,0,0.5)'
                }}
                onMouseLeave={e => {
                  const el = e.currentTarget as HTMLButtonElement
                  if (activeVid !== i) el.style.background = 'rgba(255,255,255,0.03)'
                  el.style.transform = 'translateY(0)'
                  el.style.boxShadow = 'none'
                }}
              >
                {/* thumbnail */}
                <div style={{ position: 'relative', aspectRatio: '16/9', overflow: 'hidden' }}>
                  <img src={v.thumb} alt="" style={{
                    width: '100%', height: '100%', objectFit: 'cover', display: 'block',
                    transition: 'transform .4s ease',
                  }} />
                  <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(3,10,25,0.7) 0%, transparent 60%)' }} />
                  {/* play icon */}
                  <div style={{
                    position: 'absolute', inset: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <div style={{
                      width: activeVid === i ? 36 : 28, height: activeVid === i ? 36 : 28,
                      borderRadius: '50%',
                      background: activeVid === i ? GOLD : 'rgba(255,255,255,0.2)',
                      backdropFilter: 'blur(4px)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      transition: 'all .25s',
                      boxShadow: activeVid === i ? `0 0 16px ${GOLD}88` : 'none',
                    }}>
                      <div style={{
                        width: 0, height: 0,
                        borderTop: '5px solid transparent', borderBottom: '5px solid transparent',
                        borderLeft: `8px solid ${activeVid === i ? NAVY : '#fff'}`,
                        marginLeft: 2,
                      }} />
                    </div>
                  </div>
                  {/* ep badge */}
                  <div style={{ position: 'absolute', bottom: 6, left: isFa ? 'auto' : 8, right: isFa ? 8 : 'auto' }}>
                    <span style={{ fontSize: 9.5, fontWeight: 800, color: GOLD, background: 'rgba(3,10,25,0.75)', backdropFilter: 'blur(4px)', padding: '2px 7px', borderRadius: 5 }}>{v.ep}</span>
                  </div>
                </div>

                {/* info */}
                <div style={{ padding: '10px 12px 12px', textAlign: isFa ? 'right' : 'left' }}>
                  <div style={{
                    fontSize: 11.5, fontWeight: 800, color: activeVid === i ? '#fff' : 'rgba(255,255,255,0.75)',
                    lineHeight: 1.45, marginBottom: 5,
                    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                    transition: 'color .2s',
                  }}>{v[lang].title}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, direction: 'ltr', justifyContent: isFa ? 'flex-end' : 'flex-start' }}>
                    <span style={{ fontSize: 10, color: GOLD, fontWeight: 700 }}>{v.duration}</span>
                    <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.2)' }}>·</span>
                    <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.3)', fontWeight: 600 }}>{v.date}</span>
                  </div>
                </div>
              </button>
            ))}
          </div>

        </div>
      </div>

      <FeaturedReportBanner position="media-split" />

      {/* ══ STATS BAR ══ */}
      <div style={{ background: NAVY, paddingTop: 48, paddingBottom: 48 }}>
        <div className="max-w-7xl mx-auto px-8 max-md:px-4">
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 0,
          }} className="max-md:!grid-cols-2">
            {[
              { num: '۷۷+', label: isFa ? 'اپیزود منتشرشده' : 'Episodes Published' },
              { num: '۲۰۰+', label: isFa ? 'ساعت محتوای تخصصی' : 'Hours of Content' },
              { num: '۶۰+', label: isFa ? 'مهمان خبره' : 'Expert Guests' },
              { num: '۴.۷', label: isFa ? 'میانگین امتیاز' : 'Average Rating' },
            ].map((s, i) => (
              <div key={i} style={{
                textAlign: 'center', padding: '24px 16px',
                borderRight: i < 3 ? '1px solid rgba(255,255,255,0.08)' : 'none',
              }} className="max-md:!border-none max-md:!border-b max-md:!border-white/5">
                <div style={{ fontSize: 'clamp(28px,3.5vw,44px)', fontWeight: 900, color: GOLD, lineHeight: 1, marginBottom: 8 }}>{s.num}</div>
                <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.5)', fontWeight: 600 }}>{s.label}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ══ ALL EPISODES GRID ══ */}
      <div style={{ background: '#f7f8fa', paddingTop: 72, paddingBottom: 80 }}>
        <div className="max-w-7xl mx-auto px-8 max-md:px-4">

          {/* header */}
          <div style={{ marginBottom: 40, direction: isFa ? 'rtl' : 'ltr' }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: GOLD, letterSpacing: '0.1em', marginBottom: 6 }}>
              {isFa ? 'آرشیو اپیزودها' : 'EPISODE ARCHIVE'}
            </div>
            <h2 style={{ fontSize: 'clamp(20px,2.5vw,30px)', fontWeight: 900, color: NAVY, margin: 0 }}>
              {isFa ? 'همه اپیزودها' : 'All Episodes'}
            </h2>
          </div>

          {/* grid */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 24,
          }} className="max-lg:!grid-cols-2 max-md:!grid-cols-1">
            {PODCASTS.map((p, i) => (
              <button key={p.id} onClick={() => { setActive(i); window.scrollTo({ top: 0, behavior: 'smooth' }) }}
                style={{
                  all: 'unset', cursor: 'pointer', display: 'flex', gap: 16,
                  background: '#fff', borderRadius: 18, padding: 16,
                  border: `1px solid ${active === i ? GOLD + '66' : 'rgba(0,0,0,0.06)'}`,
                  boxShadow: active === i ? `0 8px 32px -8px ${GOLD}44` : '0 2px 12px rgba(0,0,0,0.04)',
                  transition: 'all .25s', boxSizing: 'border-box',
                  flexDirection: isFa ? 'row-reverse' : 'row',
                  textAlign: isFa ? 'right' : 'left',
                }}
                onMouseEnter={e => {
                  (e.currentTarget as HTMLElement).style.transform = 'translateY(-3px)'
                  ;(e.currentTarget as HTMLElement).style.boxShadow = `0 16px 40px -12px ${GOLD}33`
                }}
                onMouseLeave={e => {
                  (e.currentTarget as HTMLElement).style.transform = 'translateY(0)'
                  ;(e.currentTarget as HTMLElement).style.boxShadow = active === i ? `0 8px 32px -8px ${GOLD}44` : '0 2px 12px rgba(0,0,0,0.04)'
                }}
              >
                {/* cover */}
                <div style={{
                  width: 80, height: 80, borderRadius: 12, overflow: 'hidden', flexShrink: 0,
                  border: active === i ? `2px solid ${GOLD}` : '2px solid transparent',
                }}>
                  <img src={p.cover} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                </div>
                {/* text */}
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minWidth: 0 }}>
                  <div>
                    <div style={{ fontSize: 10.5, fontWeight: 800, color: GOLD, marginBottom: 4 }}>{p.epNum}</div>
                    <div style={{
                      fontSize: 13.5, fontWeight: 800, color: NAVY, lineHeight: 1.45, marginBottom: 4,
                      display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                    }}>{p[lang].title}</div>
                    <div style={{ fontSize: 11.5, color: '#666', fontWeight: 600 }}>{p[lang].guest}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, direction: 'ltr', justifyContent: isFa ? 'flex-end' : 'flex-start' }}>
                    <span style={{ fontSize: 10.5, color: GOLD, fontWeight: 700 }}>★ {p.rating}</span>
                    <span style={{ fontSize: 10.5, color: '#aaa' }}>·</span>
                    <span style={{ fontSize: 10.5, color: '#aaa', fontWeight: 600 }}>{p.duration}</span>
                    <span style={{ fontSize: 10.5, color: '#aaa' }}>·</span>
                    <span style={{ fontSize: 10.5, color: '#bbb' }}>{p.date}</span>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* ══ WHY LISTEN ══ */}
      <div style={{ background: '#fff', paddingTop: 72, paddingBottom: 80 }}>
        <div className="max-w-7xl mx-auto px-8 max-md:px-4">

          <div style={{ textAlign: 'center', marginBottom: 56 }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: GOLD, letterSpacing: '0.1em', marginBottom: 10 }}>
              {isFa ? 'چرا پادکست اندیشکده؟' : 'WHY LISTEN?'}
            </div>
            <h2 style={{ fontSize: 'clamp(22px,3vw,36px)', fontWeight: 900, color: NAVY, margin: 0 }}>
              {isFa ? 'صدای متخصصان صنعت فولاد' : 'The Voice of Steel Industry Experts'}
            </h2>
          </div>

          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 28,
          }} className="max-lg:!grid-cols-1">
            {[
              {
                icon: '🎙️',
                title: isFa ? 'مهمانان خبره' : 'Expert Guests',
                desc: isFa
                  ? 'هر اپیزود با یکی از برجسته‌ترین متخصصان، مدیران و پژوهشگران صنعت فولاد ایران و جهان ضبط می‌شود.'
                  : 'Each episode features top steel industry experts, executives and researchers from Iran and around the world.',
              },
              {
                icon: '📊',
                title: isFa ? 'تحلیل عمیق' : 'Deep Analysis',
                desc: isFa
                  ? 'فراتر از اخبار روز؛ ما به ریشه‌ها، روندها و تحلیل صنعت فولاد می‌پردازیم.'
                  : 'Beyond daily news — we explore the roots, trends and analysis of the steel industry.',
              },
              {
                icon: '🔔',
                title: isFa ? 'انتشار منظم' : 'Regular Release',
                desc: isFa
                  ? 'هر هفته یک اپیزود جدید؛ همیشه به‌روز با تازه‌ترین تحولات بازار جهانی فولاد.'
                  : 'A new episode every week — always current with the latest global steel market developments.',
              },
            ].map((f, i) => (
              <div key={i} style={{
                background: '#f7f8fa', borderRadius: 20, padding: '36px 32px',
                border: '1px solid rgba(0,0,0,0.05)',
                textAlign: isFa ? 'right' : 'left',
              }}>
                <div style={{ fontSize: 36, marginBottom: 20 }}>{f.icon}</div>
                <h3 style={{ fontSize: 18, fontWeight: 900, color: NAVY, margin: '0 0 12px' }}>{f.title}</h3>
                <p style={{ fontSize: 13.5, lineHeight: 1.9, color: '#555', margin: 0 }}>{f.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

    </div>
  )
}
