"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import {
  Play,
  Heart,
  ThumbsUp,
  ThumbsDown,
  MessageCircle,
  Share2,
  Download,
  Users,
  Eye,
  ChevronRight,
  Music2,
  Radio as RadioIcon,
  Headphones,
  ArrowLeft,
  Lock,
  Check,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { CommentSection } from "@/components/shared/CommentSection";
import { setTrack, setQueue } from "@/store/slices/playerSlice";
import { useAddView } from "@/hooks/useAddView";
import { useAddToHistory } from "@/hooks/useAddToHistory";
import { useSubscribe } from "@/hooks/useSubscribe";
import { useLikeDislike } from "@/hooks/useLikeDislike";
import { useShare } from "@/hooks/useShare";
import {
  contentDetailService,
  type ContentDetail,
  type Episode,
  type RelatedMusic,
} from "@/services/contentDetailService";
import type { MusicItem } from "@/services/musicSectionService";

/* ── helpers ────────────────────────────────────────────────────────────────── */

function toMusicItem(d: ContentDetail | RelatedMusic): MusicItem {
  return {
    id: d.id,
    contentType: d.contentType,
    title: d.title,
    thumbnail: d.thumbnail,
    landscapeImg: d.landscapeImg,
    audioUrl: d.audioUrl,
    channelName: d.channelName,
    channelImage: d.channelImage,
    duration: d.duration,
    durationMs: 0,
    views: d.views,
    likes: String(d.totalLike),
    category: d.categoryName,
    language: d.languageName,
    isDownload: !!d.isDownload,
    isRent: !!d.isBuy,
    rentPrice: 0,
  };
}

function episodeToMusicItem(ep: Episode, detail: ContentDetail): MusicItem {
  return {
    id: ep.id,
    contentType: 4,
    title: ep.name,
    thumbnail: ep.thumbnail || detail.thumbnail,
    landscapeImg: ep.landscapeImg || detail.landscapeImg,
    audioUrl: ep.audioUrl,
    channelName: detail.channelName,
    channelImage: detail.channelImage,
    duration: "",
    durationMs: 0,
    views: String(ep.views),
    likes: String(ep.totalLike),
    category: "",
    language: "",
    isDownload: !!ep.isDownload,
    isRent: ep.isBuy === 1,
    rentPrice: 0,
  };
}

/* ── Avatar ─────────────────────────────────────────────────────────────────── */

function ChannelAvatar({
  src,
  name,
  size = 40,
}: {
  src: string;
  name: string;
  size?: number;
}) {
  return (
    <div
      className="rounded-full overflow-hidden flex-shrink-0 flex items-center justify-center font-bold relative"
      style={{
        width: size,
        height: size,
        background: "var(--deep)",
        fontSize: size * 0.35,
        color: "var(--text-primary)",
      }}
    >
      {src ? (
        <Image
          src={src}
          alt={name}
          fill
          className="object-cover"
          unoptimized
          sizes={`${size}px`}
        />
      ) : (
        <span>{(name || "?")[0].toUpperCase()}</span>
      )}
    </div>
  );
}

/* ── Subscribe / Like buttons ────────────────────────────────────────────────── */

function SubscribeBtn({ detail }: { detail: ContentDetail }) {
  const { subscribed, toggle, loading } = useSubscribe(
    detail.channelUserId,
    detail.isSubscribe === 1,
  );
  return (
    <button
      onClick={toggle}
      disabled={loading}
      className="flex items-center gap-1.5 px-4 py-2 rounded-full text-[11px] font-bold transition-all active:scale-95"
      style={{
        background: subscribed ? "var(--border)" : "var(--accent)",
        color: subscribed ? "#aaa" : "#fff",
        border: subscribed ? "1px solid var(--border)" : "none",
      }}
    >
      {subscribed ? (
        <Check size={11} strokeWidth={2.5} />
      ) : (
        <Users size={11} strokeWidth={2} />
      )}
      {subscribed ? "Subscribed" : "Subscribe"}
    </button>
  );
}

