import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Bookmark, CalendarDays, ChevronLeft, Mic2, Pause, Play, RotateCcw, RotateCw, Video, Volume2, VolumeX } from 'lucide-react'
import { useLang } from '@/context/LangContext'
import { authFetch, useAuth } from '@/context/AuthContext'
import { podcasts as PODCASTS, videos as VIDEOS } from '@/data/media'

const NAVY = '#032340'
const GOLD = '#CD9E53'

const CSS = `
.media-page{background:#fff;color:#032340;padding:48px 0 96px}.media-shell{width:min(1132px,calc(100% - 40px));margin:auto}.media-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}.media-heading h1,.media-heading h2{font-size:24px;font-weight:700;margin:0;border-inline-start:5px solid #CD9E53;padding-inline-start:13px}.media-view-all{display:inline-flex;align-items:center;gap:7px;color:#606060;font-size:14px}.video-stage{position:relative;width:100%;aspect-ratio:1.9/1;border-radius:16px;overflow:hidden;background:#061b2f}.video-stage img,.video-stage video{width:100%;height:100%;object-fit:cover;display:block}.video-stage video{object-fit:contain;background:#000}.video-overlay{position:absolute;inset:42% 0 0;background:linear-gradient(0deg,rgba(25,65,101,.92),transparent)}.video-play{position:absolute;inset:0;margin:auto;width:70px;height:70px;border:0;border-radius:50%;background:rgba(255,255,255,.9);color:#032340;display:grid;place-items:center;cursor:pointer;box-shadow:0 12px 36px rgba(0,0,0,.25)}.video-meta{position:absolute;inset:auto 28px 22px;display:flex;align-items:center;justify-content:space-between;color:#fff}.video-meta strong{font-size:16px}.video-meta span{font-size:13px;opacity:.86}.video-details{display:grid;grid-template-columns:491px minmax(0,1fr);gap:76px;align-items:start;margin:42px 0 78px}.playlist-title,.story-title{display:flex;align-items:center;justify-content:flex-start;gap:11px;font-size:23px;font-weight:700;margin-bottom:18px}.playlist{display:flex;flex-direction:column;gap:18px}.playlist-item{all:unset;box-sizing:border-box;cursor:pointer;display:grid;grid-template-columns:minmax(0,1fr) 266px;align-items:center;gap:14px;text-align:right;color:#032340}.playlist-copy strong{display:block;font-size:15px;line-height:1.65;margin-bottom:8px}.playlist-copy span{display:flex;align-items:center;gap:6px;color:#777;font-size:12px}.playlist-thumb{height:102px;border-radius:8px;overflow:hidden;position:relative}.playlist-thumb img{width:100%;height:100%;object-fit:cover}.playlist-thumb i{position:absolute;inset:0;margin:auto;width:42px;height:42px;border-radius:50%;background:rgba(255,255,255,.92);display:grid;place-items:center;color:#032340}.playlist-item.active strong{color:#CD9E53}.video-story p,.pod-story p{margin:0;color:#7c7c7c;font-size:15px;line-height:2.25;text-align:justify}.video-story .tags{color:#CD9E53;margin-top:12px}.podcast-section{padding-top:2px}.pod-feature{display:grid;grid-template-columns:minmax(0,1fr) 195px;background:#ededed;border-radius:16px;overflow:hidden;min-height:248px}.pod-feature-main{padding:25px 28px 18px;display:flex;flex-direction:column;min-width:0}.pod-topline{display:flex;justify-content:space-between;gap:20px}.pod-label{color:#CD9E53;font-size:16px;margin-bottom:9px}.pod-title{font-size:22px;line-height:1.55;margin:0;font-weight:700}.pod-date{display:flex;align-items:center;gap:6px;color:#777;font-size:12px;margin-top:8px}.bookmark-btn{width:38px;height:38px;border:0;background:transparent;color:#032340;display:grid;place-items:center;cursor:pointer}.wave-wrap{margin-top:auto;border-top:1px solid #b6b6b6;padding-top:9px}.pod-cover{min-height:248px}.pod-cover img{width:100%;height:100%;object-fit:cover;display:block}.player-wave{height:58px;display:flex;align-items:center;gap:2px;direction:ltr;overflow:hidden;cursor:pointer}.player-wave span{flex:1 1 0;min-width:1px;max-width:5px;border-radius:9px;background:rgba(3,35,64,.35)}.player-wave span.played{background:#CD9E53}.player-controls{display:flex;align-items:center;gap:12px;direction:ltr;color:#032340;font-size:11px}.round-play{width:38px;height:38px;border:0;border-radius:50%;background:#CD9E53;color:#032340;display:grid;place-items:center;cursor:pointer}.mute{border:0;background:transparent;color:#032340;display:grid;place-items:center;cursor:pointer}.pod-lower{display:grid;grid-template-columns:1fr 1fr;gap:76px;margin-top:30px}.pod-story-title{display:flex;align-items:center;gap:10px;font-size:20px;font-weight:700;margin-bottom:14px}.guest{margin-top:17px;color:#032340;font-size:13px}.guest b{color:#CD9E53}.episode-cards{display:flex;flex-direction:column;gap:14px}.episode-card{all:unset;box-sizing:border-box;cursor:pointer;display:grid;grid-template-columns:minmax(0,1fr) 166px;background:#f7f7f7;border-radius:12px;overflow:hidden;min-height:112px;color:#032340}.episode-card-copy{padding:15px 17px;text-align:right}.episode-card-copy small{color:#CD9E53;font-size:10px}.episode-card-copy strong{display:block;font-size:14px;line-height:1.65;margin:8px 0}.episode-card-copy span{font-size:11px;color:#888}.episode-card img{width:100%;height:100%;object-fit:cover}.media-empty{color:#888;font-size:13px}.media-page button:focus-visible{outline:3px solid rgba(205,158,83,.55);outline-offset:3px}
@media(max-width:800px){.media-page{padding-top:30px}.media-shell{width:min(100% - 28px,1132px)}.media-heading h1,.media-heading h2{font-size:20px}.video-stage{aspect-ratio:16/10}.video-details{grid-template-columns:1fr;gap:36px;margin:30px 0 58px}.playlist-item{grid-template-columns:minmax(0,1fr) 44%;}.playlist-thumb{height:88px}.pod-feature{grid-template-columns:1fr}.pod-cover{order:-1;min-height:240px;max-height:300px}.pod-feature-main{padding:20px 17px}.pod-lower{grid-template-columns:1fr;gap:30px}.pod-story{order:-1}.video-meta{inset:auto 14px 14px}.video-meta strong{font-size:13px}.pod-title{font-size:18px}.media-view-all{font-size:12px}.episode-card{grid-template-columns:minmax(0,1fr) 120px}}
@media(max-width:460px){.media-shell{width:calc(100% - 20px)}.media-heading{margin-bottom:14px}.video-stage{border-radius:11px}.video-play{width:52px;height:52px}.video-meta span{display:none}.video-details{margin-top:25px}.playlist-title,.story-title{font-size:19px}.playlist-item{grid-template-columns:1fr 132px;gap:10px}.playlist-copy strong{font-size:12px}.playlist-copy span{font-size:10px}.playlist-thumb{height:76px}.pod-feature{border-radius:12px}.pod-cover{min-height:210px}.player-wave{height:52px}.episode-card{grid-template-columns:1fr 105px}.episode-card-copy{padding:12px}.episode-card-copy strong{font-size:12px}.video-story p,.pod-story p{font-size:13px;line-height:2.1}}

.pod-feature{grid-template-columns:minmax(0,1fr) 248px}.pod-cover{width:248px;min-height:248px;aspect-ratio:1}.pod-cover img{aspect-ratio:1;object-fit:cover}
.pod-story .tags{color:#CD9E53;margin-top:12px;white-space:pre-wrap}
.tag-list{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.tag-chip{border:1px solid rgba(205,158,83,.42);background:rgba(205,158,83,.08);color:#9a6a1e;border-radius:999px;padding:5px 11px;font:inherit;font-size:12px;cursor:pointer;transition:background .15s,color .15s}.tag-chip:hover{background:#CD9E53;color:#032340}
.media-divider{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:16px;margin:0 0 58px}.media-divider::before,.media-divider::after{content:'';height:1px;background:linear-gradient(90deg,transparent,rgba(3,35,64,.2),rgba(205,158,83,.7))}.media-divider::after{background:linear-gradient(90deg,rgba(205,158,83,.7),rgba(3,35,64,.2),transparent)}.media-divider-mark{width:42px;height:42px;border:1px solid rgba(205,158,83,.5);border-radius:50%;display:grid;place-items:center;background:#fff;box-shadow:0 8px 24px rgba(3,35,64,.08);position:relative}.media-divider-mark::before{content:'';width:8px;height:8px;background:#CD9E53;transform:rotate(45deg);border-radius:2px}.media-divider-mark::after{content:'';position:absolute;inset:6px;border:1px solid rgba(3,35,64,.1);border-radius:50%}
.wave-wrap{width:calc(100% - 20px);margin-inline:10px}
.player-wave{width:100%}.player-wave span{max-width:none}
.skip-btn{position:relative;width:30px;height:30px;border:0;background:transparent;color:#032340;display:grid;place-items:center;cursor:pointer}.skip-btn small{position:absolute;font-size:8px;font-weight:900}
@media(max-width:800px){.pod-feature{grid-template-columns:1fr}.wave-wrap{width:calc(100% - 12px);margin-inline:6px}.pod-cover{width:min(100%,320px);min-height:0;aspect-ratio:1;margin-inline:auto}.pod-cover img{aspect-ratio:1}}
@media(max-width:600px){
  .podcast-section .media-heading{margin-bottom:16px}
  .pod-feature{display:flex;flex-direction:column;border-radius:16px;padding-top:18px}
  .pod-cover{order:-1;width:168px;height:168px;min-height:168px;max-height:168px;margin:0 auto;border-radius:14px;overflow:hidden;box-shadow:0 10px 28px rgba(3,35,64,.14)}
  .pod-cover img{width:168px;height:168px;aspect-ratio:1;object-fit:cover}
  .pod-feature-main{padding:18px 18px 20px}
  .pod-topline{align-items:flex-start;gap:8px}
  .pod-label{font-size:13px;margin-bottom:6px}
  .pod-title{font-size:17px;line-height:1.65}
  .pod-date{font-size:10.5px;line-height:1.8;flex-wrap:wrap}
  .bookmark-btn{width:34px;height:34px;flex:0 0 34px}
  .wave-wrap{width:100%;margin-inline:0;margin-top:16px;padding-top:10px}
  .player-wave{height:50px;gap:1.5px}
  .player-controls{justify-content:center;gap:8px;flex-wrap:nowrap}
  .pod-lower{margin-top:34px;gap:28px}
  .pod-story-title{font-size:17px;line-height:1.7;margin-bottom:10px}
  .episode-cards{gap:0;width:100%;align-items:stretch;border-top:1px solid rgba(3,35,64,.09)}
  .episode-card{direction:ltr;width:100%;grid-template-columns:minmax(0,1fr) 132px;height:104px;min-height:104px;padding:13px 0;background:transparent;border:0;border-bottom:1px solid rgba(3,35,64,.09);border-radius:0;box-shadow:none;gap:12px}
  .episode-card-copy{direction:rtl;text-align:right;padding:0;display:flex;flex-direction:column;justify-content:center;min-width:0}
  .episode-card-copy small{font-size:9.5px}
  .episode-card-copy strong{font-size:12px;line-height:1.65;margin:4px 0 6px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
  .episode-card-copy span{font-size:9.5px;line-height:1.6;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#818995}
  .episode-card img{grid-column:2;width:132px;height:78px;align-self:center;object-fit:cover;border-radius:9px;box-shadow:none}
  .tag-list{gap:6px}.tag-chip{font-size:10.5px;padding:4px 9px}
}
`

