"use client";

import {
  createContext,
  useContext,
  useEffect,
  useState,
  useRef,
  useCallback,
} from "react";
import Image from "next/image";
import {
  Play,
  Download,
  MoreHorizontal,
  Music2,
  Headphones,
  Disc3,
  ChevronLeft,
  ChevronRight,
  ListPlus,
  Heart,
} from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchMusicSections } from "@/store/slices/musicSectionSlice";
import { setTrack, setQueue } from "@/store/slices/playerSlice";
import { MusicItem, MusicSection } from "@/services/musicSectionService";
import { useRouter } from "next/navigation";
import { usePauseOnInactivity } from "@/hooks/usePauseOnInactivity";

const SectionContext = createContext<MusicItem[]>([]);

/* ── usePlayTrack ────────────────────────────────────────────────────────────── */

function usePlayTrack() {
  const dispatch = useAppDispatch();
  const sectionItems = useContext(SectionContext);
  return (item: MusicItem) => {
    dispatch(setTrack(item));
    if (sectionItems.length > 0) dispatch(setQueue(sectionItems));
  };
}

/* ── useNavigateToDetail ─────────────────────────────────────────────────────── */

function useNavigateToDetail() {
  const router = useRouter();
  return (item: MusicItem) => {
    router.push(`/content/${item.contentType}/${item.id}`);
  };
}

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