function LikeBtn({ detail }: { detail: ContentDetail }) {
  const {
    liked,
    disliked,
    totalLikes,
    totalDislikes,
    handleLike,
    handleDislike,
  } = useLikeDislike({
    contentId: detail.id,
    contentType: detail.contentType,
    initialReaction: detail.isUserLikeDislike,
    initialLikes: detail.totalLike,
    initialDislikes: detail.totalDislike,
  });
  return (
    <div
      className="flex items-center gap-0 rounded-full overflow-hidden"
      style={{ border: "1px solid var(--border)" }}
    >
      <button
        onClick={handleLike}
        className="flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-semibold transition-all active:scale-95"
        style={{
          background: liked
            ? "rgba(var(--accent-rgb),0.12)"
            : "var(--btn-ghost)",
          color: liked ? "var(--accent)" : "#aaa",
        }}
      >
        <ThumbsUp
          size={13}
          fill={liked ? "currentColor" : "none"}
          strokeWidth={1.8}
        />
        {totalLikes > 0 && <span>{totalLikes.toLocaleString()}</span>}
      </button>
      <div style={{ width: 1, background: "var(--border)", height: 20 }} />
      <button
        onClick={handleDislike}
        className="flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-semibold transition-all active:scale-95"
        style={{
          background: disliked ? "rgba(244,63,94,0.1)" : "var(--btn-ghost)",
          color: disliked ? "#f43f5e" : "#aaa",
        }}
      >
        <ThumbsDown
          size={13}
          fill={disliked ? "currentColor" : "none"}
          strokeWidth={1.8}
        />
        {totalDislikes > 0 && <span>{totalDislikes.toLocaleString()}</span>}
      </button>
    </div>
  );
}

/* ── Reel-style Like + Comment action bar ───────────────────────────────────── */