function barsFor(seedValue: string | number, count = 82) {
  let seed = String(seedValue).split('').reduce((a, c) => a + c.charCodeAt(0), 19)
  return Array.from({ length: count }, (_, i) => {
    seed = (seed * 9301 + 49297) % 233280
    const envelope = .42 + .25 * Math.sin(i * .31) + .13 * Math.sin(i * .83)
    return Math.max(.18, Math.min(.94, envelope + (seed / 233280) * .28))
  })
}

function MediaDuration({ src, fallback = '', video = false, fa = true }: { src?: string; fallback?: string; video?: boolean; fa?: boolean }) {
  const [seconds, setSeconds] = useState(0)
  useEffect(() => {
    setSeconds(0)
    if (!src) return
    const media = document.createElement(video ? 'video' : 'audio')
    media.preload = 'metadata'
    const loaded = () => { if (Number.isFinite(media.duration)) setSeconds(media.duration); media.removeAttribute('src'); media.load() }
    media.addEventListener('loadedmetadata', loaded, { once: true })
    media.src = src
    return () => { media.removeEventListener('loadedmetadata', loaded); media.removeAttribute('src'); media.load() }
  }, [src, video])
  if (!seconds) return fallback ? <>{fallback}</> : null
  const total = Math.round(seconds)
  const hours = Math.floor(total / 3600)
  const minutes = Math.floor((total % 3600) / 60)
  const secs = String(total % 60).padStart(2, '0')
  const value = hours ? `${hours}:${String(minutes).padStart(2, '0')}:${secs}` : `${minutes}:${secs}`
  return <>{fa ? value.replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[Number(d)]) : value}</>
}