function SectionSkeleton() {
  return (
    <div className="mb-10">
      <div className="flex items-center justify-between mb-4">
        <div
          className="h-4 w-36 rounded-full animate-pulse"
          style={{ background: "var(--card)" }}
        />
        <div
          className="h-3 w-12 rounded-full animate-pulse"
          style={{ background: "var(--card)" }}
        />
      </div>
      <div className="flex gap-3 overflow-hidden">
        {Array.from({ length: 5 }).map((_, i) => (
          <div
            key={i}
            className="shrink-0 flex flex-col gap-2 animate-pulse"
            style={{ width: 140 }}
          >
            <div
              className="rounded-xl"
              style={{ width: 140, height: 140, background: "var(--card)" }}
            />
            <div
              className="h-3 rounded-full"
              style={{ background: "var(--card)", width: "80%" }}
            />
            <div
              className="h-2.5 rounded-full"
              style={{ background: "var(--card)", width: "55%" }}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── Section header ──────────────────────────────────────────────────────── */

function SectionHead({
  title,
  subtitle,
  viewAll,
  onSeeAll,
}: {
  title: string;
  subtitle?: string;
  viewAll: boolean;
  onSeeAll?: () => void;
}) {
  return (
    <div className="flex items-start justify-between mb-4">
      <div>
        <h2
          className="text-sm font-bold tracking-tight"
          style={{ color: "var(--text-primary)" }}
        >
          {title}
        </h2>
        {subtitle && (
          <p
            className="text-[11px] mt-0.5 line-clamp-1"
            style={{ color: "#777" }}
          >
            {subtitle}
          </p>
        )}
      </div>
      {viewAll && (
        <button
          onClick={onSeeAll}
          className="text-[11px] font-semibold shrink-0 ml-4 px-3 py-1 rounded-full transition-all active:scale-95 hover:brightness-110"
          style={{
            color: "var(--accent)",
            background: "rgba(var(--accent-rgb),0.1)",
            border: "1px solid rgba(var(--accent-rgb),0.2)",
          }}
        >
          See all
        </button>
      )}
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 1 — list_view  (numbered track list, vertical)
═══════════════════════════════════════════════════════════════════════════ */

function EqualizerBars() {
  return (
    <span className="flex items-end gap-[2px] h-3.5">
      {[3, 5, 4, 6, 3].map((h, i) => (
        <span
          key={i}
          className="w-[2px] rounded-full"
          style={{
            background: "var(--accent)",
            height: `${h * 2}px`,
            animation: `eq-bounce ${0.4 + i * 0.08}s ease-in-out infinite alternate`,
          }}
        />
      ))}
      <style jsx>{`
        @keyframes eq-bounce {
          from {
            transform: scaleY(0.3);
          }
          to {
            transform: scaleY(1);
          }
        }
      `}</style>
    </span>
  );
}

function ListRow({ item, index }: { item: MusicItem; index: number }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();
  const currentId = useAppSelector((s) => s.player.currentTrack?.id ?? null);
  const isPlaying = useAppSelector((s) => s.player.isPlaying);
  const isActive = currentId === item.id;

  return (
    <div
      className="flex items-center gap-3 py-2.5 px-3 rounded-xl cursor-pointer group transition-all duration-150"
      style={{
        background: isActive ? "rgba(var(--accent-rgb),0.08)" : "transparent",
        borderLeft: isActive
          ? "2px solid var(--accent)"
          : "2px solid transparent",
      }}
      onClick={() => navigate(item)}
      onMouseEnter={(e) => {
        if (!isActive)
          (e.currentTarget as HTMLElement).style.background = "var(--card)";
      }}
      onMouseLeave={(e) => {
        if (!isActive)
          (e.currentTarget as HTMLElement).style.background = "transparent";
      }}
    >
      {/* Index / equalizer / play icon */}
      <div className="w-7 flex items-center justify-center shrink-0">
        {isActive && isPlaying ? (
          <EqualizerBars />
        ) : (
          <>
            <span
              className="text-xs font-semibold group-hover:hidden"
              style={{ color: isActive ? "var(--accent)" : "#555" }}
            >
              {String(index + 1).padStart(2, "0")}
            </span>
            <div
              className="hidden group-hover:flex w-6 h-6 rounded-full items-center justify-center"
              style={{ background: "var(--accent)" }}
              onClick={(e) => {
                e.stopPropagation();
                play(item);
              }}
            >
              <Play size={10} fill="white" strokeWidth={0} className="ml-px" />
            </div>
          </>
        )}
      </div>

      {/* Thumbnail */}
      <div
        className="relative w-10 h-10 rounded-lg overflow-hidden shrink-0"
        style={{
          background: "var(--deep)",
          boxShadow: isActive ? "0 0 0 1.5px var(--accent)" : "none",
        }}
      >
        {item.thumbnail ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover"
            unoptimized
            sizes="40px"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2
              size={16}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.5}
            />
          </div>
        )}
      </div>

      {/* Meta */}
      <div className="flex-1 min-w-0">
        <p
          className="text-xs font-semibold truncate"
          style={{ color: isActive ? "var(--accent)" : "var(--text-muted)" }}
        >
          {item.title}
        </p>
        <p className="text-[10px] truncate mt-0.5" style={{ color: "#555" }}>
          {item.channelName || item.language}
        </p>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-2 shrink-0">
        {item.isDownload && (
          <button
            className="opacity-0 group-hover:opacity-100 transition-opacity p-1"
            onClick={(e) => e.stopPropagation()}
          >
            <Download size={13} color="#888" strokeWidth={1.6} />
          </button>
        )}
        <span className="text-[10px] tabular-nums" style={{ color: "#555" }}>
          {item.duration}
        </span>
        <button
          className="opacity-0 group-hover:opacity-100 transition-opacity p-1"
          onClick={(e) => e.stopPropagation()}
        >
          <MoreHorizontal size={13} color="#888" strokeWidth={1.6} />
        </button>
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 2 — portrait  (3:4 cards, horizontal scroll)
═══════════════════════════════════════════════════════════════════════════ */

function PortraitCard({ item }: { item: MusicItem }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();
  const W = 120,
    H = 162;

  return (
    <button
      className="shrink-0 flex flex-col gap-2 text-left group"
      style={{ width: W }}
      onClick={() => navigate(item)}
    >
      <div
        className="relative overflow-hidden rounded-xl"
        style={{ width: W, height: H, background: "var(--deep)" }}
      >
        {item.thumbnail ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-105"
            unoptimized
            sizes={`${W}px`}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2
              size={26}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.5}
            />
          </div>
        )}
        {/* Bottom gradient */}
        <div
          className="absolute inset-x-0 bottom-0 h-16 pointer-events-none"
          style={{
            background:
              "linear-gradient(to top, rgba(0,0,0,0.75) 0%, transparent 100%)",
          }}
        />
        {/* Play button */}
        <div className="absolute inset-0 flex items-center justify-center">
          <div
            className="opacity-0 group-hover:opacity-100 transition-all duration-200 w-9 h-9 rounded-full flex items-center justify-center"
            style={{
              background: "var(--accent)",
              boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.55)",
              transform: "scale(0.8)",
            }}
            onMouseEnter={(e) =>
              ((e.currentTarget as HTMLElement).style.transform = "scale(1)")
            }
            onMouseLeave={(e) =>
              ((e.currentTarget as HTMLElement).style.transform = "scale(0.8)")
            }
            onClick={(e) => {
              e.stopPropagation();
              play(item);
            }}
          >
            <Play size={14} fill="white" strokeWidth={0} className="ml-0.5" />
          </div>
        </div>
      </div>
      <p
        className="text-[11px] font-semibold leading-tight

         line-clamp-2 px-0.5"
        style={{ color: "var(--text-primary)" }}
      >
        {item.title}
      </p>
      <p className="text-[10px] line-clamp-1 px-0.5" style={{ color: "#666" }}>
        {item.channelName || item.language}
      </p>
    </button>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 3 — playlist  (2×2 collage card, horizontal scroll)
═══════════════════════════════════════════════════════════════════════════ */

function PlaylistCard({ item }: { item: MusicItem }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();
  const imgs = (item.playlistImages || []).slice(0, 4);
  const SIZE = 140;

  return (
    <button
      className="shrink-0 flex flex-col gap-2 text-left group"
      style={{ width: SIZE }}
      onClick={() => navigate(item)}
    >
      <div
        className="relative overflow-hidden rounded-xl"
        style={{ width: SIZE, height: SIZE, background: "var(--deep)" }}
      >
        {imgs.length >= 4 ? (
          <div className="grid grid-cols-2 w-full h-full gap-px">
            {imgs.map((src, i) => (
              <div key={i} className="relative overflow-hidden">
                <Image
                  src={src}
                  alt=""
                  fill
                  className="object-cover"
                  unoptimized
                  sizes="70px"
                />
              </div>
            ))}
          </div>
        ) : imgs.length >= 1 ? (
          <Image
            src={imgs[0]}
            alt={item.title}
            fill
            className="object-cover"
            unoptimized
            sizes={`${SIZE}px`}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center flex-col gap-2">
            <Disc3
              size={28}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.5}
            />
          </div>
        )}

        {/* Overlay */}
        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-200 flex items-center justify-center">
          <div
            className="opacity-0 group-hover:opacity-100 transition-all duration-200 w-10 h-10 rounded-full flex items-center justify-center"
            style={{
              background: "var(--accent)",
              boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.55)",
            }}
            onClick={(e) => {
              e.stopPropagation();
              play(item);
            }}
          >
            <Play size={16} fill="white" strokeWidth={0} className="ml-0.5" />
          </div>
        </div>

        {/* Track count badge */}
        {item.totalEpisodes ? (
          <div
            className="absolute bottom-2 right-2 text-[9px] font-bold px-1.5 py-0.5 rounded-md"
            style={{ background: "rgba(0,0,0,0.7)", color: "white" }}
          >
            {item.totalEpisodes} tracks
          </div>
        ) : null}
      </div>
      <p
        className="text-[11px] font-semibold leading-tight
         line-clamp-1"
        style={{ color: "var(--text-primary)" }}
      >
        {item.title}
      </p>
      <p className="text-[10px] line-clamp-1" style={{ color: "#666" }}>
        {item.channelName}
      </p>
    </button>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 4 — square  (1:1 album art cards, horizontal scroll)
═══════════════════════════════════════════════════════════════════════════ */

function SquareCard({ item }: { item: MusicItem }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();
  const SIZE = 140;

  return (
    <button
      className="shrink-0 flex flex-col gap-2 text-left group"
      style={{ width: SIZE }}
      onClick={() => navigate(item)}
    >
      <div
        className="relative overflow-hidden rounded-xl"
        style={{ width: SIZE, height: SIZE, background: "var(--deep)" }}
      >
        {item.thumbnail ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-105"
            unoptimized
            sizes={`${SIZE}px`}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2
              size={28}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.5}
            />
          </div>
        )}
        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/35 transition-colors duration-200 flex items-center justify-center">
          <div
            className="opacity-0 group-hover:opacity-100 transition-all duration-200 w-10 h-10 rounded-full flex items-center justify-center"
            style={{
              background: "var(--accent)",
              boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.5)",
            }}
            onClick={(e) => {
              e.stopPropagation();
              play(item);
            }}
          >
            <Play size={16} fill="white" strokeWidth={0} className="ml-0.5" />
          </div>
        </div>
      </div>
      <p
        className="text-[11px] font-semibold leading-tight
         line-clamp-2"
        style={{ color: "var(--text-primary)" }}
      >
        {item.langName || item.title}
      </p>
      <p className="text-[10px] line-clamp-1" style={{ color: "#666" }}>
        {item.channelName || item.language}
      </p>
    </button>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 5 — landscape  (16:9 cards, horizontal scroll)
═══════════════════════════════════════════════════════════════════════════ */

const DETAIL_ONLY_TYPES = new Set([4, 6]); // podcast, radio — no direct play

function LandscapeCard({ item }: { item: MusicItem }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();
  const W = 230,
    H = 130;
  const detailOnly = DETAIL_ONLY_TYPES.has(item.contentType);

  return (
    <button
      className="shrink-0 flex flex-col gap-2 text-left group"
      style={{ width: W }}
      onClick={() => navigate(item)}
    >
      <div
        className="relative overflow-hidden rounded-xl"
        style={{ width: W, height: H, background: "var(--deep)" }}
      >
        {item.landscapeImg || item.thumbnail ? (
          <Image
            src={item.landscapeImg || item.thumbnail}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-105"
            unoptimized
            sizes={`${W}px`}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2
              size={28}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.5}
            />
          </div>
        )}
        <div
          className="absolute inset-x-0 bottom-0 h-20 pointer-events-none"
          style={{
            background:
              "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 100%)",
          }}
        />

        {/* Duration badge */}
        {item.duration && (
          <div
            className="absolute bottom-2 right-2 text-[9px] font-semibold px-1.5 py-0.5 rounded"
            style={{ background: "rgba(0,0,0,0.75)", color: "#ddd" }}
          >
            {item.duration}
          </div>
        )}

        {/* Play button — only for non-podcast, non-radio content */}
        {!detailOnly && (
          <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
            <div
              className="w-10 h-10 rounded-full flex items-center justify-center"
              style={{
                background: "var(--accent)",
                boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.55)",
              }}
              onClick={(e) => {
                e.stopPropagation();
                play(item);
              }}
            >
              <Play size={16} fill="white" strokeWidth={0} className="ml-0.5" />
            </div>
          </div>
        )}
      </div>
      <p
        className="text-[11px] font-semibold leading-tight
         line-clamp-2"
        style={{ color: "var(--text-primary)" }}
      >
        {item.title}
      </p>
      <p className="text-[10px] line-clamp-1" style={{ color: "#666" }}>
        {item.channelName}
      </p>
    </button>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 6 — round  (circular artist/radio cards, horizontal scroll)
═══════════════════════════════════════════════════════════════════════════ */

function RoundCard({ item }: { item: MusicItem }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();

  return (
    <button
      className="shrink-0 flex flex-col items-center gap-2.5 text-center group"
      style={{ width: 96 }}
      onClick={() => navigate(item)}
    >
      <div className="relative">
        {/* Outer glow ring on hover */}
        <div
          className="absolute inset-0 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-300 -m-[3px]"
          style={{
            background:
              "conic-gradient(var(--accent), transparent, var(--accent))",
            padding: "2px",
            borderRadius: "50%",
          }}
        />
        <div
          className="relative w-[76px] h-[76px] rounded-full overflow-hidden"
          style={{
            background: "var(--deep)",
            border: "2px solid var(--border)",
          }}
        >
          {item.thumbnail ? (
            <Image
              src={item.thumbnail}
              alt={item.title}
              fill
              className="object-cover transition-transform duration-300 group-hover:scale-110"
              unoptimized
              sizes="76px"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <Music2
                size={22}
                style={{ color: "var(--accent)" }}
                strokeWidth={1.5}
              />
            </div>
          )}
          <div
            className="absolute inset-0 rounded-full bg-black/0 group-hover:bg-black/35 transition-colors flex items-center justify-center"
            onClick={(e) => {
              e.stopPropagation();
              play(item);
            }}
          >
            <Play
              size={18}
              fill="white"
              strokeWidth={0}
              className="opacity-0 group-hover:opacity-100 transition-opacity ml-0.5"
            />
          </div>
        </div>
      </div>
      <p
        className="text-[11px] font-semibold leading-tight
         line-clamp-2 w-full"
        style={{ color: "var(--text-primary)" }}
      >
        {item.title}
      </p>
      {item.channelName && (
        <p className="text-[10px] line-clamp-1" style={{ color: "#666" }}>
          {item.channelName}
        </p>
      )}
    </button>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 7 — banner_view  (premium OTT hero carousel, full-width)
═══════════════════════════════════════════════════════════════════════════ */

const BANNER_AUTO_MS = 5500;

function BannerCarousel({ items }: { items: MusicItem[] }) {
  const play = usePlayTrack();
  const navigate = useNavigateToDetail();

  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const n = items.length;

  /* Pause carousel when user is inactive for 10 minutes */
  usePauseOnInactivity(setPaused);

  /* Auto-advance */
  useEffect(() => {
    if (n <= 1 || paused) return;
    const t = setTimeout(() => setIdx((p) => (p + 1) % n), BANNER_AUTO_MS);
    return () => clearTimeout(t);
  }, [idx, paused, n]);

  if (n === 0) return null;

  const cur = items[idx]!;
  const img = cur.landscapeImg || cur.thumbnail;

  return (
    <div
      style={{ width: "100%", background: "var(--bg)" }}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onClick={(e) => {
        e.stopPropagation();
        navigate(cur);
      }}
    >
      {/* ── Filmstrip ── */}
      <div style={{ width: "100%", overflow: "hidden" }}>
        <div
          style={{
            display: "flex",
            width: `${n * 100}%`,
            transform: `translateX(-${(idx / n) * 100}%)`,
            transition: "transform 0.55s cubic-bezier(0.4, 0, 0.2, 1)",
          }}
        >
          {items.map((item) => {
            const src = item.landscapeImg || item.thumbnail;
            return (
              <div
                key={item.id}
                style={{
                  width: `${100 / n}%`,
                  flexShrink: 0,
                  position: "relative",
                  height: "clamp(240px, 36vw, 420px)",
                  overflow: "hidden",
                  cursor: "pointer",
                }}
                onClick={() => navigate(item)}
              >
                {/* Background image — regular img, no fill tricks */}
                {src && (
                  <img
                    src={src}
                    alt={item.title}
                    style={{
                      position: "absolute",
                      top: 0,
                      left: 0,
                      width: "100%",
                      height: "100%",
                      objectFit: "cover",
                      display: "block",
                    }}
                  />
                )}

                {/* Dark left-to-right gradient so text is legible */}
                <div
                  style={{
                    position: "absolute",
                    top: 0,
                    left: 0,
                    width: "100%",
                    height: "100%",
                    background:
                      "linear-gradient(90deg, rgba(10,10,26,0.96) 0%, rgba(10,10,26,0.75) 40%, rgba(10,10,26,0.25) 70%, rgba(10,10,26,0.05) 100%)",
                  }}
                />
                {/* Bottom fade */}
                <div
                  style={{
                    position: "absolute",
                    bottom: 0,
                    left: 0,
                    width: "100%",
                    height: "55%",
                    background:
                      "linear-gradient(to top, rgba(10,10,26,0.95) 0%, transparent 100%)",
                  }}
                />
              </div>
            );
          })}
        </div>
      </div>

      {/* ── Content panel — overlaid on current slide via negative margin ── */}
      <div
        style={{
          position: "relative",
          marginTop: "calc(-1 * clamp(240px, 36vw, 420px))",
          height: "clamp(240px, 36vw, 420px)",
          zIndex: 5,
          pointerEvents: "none",
        }}
      >
        <div
          style={{
            height: "100%",
            display: "flex",
            flexDirection: "column",
            justifyContent: "flex-end",
            padding: "0 28px 24px",
            pointerEvents: "auto",
          }}
        >
          {/* Badges */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              marginBottom: 8,
              flexWrap: "wrap",
            }}
          >
            <span
              style={{
                fontSize: 8,
                fontWeight: 800,
                letterSpacing: "0.22em",
                textTransform: "uppercase",
                padding: "3px 8px",
                borderRadius: 3,
                background: "var(--accent)",
                color: "#fff",
              }}
            >
              Featured
            </span>
            {cur.category && (
              <span
                style={{
                  fontSize: 8,
                  fontWeight: 700,
                  letterSpacing: "0.16em",
                  textTransform: "uppercase",
                  padding: "3px 8px",
                  borderRadius: 3,
                  color: "rgba(255,255,255,0.6)",
                  border: "1px solid rgba(255,255,255,0.18)",
                  background: "rgba(255,255,255,0.06)",
                }}
              >
                {cur.category}
              </span>
            )}
          </div>

          {/* Title */}
          <h3
            style={{
              color: "#fff",
              fontWeight: 900,
              fontSize: "clamp(16px, 2.6vw, 28px)",
              letterSpacing: "-0.022em",
              lineHeight: 1.2,
              marginBottom: 6,
              maxWidth: "min(68%, 480px)",
              textShadow: "0 2px 20px rgba(0,0,0,0.8)",
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical" as const,
              overflow: "hidden",
            }}
          >
            {cur.title}
          </h3>

          {/* Meta */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              marginBottom: 14,
              flexWrap: "wrap",
            }}
          >
            {cur.channelName && (
              <span
                style={{
                  fontSize: 10,
                  fontWeight: 600,
                  color: "rgba(255,255,255,0.65)",
                }}
              >
                {cur.channelName}
              </span>
            )}
            {cur.views && (
              <>
                <span style={{ color: "rgba(255,255,255,0.2)", fontSize: 8 }}>
                  •
                </span>
                <span style={{ fontSize: 10, color: "rgba(255,255,255,0.45)" }}>
                  {cur.views}
                </span>
              </>
            )}
            {cur.duration && (
              <>
                <span style={{ color: "rgba(255,255,255,0.2)", fontSize: 8 }}>
                  •
                </span>
                <span
                  style={{
                    fontSize: 10,
                    fontFamily: "monospace",
                    color: "rgba(255,255,255,0.4)",
                  }}
                >
                  {cur.duration}
                </span>
              </>
            )}
          </div>

          {/* Action buttons */}
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <button
              style={{
                display: "flex",
                alignItems: "center",
                gap: 7,
                padding: "8px 20px",
                borderRadius: 999,
                fontSize: 11,
                fontWeight: 800,
                color: "#fff",
                cursor: "pointer",
                background: "var(--accent)",
                boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.55)",
                border: "none",
              }}
              onClick={(e) => {
                e.stopPropagation();
                navigate(cur);
              }}
            >
              <Play size={11} fill="#fff" color="#fff" strokeWidth={0} />
              Play Now
            </button>
            <button
              style={{
                display: "flex",
                alignItems: "center",
                gap: 7,
                padding: "8px 18px",
                borderRadius: 999,
                fontSize: 11,
                fontWeight: 600,
                color: "#fff",
                cursor: "pointer",
                background: "rgba(255,255,255,0.1)",
                border: "1px solid rgba(255,255,255,0.2)",
                backdropFilter: "blur(8px)",
              }}
              onClick={(e) => {
                e.stopPropagation();
                navigate(cur);
              }}
            >
              More Info
            </button>
          </div>
        </div>
      </div>

      {/* ── Controls bar ── */}
      {n > 1 && (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "10px 28px 4px",
            background: "var(--bg)",
          }}
        >
          {/* Slide counter */}
          <span
            style={{
              fontSize: 10,
              fontWeight: 700,
              color: "var(--text-muted)",
              fontVariantNumeric: "tabular-nums",
            }}
          >
            <span style={{ color: "var(--text-muted)", fontSize: 12 }}>
              {String(idx + 1).padStart(2, "0")}
            </span>
            {" / "}
            {String(n).padStart(2, "0")}
          </span>

          {/* Dot indicators */}
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            {items.map((_, i) => (
              <button
                key={i}
                onClick={() => setIdx(i)}
                style={{
                  width: i === idx ? 20 : 5,
                  height: 5,
                  borderRadius: 999,
                  border: "none",
                  cursor: "pointer",
                  background: i === idx ? "var(--accent)" : "var(--border)",
                  transition: "width 0.3s ease, background 0.3s ease",
                  padding: 0,
                }}
              />
            ))}
          </div>

          {/* Prev / Next */}
          <div style={{ display: "flex", gap: 6 }}>
            <button
              onClick={() => setIdx((idx - 1 + n) % n)}
              style={{
                width: 28,
                height: 28,
                borderRadius: "50%",
                border: "1px solid var(--border)",
                background: "var(--btn-ghost)",
                color: "var(--text-primary)",
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <ChevronLeft size={14} strokeWidth={2} />
            </button>
            <button
              onClick={() => setIdx((idx + 1) % n)}
              style={{
                width: 28,
                height: 28,
                borderRadius: "50%",
                border: "1px solid var(--border)",
                background: "var(--btn-ghost)",
                color: "var(--text-primary)",
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <ChevronRight size={14} strokeWidth={2} />
            </button>
          </div>
        </div>
      )}

      {/* Progress bar */}
      {!paused && (
        <div
          style={{
            height: 2,
            background: "var(--border)",
            width: "100%",
          }}
        >
          <div
            key={idx}
            style={{
              height: "100%",
              background: "var(--accent)",
              borderRadius: 1,
              animation: `banner-prog ${BANNER_AUTO_MS}ms linear forwards`,
            }}
          />
        </div>
      )}
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   LAYOUT 8 — podcast_list_view  (vertical podcast list with large thumbs)
═══════════════════════════════════════════════════════════════════════════ */

function PodcastListRow({ item }: { item: MusicItem }) {
  const navigate = useNavigateToDetail();

  return (
    <div
      className="flex items-center gap-3.5 py-3 px-3 rounded-xl cursor-pointer group transition-all duration-150"
      style={{ background: "transparent" }}
      onMouseEnter={(e) =>
        ((e.currentTarget as HTMLElement).style.background = "var(--card)")
      }
      onMouseLeave={(e) =>
        ((e.currentTarget as HTMLElement).style.background = "transparent")
      }
      onClick={() => navigate(item)}
    >
      {/* Thumbnail */}
      <div
        className="relative shrink-0 rounded-xl overflow-hidden"
        style={{ width: 68, height: 68, background: "var(--deep)" }}
      >
        {item.thumbnail ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-105"
            unoptimized
            sizes="68px"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Headphones
              size={24}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.5}
            />
          </div>
        )}
      </div>

      {/* Info */}
      <div className="flex-1 min-w-0">
        <p
          className="text-xs font-bold truncate leading-tight"
          style={{ color: "var(--text-primary)" }}
        >
          {item.title}
        </p>
        <p
          className="text-[10px] mt-0.5 truncate font-medium"
          style={{ color: "var(--accent)" }}
        >
          {item.channelName}
        </p>
        <div className="flex items-center gap-2 mt-1.5">
          {item.totalEpisodes ? (
            <span
              className="text-[9px] font-semibold px-2 py-0.5 rounded-full"
              style={{
                background: "rgba(var(--accent-rgb),0.12)",
                color: "var(--accent)",
                border: "1px solid rgba(var(--accent-rgb),0.2)",
              }}
            >
              {item.totalEpisodes} ep
            </span>
          ) : null}
          {item.duration && (
            <span className="text-[10px]" style={{ color: "#555" }}>
              {item.duration}
            </span>
          )}
        </div>
      </div>

      {/* Arrow — navigate to detail (no direct play for podcasts) */}
      <ChevronRight
        size={16}
        strokeWidth={2}
        className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-150"
        style={{ color: "#555" }}
      />
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   Horizontal scroll wrapper
═══════════════════════════════════════════════════════════════════════════ */

function HorizontalScroll({ children }: { children: React.ReactNode }) {
  return (
    <div className="relative">
      <div className="flex gap-3 overflow-x-auto scrollbar-hide pb-1">
        {children}
      </div>
      <div className="absolute right-0 top-0 bottom-0 w-6 pointer-events-none z-10 bg-gradient-to-l from-[var(--bg)] to-transparent" />
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   Section renderer — all 8 layout types
═══════════════════════════════════════════════════════════════════════════ */

function MusicSectionBlock({ section }: { section: MusicSection }) {
  const router = useRouter();
  if (section.items.length === 0) return null;

  const handleSeeAll = () => {
    router.push(
      `/music/section/${section.id}?title=${encodeURIComponent(section.title)}`,
    );
  };

  const layoutMap: Record<string, (items: MusicItem[]) => React.ReactNode> = {
    /* 1. Numbered vertical track list */
    list_view: (items) => (
      <div className="flex flex-col">
        {items.map((item, i) => (
          <ListRow key={item.id} item={item} index={i} />
        ))}
      </div>
    ),

    /* 2. Portrait (3:4) cards — horizontal scroll */
    portrait: (items) => (
      <HorizontalScroll>
        {items.map((item) => (
          <PortraitCard key={item.id} item={item} />
        ))}
      </HorizontalScroll>
    ),

    /* 3. Playlist collage cards — horizontal scroll */
    playlist: (items) => (
      <HorizontalScroll>
        {items.map((item) => (
          <PlaylistCard key={item.id} item={item} />
        ))}
      </HorizontalScroll>
    ),

    /* 4. Square (1:1) album art cards — horizontal scroll */
    square: (items) => (
      <HorizontalScroll>
        {items.map((item) => (
          <SquareCard key={item.id} item={item} />
        ))}
      </HorizontalScroll>
    ),

    /* 5. Landscape (16:9) cards — horizontal scroll */
    landscape: (items) => (
      <HorizontalScroll>
        {items.map((item) => (
          <LandscapeCard key={item.id} item={item} />
        ))}
      </HorizontalScroll>
    ),

    /* 6. Round circular cards — horizontal scroll */
    round: (items) => (
      <HorizontalScroll>
        {items.map((item) => (
          <RoundCard key={item.id} item={item} />
        ))}
      </HorizontalScroll>
    ),

    /* 7. Full-width auto-scroll banner carousel */
    banner_view: (items) => <BannerCarousel items={items} />,

    /* 8. Podcast vertical list — no scroll */
    podcast_list_view: (items) => (
      <div
        className="flex flex-col rounded-2xl overflow-hidden"
        style={{
          border: "1px solid var(--border)",
          background: "var(--border-soft)",
        }}
      >
        {items.map((item, i) => (
          <div key={item.id}>
            <PodcastListRow item={item} />
            {i < items.length - 1 && (
              <div
                className="mx-4"
                style={{ height: "1px", background: "var(--border)" }}
              />
            )}
          </div>
        ))}
      </div>
    ),
  };

  const renderer =
    layoutMap[section.screenLayout] ??
    ((items: MusicItem[]) => (
      <HorizontalScroll>
        {items.map((item) => (
          <SquareCard key={item.id} item={item} />
        ))}
      </HorizontalScroll>
    ));

  return (
    <SectionContext.Provider value={section.items}>
      <section className="mb-10">
        <SectionHead
          title={section.title}
          subtitle={section.shortTitle}
          viewAll={section.viewAll}
          onSeeAll={handleSeeAll}
        />
        {renderer(section.items)}
      </section>
    </SectionContext.Provider>
  );
}

/* ═══════════════════════════════════════════════════════════════════════════
   MusicPage root
═══════════════════════════════════════════════════════════════════════════ */

export default function MusicPage({
  contentType = 1,
}: {
  contentType?: number;
}) {
  const dispatch = useAppDispatch();
  const { sections, isLoading, error } = useAppSelector((s) => s.musicSection);

  useEffect(() => {
    dispatch(fetchMusicSections(contentType));
  }, [dispatch, contentType]);

  /* Split banner sections out so they render full-width without padding */
  const bannerSections = sections.filter(
    (s) => s.screenLayout === "banner_view",
  );
  const otherSections = sections.filter(
    (s) => s.screenLayout !== "banner_view",
  );

  return (
    <div className="min-h-screen pb-32" style={{ background: "var(--bg)" }}>
      {/* ── Full-width banners (no horizontal padding) ──────────────────── */}
      {!isLoading &&
        !error &&
        bannerSections.map((section) => (
          <SectionContext.Provider key={section.id} value={section.items}>
            {section.items.length > 0 && (
              <BannerCarousel items={section.items} />
            )}
          </SectionContext.Provider>
        ))}

      {/* ── Other sections (padded) ──────────────────────────────────────── */}
      <div className="px-5 pt-6">
        {isLoading ? (
          <>
            {Array.from({ length: 4 }).map((_, i) => (
              <SectionSkeleton key={i} />
            ))}
          </>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <Music2 size={40} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>
              {error}
            </p>
            <button
              onClick={() => dispatch(fetchMusicSections(contentType))}
              className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] transition-all active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              Retry
            </button>
          </div>
        ) : sections.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-3">
            <Music2 size={40} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>
              No content available
            </p>
          </div>
        ) : (
          otherSections.map((section) => (
            <MusicSectionBlock key={section.id} section={section} />
          ))
        )}
      </div>
    </div>
  );
}