function ContentLikeCommentBar({ detail }: { detail: ContentDetail }) {
  const [commentOpen, setCommentOpen] = useState(false);
  const [likeAnim, setLikeAnim] = useState(false);
  const { share, copied } = useShare();

  const {
    liked,
    disliked,
    totalLikes,
    totalDislikes,
    handleLike,
    handleDislike,
  } = useLikeDislike({
    contentId: detail.id,
    contentType: detail.contentType,
    initialReaction: detail.isUserLikeDislike,
    initialLikes: detail.totalLike,
    initialDislikes: detail.totalDislike,
  });

  const onLike = () => {
    if (!liked) {
      setLikeAnim(true);
      setTimeout(() => setLikeAnim(false), 420);
    }
    handleLike();
  };

  return (
    <>
      <div className="flex items-center justify-center gap-6">
        {/* Like */}
        <button
          onClick={onLike}
          className="flex flex-col items-center gap-1.5 active:scale-90 transition-transform select-none"
          style={{ WebkitTapHighlightColor: "transparent" }}
        >
          <div
            className="w-13 h-13 rounded-full flex items-center justify-center"
            style={{
              width: 52,
              height: 52,
              background: liked
                ? "rgba(var(--accent-rgb),0.18)"
                : "var(--btn-ghost-hover)",
              border: `1.5px solid ${liked ? "rgba(var(--accent-rgb),0.45)" : "var(--border)"}`,
              boxShadow: liked
                ? "0 0 22px rgba(var(--accent-rgb),0.28)"
                : "none",
              transition: "all 0.25s cubic-bezier(0.34,1.5,0.64,1)",
            }}
          >
            <ThumbsUp
              size={22}
              fill={liked ? "var(--accent)" : "none"}
              color={liked ? "var(--accent)" : "#aaa"}
              strokeWidth={1.8}
              style={{
                transition: "transform 0.22s cubic-bezier(0.34,1.8,0.64,1)",
                transform: likeAnim ? "scale(1.4)" : "scale(1)",
              }}
            />
          </div>
          <span
            className="text-[11px] font-bold tabular-nums"
            style={{ color: liked ? "var(--accent)" : "#888" }}
          >
            {totalLikes > 0 ? totalLikes.toLocaleString() : "Like"}
          </span>
        </button>

        {/* Dislike */}
        <button
          onClick={handleDislike}
          className="flex flex-col items-center gap-1.5 active:scale-90 transition-transform select-none"
          style={{ WebkitTapHighlightColor: "transparent" }}
        >
          <div
            className="w-13 h-13 rounded-full flex items-center justify-center"
            style={{
              width: 52,
              height: 52,
              background: disliked
                ? "rgba(244,63,94,0.12)"
                : "var(--btn-ghost-hover)",
              border: `1.5px solid ${disliked ? "rgba(244,63,94,0.35)" : "var(--border)"}`,
              transition: "all 0.25s ease",
            }}
          >
            <ThumbsDown
              size={22}
              fill={disliked ? "#f43f5e" : "none"}
              color={disliked ? "#f43f5e" : "#aaa"}
              strokeWidth={1.8}
            />
          </div>
          <span
            className="text-[11px] font-bold tabular-nums"
            style={{ color: disliked ? "#f43f5e" : "#888" }}
          >
            {totalDislikes > 0 ? totalDislikes.toLocaleString() : "Dislike"}
          </span>
        </button>

        {/* Comment — always visible */}
        <button
          onClick={() => setCommentOpen(true)}
          className="flex flex-col items-center gap-1.5 active:scale-90 transition-transform select-none"
          style={{ WebkitTapHighlightColor: "transparent" }}
        >
          <div
            className="rounded-full flex items-center justify-center"
            style={{
              width: 52,
              height: 52,
              background: commentOpen
                ? "rgba(99,102,241,0.15)"
                : "var(--btn-ghost-hover)",
              border: `1.5px solid ${commentOpen ? "rgba(99,102,241,0.35)" : "var(--border)"}`,
              transition: "all 0.25s ease",
            }}
          >
            <MessageCircle
              size={22}
              color={commentOpen ? "#818cf8" : "#aaa"}
              fill={commentOpen ? "rgba(99,102,241,0.2)" : "none"}
              strokeWidth={1.8}
            />
          </div>
          <span
            className="text-[11px] font-bold tabular-nums"
            style={{ color: commentOpen ? "#818cf8" : "#888" }}
          >
            {detail.totalComment > 0
              ? detail.totalComment.toLocaleString()
              : "Comments"}
          </span>
        </button>

        {/* Share */}
        <button
          className="flex flex-col items-center gap-1.5 active:scale-90 transition-transform select-none"
          style={{ WebkitTapHighlightColor: "transparent" }}
          onClick={() =>
            share({
              title: detail.title,
              path: `/content/${detail.contentType}/${detail.id}`,
            })
          }
        >
          <div
            className="rounded-full flex items-center justify-center"
            style={{
              width: 52,
              height: 52,
              background: copied
                ? "rgba(var(--accent-rgb),0.14)"
                : "var(--btn-ghost-hover)",
              border: `1.5px solid ${copied ? "rgba(var(--accent-rgb),0.4)" : "var(--border)"}`,
            }}
          >
            <Share2
              size={22}
              color={copied ? "var(--accent)" : "#aaa"}
              strokeWidth={1.8}
            />
          </div>
          <span
            className="text-[11px] font-bold"
            style={{ color: copied ? "var(--accent)" : "#888" }}
          >
            {copied ? "Copied!" : "Share"}
          </span>
        </button>
      </div>

      {/* Comment bottom sheet */}
      {commentOpen && (
        <CommentSection
          mode="sheet"
          isOpen={commentOpen}
          onClose={() => setCommentOpen(false)}
          contentType={detail.contentType}
          contentId={detail.id}
          totalComments={detail.totalComment}
          canComment={true}
        />
      )}

      <style>{`
        @keyframes cd-heart-pop { 0%{transform:scale(1)} 40%{transform:scale(1.45)} 70%{transform:scale(0.9)} 100%{transform:scale(1)} }
      `}</style>
    </>
  );
}

/* ── Cover art ───────────────────────────────────────────────────────────────── */

function CoverArt({
  src,
  alt,
  size = 240,
  glow = true,
  priority = false,
}: {
  src: string;
  alt: string;
  size?: number;
  glow?: boolean;
  /** Pass true when this cover is the above-fold LCP image */
  priority?: boolean;
}) {
  return (
    <div
      className="relative flex-shrink-0"
      style={{ width: size, height: size }}
    >
      {glow && (
        <div
          className="absolute -inset-4 rounded-3xl pointer-events-none"
          style={{
            background:
              "radial-gradient(circle, rgba(var(--accent-rgb),0.15) 0%, transparent 70%)",
          }}
        />
      )}
      <div
        className="relative w-full h-full rounded-2xl overflow-hidden"
        style={{
          background: "var(--deep)",
          boxShadow: "0 16px 48px rgba(0,0,0,0.55)",
        }}
      >
        {src ? (
          <Image
            src={src}
            alt={alt}
            fill
            className="object-cover"
            unoptimized
            sizes={`${size}px`}
            priority={priority}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2 size={size * 0.3} color="var(--text-muted)" />
          </div>
        )}
      </div>
    </div>
  );
}