function AudioWave({ src, id }: { src?: string; id: string | number }) {
  const audio = useRef<HTMLAudioElement>(null)
  const [playing, setPlaying] = useState(false)
  const [muted, setMuted] = useState(false)
  const [current, setCurrent] = useState(0)
  const [duration, setDuration] = useState(0)
  const bars = useMemo(() => barsFor(id), [id])
  const progress = duration ? current / duration : 0
  useEffect(() => { setPlaying(false); setCurrent(0); setDuration(0); audio.current?.load() }, [src, id])
  const fmt = (v: number) => Number.isFinite(v) ? `${Math.floor(v / 60)}:${String(Math.floor(v % 60)).padStart(2, '0')}` : '0:00'
  const toggle = async () => {
    if (!audio.current || !src) return
    if (audio.current.paused) await audio.current.play(); else audio.current.pause()
  }
  const seek = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!audio.current || !duration) return
    const box = e.currentTarget.getBoundingClientRect()
    audio.current.currentTime = Math.max(0, Math.min(1, (e.clientX - box.left) / box.width)) * duration
  }
  const skip = (seconds: number) => {
    if (!audio.current) return
    const end = duration || audio.current.duration || 0
    audio.current.currentTime = Math.max(0, Math.min(end, audio.current.currentTime + seconds))
    setCurrent(audio.current.currentTime)
  }
  return <div>
    <audio ref={audio} src={src} preload="metadata" onLoadedMetadata={e => setDuration(Number.isFinite(e.currentTarget.duration) ? e.currentTarget.duration : 0)} onTimeUpdate={e => setCurrent(e.currentTarget.currentTime)} onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)} />
    <div className="player-wave" onClick={seek} role="slider" aria-label="موقعیت پخش" aria-valuemin={0} aria-valuemax={Math.round(duration)} aria-valuenow={Math.round(current)} tabIndex={0}>
      {bars.map((h, i) => <span key={i} className={(i + .5) / bars.length <= progress ? 'played' : ''} style={{ height: `${Math.round(h * 50)}px` }} />)}
    </div>
    <div className="player-controls">
      <button className="skip-btn" onClick={() => skip(-10)} disabled={!src} aria-label="۱۰ ثانیه عقب"><RotateCcw size={21} /><small>۱۰</small></button>
      <button className="round-play" onClick={toggle} disabled={!src} aria-label={playing ? 'توقف' : 'پخش'}>{playing ? <Pause size={15} fill="currentColor" /> : <Play size={15} fill="currentColor" />}</button>
      <button className="skip-btn" onClick={() => skip(10)} disabled={!src} aria-label="۱۰ ثانیه جلو"><RotateCw size={21} /><small>۱۰</small></button>
      <b>{fmt(current)}</b><span>{fmt(duration)}</span>
      <button className="mute" onClick={() => { if (!audio.current) return; audio.current.muted = !audio.current.muted; setMuted(audio.current.muted) }} aria-label="صدا">{muted ? <VolumeX size={17} /> : <Volume2 size={17} />}</button>
    </div>
  </div>
}

