import { useState, useRef, useEffect, useCallback, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { useLang } from '@/context/LangContext'
import { authFetch, useAuth } from '@/context/AuthContext'
import { ChevronLeft, ChevronRight, PlayCircle, Play, Pause, Volume2, VolumeX, CalendarDays, Bookmark, Mic2 } 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 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;
}
.podcast-figma-feature { display:grid; grid-template-columns:minmax(0,1fr) 195px; }
.podcast-figma-content { padding:28px 30px 22px; }
.podcast-figma-cover { min-height:212px; }
.podcast-figma-intro { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:72px; }
@media (max-width: 760px) {
  .podcast-figma-feature { grid-template-columns:1fr; }
  .podcast-figma-cover { min-height:220px; order:-1; }
  .podcast-figma-content { padding:22px 18px 18px; }
  .podcast-figma-intro { grid-template-columns:1fr; gap:24px; }
}
`

/* ══ Real waveform audio player ══ */
function mediaWaveBars(seedValue: string | number, count = 74) {
  let seed = String(seedValue).split('').reduce((sum, char) => sum + char.charCodeAt(0), 17)
  return Array.from({ length: count }, (_, index) => {
    seed = (seed * 9301 + 49297) % 233280
    const random = seed / 233280
    const envelope = 0.48 + 0.28 * Math.sin(index * 0.31) + 0.16 * Math.sin(index * 0.83)
    return Math.max(0.16, Math.min(0.96, envelope + random * 0.3))
  })
}

/* ══ Uploaded-file waveform player ══ */
function MediaWavePlayer({ src, episodeKey, light = false }: { src: string; episodeKey: string | number; light?: boolean }) {
  const audioRef = useRef<HTMLAudioElement>(null)
  const [playing, setPlaying] = useState(false)
  const [muted, setMuted] = useState(false)
  const [current, setCurrent] = useState(0)
  const [duration, setDuration] = useState(0)
  const [failed, setFailed] = useState(false)
  const bars = useMemo(() => mediaWaveBars(episodeKey), [episodeKey])
  const progress = duration > 0 ? Math.min(current / duration, 1) : 0

  useEffect(() => {
    const audio = audioRef.current
    if (!audio) return
    audio.pause()
    audio.currentTime = 0
    setPlaying(false)
    setMuted(false)
    setCurrent(0)
    setDuration(0)
    setFailed(false)
    audio.load()
  }, [src, episodeKey])

  const toggle = async () => {
    const audio = audioRef.current
    if (!audio || failed) return
    if (audio.paused) {
      try {
        await audio.play()
        setPlaying(true)
      } catch {
        setFailed(true)
      }
    } else {
      audio.pause()
      setPlaying(false)
    }
  }

  const seek = (event: React.MouseEvent<HTMLDivElement>) => {
    const audio = audioRef.current
    if (!audio || !duration) return
    const rect = event.currentTarget.getBoundingClientRect()
    const ratio = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width))
    audio.currentTime = ratio * duration
    setCurrent(audio.currentTime)
  }

  const toggleMute = () => {
    const audio = audioRef.current
    if (!audio) return
    audio.muted = !audio.muted
    setMuted(audio.muted)
  }

  const fmt = (seconds: number) => {
    if (!Number.isFinite(seconds) || seconds < 0) return '0:00'
    const minutes = Math.floor(seconds / 60)
    return `${minutes}:${String(Math.floor(seconds % 60)).padStart(2, '0')}`
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <audio
        ref={audioRef}
        src={src}
        preload="metadata"
        onLoadedMetadata={(event) => setDuration(Number.isFinite(event.currentTarget.duration) ? event.currentTarget.duration : 0)}
        onDurationChange={(event) => setDuration(Number.isFinite(event.currentTarget.duration) ? event.currentTarget.duration : 0)}
        onTimeUpdate={(event) => setCurrent(event.currentTarget.currentTime)}
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
        onEnded={() => { setPlaying(false); setCurrent(0) }}
        onError={() => setFailed(true)}
        style={{ display: 'none' }}
      />

      <div
        role="slider"
        aria-label="موقعیت پخش پادکست"
        aria-valuemin={0}
        aria-valuemax={Math.max(0, Math.round(duration))}
        aria-valuenow={Math.round(current)}
        tabIndex={0}
        onClick={seek}
        onKeyDown={(event) => {
          const audio = audioRef.current
          if (!audio || !duration) return
          if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
            event.preventDefault()
            const delta = event.key === 'ArrowRight' ? 5 : -5
            audio.currentTime = Math.max(0, Math.min(duration, audio.currentTime + delta))
          }
        }}
        style={{
          width: '100%', maxWidth: '100%', height: 64, display: 'flex', alignItems: 'center', gap: 2,
          cursor: duration ? 'pointer' : 'default', direction: 'ltr',
          borderRadius: 10, padding: '0 4px', outline: 'none', overflow: 'hidden', boxSizing: 'border-box',
        }}
      >
        {bars.map((height, index) => {
          const played = (index + 0.5) / bars.length <= progress
          return (
            <span key={index} style={{
              flex: '1 1 0', minWidth: 1, maxWidth: 6,
              height: `${Math.round(height * 54)}px`, borderRadius: 999,
              background: played ? GOLD : (light ? 'rgba(3,35,64,0.55)' : 'rgba(255,255,255,0.18)'),
              boxShadow: played ? `0 0 8px ${GOLD}55` : 'none',
              transition: 'background-color 160ms ease, box-shadow 160ms ease',
            }} />
          )
        })}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, direction: 'ltr' }}>
        <button type="button" onClick={toggle} disabled={failed} aria-label={playing ? 'توقف پادکست' : 'پخش پادکست'} style={{
          width: 42, height: 42, borderRadius: '50%', border: 'none', flexShrink: 0,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          background: failed ? 'rgba(3,35,64,0.12)' : GOLD,
          color: NAVY, cursor: failed ? 'not-allowed' : 'pointer',
          boxShadow: playing ? `0 0 18px ${GOLD}66` : 'none',
        }}>
          {playing ? <Pause size={17} fill={NAVY} /> : <Play size={17} fill={NAVY} style={{ marginLeft: 2 }} />}
        </button>

        <span style={{ minWidth: 38, color: light ? NAVY : '#fff', fontSize: 11, fontWeight: 800 }}>{fmt(current)}</span>
        <span style={{ minWidth: 38, textAlign: 'right', color: light ? 'rgba(3,35,64,0.55)' : 'rgba(255,255,255,0.48)', fontSize: 11, fontWeight: 700 }}>{fmt(duration)}</span>
        <button type="button" onClick={toggleMute} aria-label={muted ? 'فعال کردن صدا' : 'قطع صدا'} style={{ border: 0, background: 'transparent', padding: 5, cursor: 'pointer', display: 'flex' }}>
          {muted ? <VolumeX size={17} color={light ? NAVY : 'rgba(255,255,255,0.55)'} /> : <Volume2 size={17} color={light ? NAVY : 'rgba(255,255,255,0.55)'} />}
        </button>
      </div>

      {failed && <div style={{ color: '#fca5a5', fontSize: 11, textAlign: 'right' }}>فایل صوتی قابل پخش نیست. آدرس فایل یا فرمت آن را بررسی کنید.</div>}
    </div>
  )
}

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>
  )
}

/* ══ MAIN ══ */
export default function Podcast() {
  const { lang } = useLang()
  const { member } = useAuth()
  const navigate = useNavigate()
  const t = T[lang]
  const isFa = lang === 'fa'
  const [active, setActive]     = useState(0)
  const [activeVid, setActiveVid] = useState(0)
  const [vidPlaying, setVidPlaying] = useState(false)
  const [bookmarkedIds, setBookmarkedIds] = useState<Set<string>>(new Set())
  const [bookmarkBusy, setBookmarkBusy] = useState(false)
  const pod = PODCASTS[active]
  const vid = VIDEOS[activeVid]
  const showPodGuest = Boolean(pod[lang].guest?.trim())

  useEffect(() => {
    if (!member) { setBookmarkedIds(new Set()); return }
    let mounted = true
    authFetch('/api/members/me/bookmarks')
      .then(async response => response.ok ? response.json() : [])
      .then(items => {
        if (!mounted || !Array.isArray(items)) return
        setBookmarkedIds(new Set(items.filter(item => item.contentType === 'podcast').map(item => String(item.contentId))))
      })
      .catch(() => {})
    return () => { mounted = false }
  }, [member])

  const togglePodcastBookmark = async () => {
    if (!member) { navigate('/login'); return }
    if (bookmarkBusy) return
    const contentId = String(pod.id)
    const saved = bookmarkedIds.has(contentId)
    setBookmarkBusy(true)
    try {
      const response = saved
        ? await authFetch(`/api/members/me/bookmarks/podcast/${encodeURIComponent(contentId)}`, { method: 'DELETE' })
        : await authFetch('/api/members/me/bookmarks', {
            method: 'POST',
            body: JSON.stringify({ contentId, contentType: 'podcast', title: pod[lang].title, summary: pod[lang].body, coverImage: pod.cover, path: '/podcast' }),
          })
      if (!response.ok) return
      setBookmarkedIds(current => {
        const next = new Set(current)
        if (saved) next.delete(contentId); else next.add(contentId)
        return next
      })
    } finally { setBookmarkBusy(false) }
  }

  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: 72 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <span style={{ color: '#606060', fontSize: 14 }}>{isFa ? 'مشاهده همه' : 'View all'}</span>
            <h1 style={{ margin: 0, color: NAVY, fontSize: 24, fontWeight: 800, borderRight: isFa ? `5px solid ${GOLD}` : 0, borderLeft: !isFa ? `5px solid ${GOLD}` : 0, paddingRight: isFa ? 12 : 0, paddingLeft: !isFa ? 12 : 0 }}>
              {isFa ? 'پادکست‌ها' : 'Podcasts'}
            </h1>
          </div>

          <section className="podcast-figma-feature" style={{ background: '#ededed', borderRadius: 16, overflow: 'hidden', color: NAVY }}>
            <div className="podcast-figma-content" style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
                <button type="button" onClick={togglePodcastBookmark} disabled={bookmarkBusy} aria-label={bookmarkedIds.has(String(pod.id)) ? (isFa ? 'حذف از علاقه‌مندی‌ها' : 'Remove bookmark') : (isFa ? 'ذخیره در علاقه‌مندی‌ها' : 'Bookmark')} style={{ width: 36, height: 36, border: 0, background: 'transparent', color: bookmarkedIds.has(String(pod.id)) ? GOLD : NAVY, cursor: bookmarkBusy ? 'wait' : 'pointer', display: 'grid', placeItems: 'center' }}>
                  <Bookmark size={27} strokeWidth={1.6} fill={bookmarkedIds.has(String(pod.id)) ? 'currentColor' : 'none'} />
                </button>
                <div style={{ textAlign: isFa ? 'right' : 'left' }}>
                  <div style={{ color: GOLD, fontSize: 17, marginBottom: 14 }}>{pod.epNum}</div>
                  <h2 style={{ margin: 0, color: NAVY, fontSize: 'clamp(20px,2.2vw,29px)', lineHeight: 1.45, fontWeight: 700 }}>{pod[lang].title}</h2>
                  <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 7, color: '#606060', fontSize: 13, justifyContent: isFa ? 'flex-start' : 'flex-end' }}>
                    <CalendarDays size={19} color={GOLD} />
                    <span>{pod.date}</span>
                  </div>
                </div>
              </div>
              <div style={{ height: 1, background: '#adadad', margin: '16px 0 4px' }} />
              <div style={{ marginTop: 'auto' }}>
                {pod.mediaUrl
                  ? <MediaWavePlayer src={pod.mediaUrl} episodeKey={pod.id} light />
                  : <WavePlayer episodeKey={pod.id} />}
              </div>
            </div>

            <div className="podcast-figma-cover" style={{ position: 'relative', background: NAVY }}>
              <img src={pod.cover} alt={pod[lang].title} style={{ width: '100%', height: '100%', minHeight: 'inherit', objectFit: 'cover', display: 'block' }} />
            </div>
          </section>

          <section className="podcast-figma-intro" style={{ marginTop: 54, color: NAVY, alignItems: 'start' }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <Mic2 size={28} color={GOLD} />
                <h2 style={{ margin: 0, fontSize: 24, lineHeight: 1.5 }}>{pod[lang].title}</h2>
              </div>
              <p style={{ margin: 0, color: '#989898', fontSize: 16, lineHeight: 2.05, textAlign: 'justify' }}>{pod[lang].body}</p>
              {showPodGuest && (
                <div style={{ marginTop: 18, fontSize: 16, color: NAVY, fontWeight: 700 }}>
                  {isFa ? 'مهمان برنامه: ' : 'Guest: '}<span style={{ color: GOLD }}>{pod[lang].guest}</span>
                </div>
              )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 14 }}>
              {PODCASTS.filter((_, index) => index !== active).slice(0, 2).map((item) => {
                const sourceIndex = PODCASTS.indexOf(item)
                return (
                  <button key={item.id} type="button" onClick={() => setActive(sourceIndex)} style={{ border: 0, background: '#f9f9f9', borderRadius: 12, padding: 8, display: 'grid', gridTemplateColumns: isFa ? '1fr 132px' : '132px 1fr', gap: 18, alignItems: 'center', minHeight: 142, cursor: 'pointer', color: NAVY, textAlign: isFa ? 'right' : 'left', fontFamily: 'inherit' }}>
                    <div style={{ padding: '12px 14px' }}>
                      <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>{item[lang].title}</div>
                      <div style={{ color: '#606060', fontSize: 13 }}>{item.duration}</div>
                    </div>
                    <img src={item.cover} alt="" style={{ width: '100%', height: 126, borderRadius: 16, objectFit: 'cover', order: isFa ? 2 : 0 }} />
                  </button>
                )
              })}
            </div>
          </section>
        </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>
                    {Boolean(p[lang].guest?.trim()) && (
                      <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>
  )
}