/* ── Stat pill ───────────────────────────────────────────────────────────────── */

function StatPill({
  icon: Icon,
  value,
  color = "#888",
}: {
  icon: React.ElementType;
  value: string | number;
  color?: string;
}) {
  return (
    <div className="flex items-center gap-1">
      <Icon size={11} color={color} strokeWidth={1.8} />
      <span className="text-[11px]" style={{ color }}>
        {value}
      </span>
    </div>
  );
}

/* ── Skeleton ────────────────────────────────────────────────────────────────── */

function DetailSkeleton() {
  return (
    <div className="animate-pulse px-4 py-6 md:px-8 flex flex-col gap-6  mx-auto">
      <div className="flex flex-col sm:flex-row gap-6">
        <div
          className="w-48 h-48 rounded-2xl flex-shrink-0"
          style={{ background: "var(--card)" }}
        />
        <div className="flex-1 space-y-3 pt-2">
          <div
            className="h-4 rounded-full"
            style={{ background: "var(--card)", width: "80%" }}
          />
          <div
            className="h-3 rounded-full"
            style={{ background: "var(--card)", width: "50%" }}
          />
          <div
            className="h-3 rounded-full"
            style={{ background: "var(--card)", width: "65%" }}
          />
          <div className="flex gap-2 mt-4">
            <div
              className="h-8 w-24 rounded-full"
              style={{ background: "var(--card)" }}
            />
            <div
              className="h-8 w-24 rounded-full"
              style={{ background: "var(--card)" }}
            />
          </div>
        </div>
      </div>
      {[1, 2, 3, 4].map((i) => (
        <div key={i} className="flex gap-3 items-center">
          <div
            className="w-14 h-14 rounded-xl flex-shrink-0"
            style={{ background: "var(--card)" }}
          />
          <div className="flex-1 space-y-2">
            <div
              className="h-3 rounded-full"
              style={{ background: "var(--card)", width: "70%" }}
            />
            <div
              className="h-2.5 rounded-full"
              style={{ background: "var(--card)", width: "45%" }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ── Podcast layout ──────────────────────────────────────────────────────────── */

function PodcastDetail({
  detail,
  episodes,
}: {
  detail: ContentDetail;
  episodes: Episode[];
}) {
  const dispatch = useAppDispatch();

  // Auto-play the first free episode as soon as the list loads
  useEffect(() => {
    if (episodes.length === 0) return;
    const queue = episodes.map((e) => episodeToMusicItem(e, detail));
    const firstFree =
      queue.find((_, i) => episodes[i]?.isBuy !== 1) ?? queue[0];
    if (firstFree) {
      dispatch(setQueue(queue));
      dispatch(setTrack(firstFree));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [episodes]);

  const playEpisode = (ep: Episode, index: number) => {
    const queue = episodes.map((e) => episodeToMusicItem(e, detail));
    const track = queue[index];
    if (track) {
      dispatch(setQueue(queue));
      dispatch(setTrack(track));
    }
  };

  return (
    <div className="flex flex-col gap-6  mx-auto px-4 py-6 md:px-8 pb-28">
      {/* Hero */}
      <div
        className="flex flex-col sm:flex-row gap-6 p-5 rounded-2xl"
        style={{
          background:
            "linear-gradient(135deg, var(--card) 0%, rgba(22,33,62,0.5) 100%)",
          border: "1px solid var(--border)",
          animation: "cd-rise 0.45s ease both",
        }}
      >
        <CoverArt
          src={detail.thumbnail}
          alt={detail.title}
          size={180}
          priority
        />

        <div className="flex flex-col gap-3 flex-1 min-w-0">
          {/* Eyebrow */}
          <div className="flex items-center gap-2">
            <Headphones size={12} color="var(--accent)" strokeWidth={2} />
            <span
              className="text-[10px] font-bold uppercase tracking-widest"
              style={{ color: "var(--accent)" }}
            >
              Podcast · {episodes.length} Episodes
            </span>
          </div>

          <h1
            className="text-xl font-black leading-tight"
            style={{ letterSpacing: "-0.02em", color: "var(--text-primary)" }}
          >
            {detail.title}
          </h1>

          {/* Channel row */}
          <div className="flex items-center gap-2.5">
            <ChannelAvatar
              src={detail.channelImage}
              name={detail.channelName}
              size={28}
            />
            <span
              className="text-[12px] font-semibold"
              style={{ color: "var(--text-primary)" }}
            >
              {detail.channelName}
            </span>
            <span className="text-[11px]" style={{ color: "#555" }}>
              {detail.totalSubscribers.toLocaleString()} subscribers
            </span>
          </div>

          {/* Stats */}
          <div className="flex items-center gap-4 flex-wrap">
            <StatPill icon={Eye} value={detail.views} />
            <StatPill icon={Heart} value={detail.totalLike.toLocaleString()} />
            <StatPill icon={MessageCircle} value={detail.totalComment} />
            <span className="text-[10px]" style={{ color: "#555" }}>
              {detail.languageName} · {detail.categoryName}
            </span>
          </div>

          {/* Description */}
          {detail.description && (
            <p
              className="text-[11px] leading-relaxed line-clamp-3"
              style={{ color: "#888" }}
            >
              {detail.description}
            </p>
          )}

          {/* Subscribe */}
          <SubscribeBtn detail={detail} />
        </div>
      </div>

      {/* Reel-style Like + Comment bar */}
      <div style={{ animation: "cd-rise 0.5s ease both 0.08s" }}>
        <ContentLikeCommentBar detail={detail} />
      </div>

      {/* Episodes */}
      <div style={{ animation: "cd-rise 0.5s ease both 0.12s" }}>
        <h2
          className="text-[11px] font-bold uppercase tracking-widest mb-3"
          style={{ color: "#555" }}
        >
          Episodes — {episodes.length}
        </h2>
        <div className="flex flex-col gap-1">
          {episodes.map((ep, i) => (
            <EpisodeRow
              key={ep.id}
              ep={ep}
              index={i}
              total={episodes.length}
              onPlay={() => playEpisode(ep, i)}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

function EpisodeRow({
  ep,
  index,
  total,
  onPlay,
}: {
  ep: Episode;
  index: number;
  total: number;
  onPlay: () => void;
}) {
  const [hovered, setHovered] = useState(false);
  const num = index + 1;

  return (
    <div
      className="group flex items-center gap-4 px-4 py-3 rounded-xl cursor-pointer transition-all duration-150"
      style={{
        background: hovered ? "var(--card)" : "transparent",
        border: `1px solid ${hovered ? "var(--border)" : "transparent"}`,
        animation: "cd-row-in 0.4s ease both",
        animationDelay: `${Math.min(index * 50, 400)}ms`,
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={onPlay}
    >
      {/* Number / play toggle */}
      <div
        className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 transition-all"
        style={{
          background: hovered ? "var(--accent)" : "var(--border-soft)",
        }}
      >
        {hovered ? (
          <Play
            size={13}
            fill="#fff"
            color="#fff"
            strokeWidth={0}
            style={{ marginLeft: 1 }}
          />
        ) : (
          <span className="text-[11px] font-bold" style={{ color: "#888" }}>
            {num}
          </span>
        )}
      </div>

      {/* Thumbnail */}
      <div
        className="relative w-14 h-14 rounded-xl overflow-hidden flex-shrink-0"
        style={{ background: "var(--deep)" }}
      >
        {ep.thumbnail && (
          <Image
            src={ep.thumbnail}
            alt={ep.name}
            fill
            className="object-cover"
            unoptimized
            sizes="56px"
          />
        )}
        {ep.isBuy === 1 && (
          <div className="absolute inset-0 bg-black/60 flex items-center justify-center">
            <Lock size={12} color="#f59e0b" />
          </div>
        )}
      </div>

      {/* Info */}
      <div className="flex-1 min-w-0">
        <p
          className="text-[12px] font-semibold truncate"
          style={{ color: "var(--text-primary)" }}
        >
          {ep.name}
        </p>
        <p
          className="text-[10px] mt-0.5 line-clamp-1"
          style={{ color: "#666" }}
        >
          {ep.description}
        </p>
        <div className="flex items-center gap-3 mt-1">
          {ep.views > 0 && <StatPill icon={Eye} value={ep.views} />}
          {ep.isDownload === 1 && (
            <Download size={10} color="#888" strokeWidth={1.8} />
          )}
        </div>
      </div>

      <ChevronRight
        size={14}
        color={hovered ? "var(--accent)" : "#444"}
        strokeWidth={2}
      />
    </div>
  );
}

/* ── Music layout ────────────────────────────────────────────────────────────── */

function MusicDetail({
  detail,
  related,
}: {
  detail: ContentDetail;
  related: RelatedMusic[];
}) {
  const dispatch = useAppDispatch();

  const play = () => {
    const allItems = [detail, ...related].map(toMusicItem);
    dispatch(setQueue(allItems));
    dispatch(setTrack(toMusicItem(detail)));
  };

  return (
    <div className="flex flex-col gap-8  mx-auto px-4 py-6 md:px-8 pb-28">
      {/* Hero */}
      <div
        className="flex flex-col items-center text-center gap-5 pt-4"
        style={{ animation: "cd-rise 0.45s ease both" }}
      >
        <CoverArt
          src={detail.thumbnail}
          alt={detail.title}
          size={220}
          glow
          priority
        />

        <div className="flex flex-col gap-2 w-full">
          <h1
            className="text-2xl font-black leading-tight"
            style={{ letterSpacing: "-0.03em", color: "var(--text-primary)" }}
          >
            {detail.title}
          </h1>
          <div className="flex items-center justify-center gap-2">
            <ChannelAvatar
              src={detail.channelImage}
              name={detail.channelName}
              size={22}
            />
            <span
              className="text-[13px] font-semibold"
              style={{ color: "#ccc" }}
            >
              {detail.channelName}
            </span>
          </div>

          <div className="flex items-center justify-center gap-4 mt-1">
            <StatPill icon={Eye} value={detail.views} />
            <StatPill icon={Heart} value={detail.totalLike.toLocaleString()} />
            <span className="text-[10px]" style={{ color: "#555" }}>
              {detail.duration || ""}
            </span>
          </div>
        </div>

        {/* Play button */}
        <button
          onClick={play}
          className="flex items-center gap-3 px-8 py-3 rounded-full text-[13px] font-black text-[#ffffff] transition-all active:scale-95 hover:brightness-110"
          style={{
            background: "var(--accent)",
            boxShadow: "0 8px 28px rgba(var(--accent-rgb),0.35)",
          }}
        >
          <Play size={16} fill="#fff" color="#fff" strokeWidth={0} />
          Play Now
        </button>

        {/* Subscribe row */}
        <SubscribeBtn detail={detail} />
      </div>

      {/* Reel-style Like + Comment bar */}
      <div style={{ animation: "cd-rise 0.48s ease both 0.08s" }}>
        <ContentLikeCommentBar detail={detail} />
      </div>

      {/* Description */}
      {detail.description && (
        <div
          className="rounded-2xl p-4"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border-soft)",
            animation: "cd-rise 0.5s ease both 0.1s",
          }}
        >
          <p
            className="text-[11px] font-bold uppercase tracking-widest mb-2"
            style={{ color: "#555" }}
          >
            About
          </p>
          <p className="text-[12px] leading-relaxed" style={{ color: "#aaa" }}>
            {detail.description}
          </p>
        </div>
      )}

      {/* Related */}
      {related.length > 0 && (
        <div style={{ animation: "cd-rise 0.55s ease both 0.15s" }}>
          <h2
            className="text-[11px] font-bold uppercase tracking-widest mb-3"
            style={{ color: "#555" }}
          >
            Related Music
          </h2>
          <div className="flex flex-col gap-1">
            {related.map((r, i) => (
              <RelatedMusicRow
                key={r.id}
                item={r}
                index={i}
                onPlay={() => {
                  const queue = [detail, ...related].map(toMusicItem);
                  dispatch(setQueue(queue));
                  dispatch(setTrack(toMusicItem(r)));
                }}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function RelatedMusicRow({
  item,
  index,
  onPlay,
}: {
  item: RelatedMusic;
  index: number;
  onPlay: () => void;
}) {
  const [hovered, setHovered] = useState(false);
  return (
    <div
      className="flex items-center gap-3 px-3 py-2.5 rounded-xl cursor-pointer transition-all"
      style={{
        background: hovered ? "var(--card)" : "transparent",
        animation: "cd-row-in 0.4s ease both",
        animationDelay: `${Math.min(index * 45, 400)}ms`,
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={onPlay}
    >
      <div
        className="relative w-11 h-11 rounded-xl overflow-hidden flex-shrink-0"
        style={{ background: "var(--deep)" }}
      >
        {item.thumbnail && (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover"
            unoptimized
            sizes="44px"
          />
        )}
        {hovered && (
          <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
            <Play size={13} fill="#fff" color="#fff" strokeWidth={0} />
          </div>
        )}
      </div>
      <div className="flex-1 min-w-0">
        <p
          className="text-[12px] font-semibold truncate"
          style={{ color: "var(--text-primary)" }}
        >
          {item.title}
        </p>
        <p className="text-[10px] truncate" style={{ color: "#888" }}>
          {item.channelName}
        </p>
      </div>
      <div className="text-right flex-shrink-0">
        <p className="text-[10px]" style={{ color: "#666" }}>
          {item.duration}
        </p>
        <p className="text-[10px]" style={{ color: "#555" }}>
          {item.views}
        </p>
      </div>
    </div>
  );
}

/* ── Radio layout ────────────────────────────────────────────────────────────── */

function RadioDetail({ detail }: { detail: ContentDetail }) {
  const dispatch = useAppDispatch();

  const play = () => {
    dispatch(setTrack(toMusicItem(detail)));
  };

  return (
    <div className="flex flex-col gap-6  mx-auto px-4 py-8 pb-28">
      <div
        className="flex flex-col items-center text-center gap-5 p-8 rounded-3xl"
        style={{
          background:
            "linear-gradient(135deg, var(--card) 0%, var(--deep) 100%)",
          border: "1px solid var(--border)",
          animation: "cd-rise 0.45s ease both",
        }}
      >
        {/* Animated ring */}
        <div className="relative">
          <div
            className="w-52 h-52 rounded-full flex items-center justify-center"
            style={{
              background:
                "linear-gradient(135deg, rgba(var(--accent-rgb),0.15), rgba(15,52,96,0.5))",
              border: "2px solid rgba(var(--accent-rgb),0.2)",
              boxShadow: "0 0 60px rgba(var(--accent-rgb),0.1)",
            }}
          >
            <div
              className="w-44 h-44 rounded-full overflow-hidden relative"
              style={{ background: "var(--deep)" }}
            >
              {detail.thumbnail && (
                <Image
                  src={detail.thumbnail}
                  alt={detail.title}
                  fill
                  className="object-cover"
                  unoptimized
                  sizes="176px"
                />
              )}
            </div>
          </div>
          <div
            className="absolute -bottom-1 -right-1 w-10 h-10 rounded-full flex items-center justify-center"
            style={{
              background: "var(--accent)",
              boxShadow: "0 4px 16px rgba(var(--accent-rgb),0.4)",
            }}
          >
            <RadioIcon size={16} color="#fff" strokeWidth={1.8} />
          </div>
        </div>

        <div>
          <div className="flex items-center justify-center gap-1.5 mb-2">
            <span
              className="text-[9px] font-black px-2 py-0.5 rounded uppercase tracking-widest"
              style={{
                background: "rgba(var(--accent-rgb),0.12)",
                color: "var(--accent)",
              }}
            >
              LIVE RADIO
            </span>
          </div>
          <h1
            className="text-xl font-black"
            style={{ letterSpacing: "-0.02em", color: "var(--text-primary)" }}
          >
            {detail.title}
          </h1>
          <div className="flex items-center justify-center gap-2 mt-2">
            <ChannelAvatar
              src={detail.channelImage}
              name={detail.channelName}
              size={22}
            />
            <span className="text-[12px]" style={{ color: "#aaa" }}>
              {detail.channelName}
            </span>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <StatPill icon={Eye} value={detail.views} />
          <span className="text-[10px]" style={{ color: "#555" }}>
            {detail.languageName}
          </span>
          <span className="text-[10px]" style={{ color: "#555" }}>
            {detail.categoryName}
          </span>
        </div>

        <button
          onClick={play}
          className="flex items-center gap-2 px-8 py-3 rounded-full text-[13px] font-black text-[#ffffff] transition-all active:scale-95"
          style={{
            background: "var(--accent)",
            boxShadow: "0 8px 28px rgba(var(--accent-rgb),0.35)",
          }}
        >
          <RadioIcon size={16} strokeWidth={2} />
          Listen Live
        </button>

        <SubscribeBtn detail={detail} />

        {detail.description && (
          <p
            className="text-[11px] leading-relaxed text-center"
            style={{ color: "#888" }}
          >
            {detail.description}
          </p>
        )}
      </div>

      {/* Reel-style Like + Comment bar */}
      <div style={{ animation: "cd-rise 0.5s ease both 0.08s" }}>
        <ContentLikeCommentBar detail={detail} />
      </div>
    </div>
  );
}

/* ── Main page ───────────────────────────────────────────────────────────────── */

export default function ContentDetailPage({
  contentType,
  contentId,
}: {
  contentType: number;
  contentId: string;
}) {
  const router = useRouter();
  const [detail, setDetail] = useState<ContentDetail | null>(null);
  const [episodes, setEpisodes] = useState<Episode[]>([]);
  const [related, setRelated] = useState<RelatedMusic[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const currentTime = useAppSelector((s) => s.player.currentTime);
  const currentTimeRef = useRef(0);
  useEffect(() => { currentTimeRef.current = currentTime; }, [currentTime]);

  useAddView(contentType, contentId);
  useAddToHistory(contentType, contentId, undefined, 5000, () => currentTimeRef.current);

  useEffect(() => {
    if (!contentId) return;
    setLoading(true);
    contentDetailService
      .getDetail(contentType, contentId)
      .then(async (d) => {
        if (!d) {
          setError("Content not found.");
          setLoading(false);
          return;
        }
        setDetail(d);

        if (contentType === 4) {
          const eps = await contentDetailService
            .getEpisodes(contentId)
            .catch(() => []);
          setEpisodes(eps);
        } else if (contentType === 2) {
          const rel = await contentDetailService
            .getRelatedMusic(contentId)
            .catch(() => []);
          setRelated(rel);
        }
      })
      .catch(() => setError("Failed to load content."))
      .finally(() => setLoading(false));
  }, [contentType, contentId]);

  return (
    <div className="min-h-screen" style={{ background: "var(--bg)" }}>
      {/* Back button */}
      <div
        className="sticky top-0 z-10 flex items-center gap-3 px-4 py-3"
        style={{
          background: "var(--bg)",
          borderBottom: "1px solid var(--border-soft)",
        }}
      >
        <button
          onClick={() => router.back()}
          className="w-8 h-8 rounded-full flex items-center justify-center transition-all hover:brightness-125"
          style={{ background: "var(--btn-ghost)" }}
        >
          <ArrowLeft size={15} color="var(--text-primary)" strokeWidth={2} />
        </button>
        <span
          className="text-sm font-bold truncate"
          style={{ color: "var(--text-primary)" }}
        >
          {loading ? "Loading…" : detail?.title || "Content"}
        </span>
      </div>

      {loading && <DetailSkeleton />}

      {!loading && error && (
        <div className="flex flex-col items-center justify-center py-24 gap-3">
          <Music2 size={32} color="#555" strokeWidth={1.2} />
          <p className="text-sm" style={{ color: "#888" }}>
            {error}
          </p>
          <button
            onClick={() => router.back()}
            className="text-xs font-semibold px-4 py-2 rounded-full text-[#ffffff] active:scale-95"
            style={{ background: "var(--accent)" }}
          >
            Go back
          </button>
        </div>
      )}

      {!loading && detail && !error && (
        <>
          {contentType === 4 && (
            <PodcastDetail detail={detail} episodes={episodes} />
          )}
          {contentType === 2 && (
            <MusicDetail detail={detail} related={related} />
          )}
          {contentType === 6 && <RadioDetail detail={detail} />}
          {![2, 4, 6].includes(contentType) && (
            <MusicDetail detail={detail} related={related} />
          )}
        </>
      )}
    </div>
  );
}