export default function PodcastFigma() {
  const { lang } = useLang()
  const { member } = useAuth()
  const navigate = useNavigate()
  const fa = lang === 'fa'
  const [activeVideo, setActiveVideo] = useState(0)
  const [videoPlaying, setVideoPlaying] = useState(false)
  const [activePodcast, setActivePodcast] = useState(0)
  const [bookmarks, setBookmarks] = useState<Set<string>>(new Set())
  const [busy, setBusy] = useState(false)
  const video = VIDEOS[activeVideo]
  const podcast = PODCASTS[activePodcast]

  useEffect(() => {
    if (!member) { setBookmarks(new Set()); return }
    authFetch('/api/members/me/bookmarks').then(r => r.ok ? r.json() : []).then(items => {
      if (Array.isArray(items)) setBookmarks(new Set(items.filter(x => x.contentType === 'podcast').map(x => String(x.contentId))))
    }).catch(() => {})
  }, [member])

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

  if (!video || !podcast) return <div className="media-page"><div className="media-shell media-empty">محتوایی برای نمایش وجود ندارد.</div></div>

  return <main className="media-page" dir={fa ? 'rtl' : 'ltr'}>
    <style>{CSS}</style>
    <div className="media-shell">
      <section>
        <header className="media-heading"><h1>{fa ? 'ویدیوکست‌ها' : 'Videocasts'}</h1><span className="media-view-all">{fa ? 'مشاهده همه' : 'View all'} <ChevronLeft size={15} /></span></header>
        <div className="video-stage">
          {videoPlaying && video.mediaUrl ? <video src={video.mediaUrl} controls autoPlay onEnded={() => setVideoPlaying(false)} /> : <>
            <img src={video.thumb} alt={video[lang].title} /><div className="video-overlay" />
            <button className="video-play" onClick={() => video.mediaUrl && setVideoPlaying(true)} aria-label={fa ? 'پخش ویدیو' : 'Play video'}><Play size={28} fill="currentColor" /></button>
            <div className="video-meta"><strong>{video[lang].title}</strong><span><MediaDuration src={video.mediaUrl} fallback={video.duration} video fa={fa} /></span></div>
          </>}
        </div>

        <div className="video-details">
          <article className="video-story"><div className="story-title">{video[lang].title}<Video size={27} strokeWidth={1.6} /></div>{video[lang].body && <p>{video[lang].body}</p>}{Boolean(video.tags?.length) && <div className="tag-list">{video.tags!.map(tag => <button type="button" className="tag-chip" key={tag} onClick={() => navigate(`/search?tag=${encodeURIComponent(tag)}`)}>#{tag.replace(/\s+/g, '_')}</button>)}</div>}</article>
          <div>
            <div className="playlist-title"><Video size={27} strokeWidth={1.6} />{fa ? 'پلی‌لیست' : 'Playlist'}</div>
            <div className="playlist">{VIDEOS.slice(0, 3).map((item, index) => <button key={item.id} className={`playlist-item ${index === activeVideo ? 'active' : ''}`} onClick={() => { setActiveVideo(index); setVideoPlaying(false) }}>
              <div className="playlist-copy"><strong>{item[lang].title}</strong><span><CalendarDays size={16} color={GOLD} />{item.date}{(item.mediaUrl || item.duration) && <> · <MediaDuration src={item.mediaUrl} fallback={item.duration} video fa={fa} /></>}</span></div>
              <div className="playlist-thumb"><img src={item.thumb} alt="" /><i><Play size={18} fill="currentColor" /></i></div>
            </button>)}</div>
          </div>
        </div>
      </section>

      <div className="media-divider" aria-hidden="true"><span className="media-divider-mark" /></div>

      <section className="podcast-section">
        <header className="media-heading"><h2>{fa ? 'پادکست‌ها' : 'Podcasts'}</h2><span className="media-view-all">{fa ? 'مشاهده همه' : 'View all'} <ChevronLeft size={15} /></span></header>
        <div className="pod-feature">
          <div className="pod-feature-main">
            <div className="pod-topline"><div><div className="pod-label">{podcast.epNum}</div><h3 className="pod-title">{podcast[lang].title}</h3><div className="pod-date"><CalendarDays size={17} color={GOLD} />{podcast.date}{(podcast.mediaUrl || podcast.duration) && <> · <MediaDuration src={podcast.mediaUrl} fallback={podcast.duration} fa={fa} /></>}</div></div><button className="bookmark-btn" onClick={toggleBookmark} disabled={busy} aria-label="ذخیره"><Bookmark size={26} fill={bookmarks.has(String(podcast.id)) ? 'currentColor' : 'none'} color={bookmarks.has(String(podcast.id)) ? GOLD : NAVY} /></button></div>
            <div className="wave-wrap"><AudioWave src={podcast.mediaUrl} id={podcast.id} /></div>
          </div>
          <div className="pod-cover"><img src={podcast.cover} alt={podcast[lang].title} /></div>
        </div>

        <div className="pod-lower">
          <article className="pod-story"><div className="pod-story-title"><Mic2 size={23} color={GOLD} />{podcast[lang].title}</div>{podcast[lang].body && <p>{podcast[lang].body}</p>}{Boolean(podcast[lang].guest?.trim()) && <div className="guest">{fa ? 'مهمان برنامه:' : 'Guest:'} <b>{podcast[lang].guest}</b></div>}{Boolean(podcast.tags?.length) && <div className="tag-list">{podcast.tags!.map(tag => <button type="button" className="tag-chip" key={tag} onClick={() => navigate(`/search?tag=${encodeURIComponent(tag)}`)}>#{tag.replace(/\s+/g, '_')}</button>)}</div>}</article>
          <div className="episode-cards">{PODCASTS.filter((_, i) => i !== activePodcast).slice(0, 2).map(item => <button className="episode-card" key={item.id} onClick={() => setActivePodcast(PODCASTS.findIndex(p => p.id === item.id))}><div className="episode-card-copy"><small>{item.epNum}</small><strong>{item[lang].title}</strong><span>{item.date}{(item.mediaUrl || item.duration) && <> · <MediaDuration src={item.mediaUrl} fallback={item.duration} fa={fa} /></>}</span></div><img src={item.cover} alt="" /></button>)}</div>
        </div>
      </section>
    </div>
  </main>
}
