"use client";

import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  Play,
  Download,
  MoreVertical,
  Music2,
  Headphones,
  Radio,
  RotateCcw,
  CheckCircle2,
} from "lucide-react";
import { useAppDispatch } from "@/store/hooks";
import { stopAll } from "@/store/slices/playerSlice";
import { setReelQueue } from "@/store/slices/reelQueueSlice";
import { useSidebar } from "@/lib/SidebarContext";
import { ContentItem } from "@/types/content";
import { getLayout, CONTENT_TYPE_MAP } from "@/config/contentTypes";
import { reelsListService, type MappedReel } from "@/services/reelsListService";
import {
  ContentActionsModal,
  type ContentActionContext,
} from "@/components/shared/ContentActionsModal";

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

function contentItemToMappedReel(item: ContentItem): MappedReel {
  const idNum = parseInt(item.id) || 0;
  return {
    id: item.id,
    contentType: item.contentType,
    caption: item.title,
    likes: item.likes,
    totalLikeCount: 0,
    totalDislikeCount: 0,
    isUserLikeDislike: 0,
    isLike: 0,
    image: item.portraitImg || item.thumbnail,
    hue: (idNum * 47) % 360,
    channelName: item.channelName,
    channelImage: item.channelImage || "",
    channelId: "",
    channelUserId: "",
    videoUrl: item.videoUrl,
    totalComments: item.totalComments,
    totalView: item.views,
    creator: item.channelName,
    initial: (item.channelName[0] ?? "?").toUpperCase(),
    sound: item.title.slice(0, 40) || "Original Sound",
    comments: String(item.totalComments),
  };
}

function useNavigate() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { collapse } = useSidebar();
  return (item: ContentItem) => {
    dispatch(stopAll());
    collapse();
    let href: string;
    if (item.contentType === 3) {
      href = `/reel/${item.id}`;
    } else if (
      item.contentType === 2 ||
      item.contentType === 4 ||
      item.contentType === 6
    ) {
      href = `/content/${item.contentType}/${item.id}`;
    } else {
      href = `/video/${item.id}`;
    }
    router.push(href);
  };
}

function ProgressPill({ pct }: { pct: number }) {
  if (pct <= 0) return null;
  const done = pct >= 95;
  return (
    <span
      className="inline-flex items-center gap-1 text-[8px] font-bold px-1.5 py-[2px] rounded-sm shrink-0"
      style={{
        background: done
          ? "rgba(34,197,94,0.13)"
          : "rgba(var(--accent-rgb),0.12)",
        color: done ? "#4ade80" : "var(--accent)",
        border: done
          ? "1px solid rgba(34,197,94,0.22)"
          : "1px solid rgba(var(--accent-rgb),0.2)",
      }}
    >
      {done && <CheckCircle2 size={7} strokeWidth={2.5} />}
      {done ? "Watched" : `${pct}%`}
    </span>
  );
}

function ChannelAvatar({ item }: { item: ContentItem }) {
  return (
    <div
      className="relative w-7 h-7 rounded-full overflow-hidden shrink-0"
      style={{ background: "var(--deep)" }}
    >
      {item.channelImage ? (
        <Image
          src={item.channelImage}
          alt={item.channelName}
          fill
          className="object-cover"
          unoptimized
          sizes="28px"
        />
      ) : (
        <div
          className="w-full h-full flex items-center justify-center text-[10px] font-bold text-[#ffffff]"
          style={{ background: "#2a2a4e" }}
        >
          {item.channelName[0]?.toUpperCase()}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   LAYOUT 1 — video-grid  (content_type 1 = Video, 5 = Live Event)
   Responsive 4-col grid, landscape thumbnail, progress bar, meta row
───────────────────────────────────────────────────────────────────────────── */

export function VideoCard({
  item,
  index,
  onDeleteItem,
}: {
  item: ContentItem;
  index: number;
  onDeleteItem?: () => void;
}) {
  const go = useNavigate();
  const delay = Math.min(index * 40, 640);
  const isLive = item.isLive;
  const [actionCtx, setActionCtx] = useState<ContentActionContext | null>(null);

  return (
    <>
      <div
        className="group flex flex-col rounded-xl overflow-hidden cursor-pointer"
        style={{
          background: "var(--card)",
          border: isLive
            ? "1px solid rgba(217,48,37,0.22)"
            : "1px solid var(--border-soft)",
          boxShadow: isLive ? "0 0 0 1px rgba(217,48,37,0.1)" : "none",
          animation: "liked-card-in 0.4s ease forwards",
          animationDelay: `${delay}ms`,
          opacity: 0,
        }}
        onClick={() => go(item)}
      >
        {/* Thumbnail */}
        <div
          className="relative aspect-video overflow-hidden"
          style={{ background: "var(--deep)" }}
        >
          {item.thumbnail ? (
            <Image
              src={item.thumbnail}
              alt={item.title}
              fill
              className="object-cover transition-transform duration-300 group-hover:scale-[1.04]"
              sizes="(max-width: 560px) 100vw, (max-width: 980px) 50vw, 33vw"
              unoptimized
            />
          ) : null}
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              background:
                "linear-gradient(to top,rgba(0,0,0,0.6) 0%,transparent 55%)",
            }}
          />

          {/* Live badge */}
          {isLive && (
            <span
              className="absolute top-2 left-2 text-[8px] font-bold uppercase px-1.5 py-0.5 rounded-sm tracking-widest flex items-center gap-1 text-[#ffffff]"
              style={{ background: "#d93025" }}
            >
              <span className="w-1.5 h-1.5 rounded-full bg-white inline-block animate-pulse" />
              LIVE
            </span>
          )}

          {/* Duration */}
          {item.duration && !isLive && (
            <span
              className="absolute bottom-2 right-2 text-[9px] font-semibold px-1 py-0.5 rounded-sm font-mono text-[#ffffff]"
              style={{ background: "rgba(0,0,0,0.82)" }}
            >
              {item.duration}
            </span>
          )}

          {/* Play overlay */}
          <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
            <span
              className="w-11 h-11 rounded-full flex items-center justify-center"
              style={{
                background: "rgba(var(--accent-rgb),0.92)",
                boxShadow: "0 4px 22px rgba(var(--accent-rgb),0.55)",
              }}
            >
              <Play size={17} fill="white" strokeWidth={0} className="ml-0.5" />
            </span>
          </div>

          {/* Watch progress */}
          {item.progressPct > 0 && (
            <div
              className="absolute bottom-0 left-0 right-0"
              style={{ height: 3, background: "rgba(255,255,255,0.12)" }}
            >
              <div
                style={{
                  height: "100%",
                  width: `${item.progressPct}%`,
                  background:
                    item.progressPct >= 95 ? "#4ade80" : "var(--accent)",
                }}
              />
            </div>
          )}
        </div>

        {/* Meta */}
        <div className="flex items-start gap-2.5 p-3">
          <ChannelAvatar item={item} />
          <div className="flex-1 min-w-0">
            <p className="text-xs font-semibold line-clamp-2 leading-snug tracking-tight" style={{ color: "var(--text-primary)" }}>
              {item.title}
            </p>
            <p className="text-[10px] mt-1 truncate" style={{ color: "#888" }}>
              {item.channelName}
            </p>
            <div className="flex items-center gap-2 mt-0.5 flex-wrap">
              <span className="text-[10px]" style={{ color: "#666" }}>
                {item.views}
              </span>
              <span style={{ color: "#444", fontSize: 9 }}>·</span>
              <span className="text-[10px]" style={{ color: "#666" }}>
                {item.uploadedAt}
              </span>
              {item.progressPct > 0 && (
                <>
                  <span style={{ color: "#444", fontSize: 9 }}>·</span>
                  <ProgressPill pct={item.progressPct} />
                </>
              )}
            </div>
          </div>
          <button
            className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity p-1.5 rounded-lg hover:bg-white/10 active:scale-90"
            onClick={(e) => {
              e.stopPropagation();
              setActionCtx({
                contentId: item.id,
                contentType: item.contentType,
                channelId: item.channelId,
                channelUserId: item.channelUserId,
                title: item.title,
                thumbnail: item.thumbnail,
                channelName: item.channelName,
              });
            }}
          >
            <MoreVertical size={13} color="#888" />
          </button>
          {onDeleteItem && (
            <button
              className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity p-1.5 rounded-lg hover:bg-red-500/15 active:scale-90"
              title="Remove from history"
              onClick={(e) => {
                e.stopPropagation();
                onDeleteItem();
              }}
            >
              <svg
                width="12"
                height="12"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#f43f5e"
                strokeWidth="2.2"
                strokeLinecap="round"
              >
                <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
              </svg>
            </button>
          )}
        </div>
      </div>

      {actionCtx && (
        <ContentActionsModal
          context={actionCtx}
          onClose={() => setActionCtx(null)}
        />
      )}
    </>
  );
}

export function VideoGrid({
  items,
  onDeleteItem,
}: {
  items: ContentItem[];
  onDeleteItem?: (item: ContentItem) => void;
}) {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      {items.map((item, i) => (
        <VideoCard
          key={item.id}
          item={item}
          index={i}
          onDeleteItem={onDeleteItem ? () => onDeleteItem(item) : undefined}
        />
      ))}
    </div>
  );
}

export function VideoGridSkeleton({ count = 8 }: { count?: number }) {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      {Array.from({ length: count }).map((_, i) => (
        <div
          key={i}
          className="rounded-xl overflow-hidden animate-pulse"
          style={{ background: "var(--card)" }}
        >
          <div className="aspect-video" style={{ background: "var(--deep)" }} />
          <div className="p-3 flex gap-2.5">
            <div
              className="w-7 h-7 rounded-full shrink-0"
              style={{ background: "var(--deep)" }}
            />
            <div className="flex-1 flex flex-col gap-2">
              <div
                className="h-3 rounded-full"
                style={{ background: "var(--deep)", width: "88%" }}
              />
              <div
                className="h-2.5 rounded-full"
                style={{ background: "var(--deep)", width: "55%" }}
              />
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   LAYOUT 2 — music-list  (content_type 2 = Music)
   Numbered track rows, album art, progress dot, duration
───────────────────────────────────────────────────────────────────────────── */

export function MusicRow({
  item,
  index,
  onDeleteItem,
}: {
  item: ContentItem;
  index: number;
  onDeleteItem?: () => void;
}) {
  const go = useNavigate();
  const delay = Math.min(index * 35, 500);
  const [actionCtx, setActionCtx] = useState<ContentActionContext | null>(null);

  return (
    <div
      className="group flex items-center gap-3 py-2.5 px-3 rounded-xl cursor-pointer transition-colors duration-150"
      style={{
        background: "transparent",
        animation: "liked-card-in 0.38s ease forwards",
        animationDelay: `${delay}ms`,
        opacity: 0,
        borderLeft:
          item.progressPct > 0
            ? "2px solid rgba(var(--accent-rgb),0.4)"
            : "2px solid transparent",
      }}
      onMouseEnter={(e) =>
        ((e.currentTarget as HTMLElement).style.background = "var(--card)")
      }
      onMouseLeave={(e) =>
        ((e.currentTarget as HTMLElement).style.background = "transparent")
      }
      onClick={() => go(item)}
    >
      {/* Index / play */}
      <div className="w-7 flex items-center justify-center shrink-0">
        <span
          className="text-xs font-bold group-hover:hidden"
          style={{ color: "#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)" }}
        >
          <Play size={10} fill="white" strokeWidth={0} className="ml-px" />
        </div>
      </div>

      {/* Album art */}
      <div
        className="relative w-10 h-10 rounded-lg overflow-hidden shrink-0"
        style={{ background: "var(--deep)" }}
      >
        {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>
        )}
        {item.progressPct > 0 && (
          <div
            className="absolute bottom-0 left-0 right-0"
            style={{ height: 2, background: "rgba(0,0,0,0.5)" }}
          >
            <div
              style={{
                height: "100%",
                width: `${item.progressPct}%`,
                background: "var(--accent)",
              }}
            />
          </div>
        )}
      </div>

      {/* Title + artist */}
      <div className="flex-1 min-w-0">
        <p className="text-xs font-semibold truncate" style={{ color: "var(--text-primary)" }}>
          {item.title}
        </p>
        <div className="flex items-center gap-2 mt-0.5">
          <p className="text-[10px] truncate" style={{ color: "#666" }}>
            {item.channelName}
          </p>
          {item.progressPct > 0 && <ProgressPill pct={item.progressPct} />}
        </div>
      </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.5 rounded-lg hover:bg-white/10 active:scale-90"
          onClick={(e) => {
            e.stopPropagation();
            setActionCtx({
              contentId: item.id,
              contentType: item.contentType,
              channelId: item.channelId,
              channelUserId: item.channelUserId,
              title: item.title,
              thumbnail: item.thumbnail,
              channelName: item.channelName,
            });
          }}
        >
          <MoreVertical size={13} color="#888" />
        </button>
        {onDeleteItem && (
          <button
            className="opacity-0 group-hover:opacity-100 transition-opacity p-1.5 rounded-lg hover:bg-red-500/15 active:scale-90"
            onClick={(e) => {
              e.stopPropagation();
              onDeleteItem();
            }}
          >
            <svg
              width="11"
              height="11"
              viewBox="0 0 24 24"
              fill="none"
              stroke="#f43f5e"
              strokeWidth="2.2"
              strokeLinecap="round"
            >
              <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
            </svg>
          </button>
        )}
      </div>

      {actionCtx && (
        <ContentActionsModal
          context={actionCtx}
          onClose={() => setActionCtx(null)}
        />
      )}
    </div>
  );
}

export function MusicList({
  items,
  onDeleteItem,
}: {
  items: ContentItem[];
  onDeleteItem?: (item: ContentItem) => void;
}) {
  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{
        border: "1px solid var(--border-soft)",
        background: "transparent",
      }}
    >
      {items.map((item, i) => (
        <div key={item.id}>
          <MusicRow
            item={item}
            index={i}
            onDeleteItem={onDeleteItem ? () => onDeleteItem(item) : undefined}
          />
          {i < items.length - 1 && (
            <div
              className="mx-3"
              style={{ height: 1, background: "var(--border-soft)" }}
            />
          )}
        </div>
      ))}
    </div>
  );
}

export function MusicListSkeleton({ count = 7 }: { count?: number }) {
  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{ border: "1px solid var(--border-soft)" }}
    >
      {Array.from({ length: count }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-3 px-3 py-3 animate-pulse"
        >
          <div className="w-7 shrink-0" />
          <div
            className="w-10 h-10 rounded-lg shrink-0"
            style={{ background: "var(--deep)" }}
          />
          <div className="flex-1 flex flex-col gap-2">
            <div
              className="h-3 rounded-full"
              style={{ background: "var(--deep)", width: "72%" }}
            />
            <div
              className="h-2.5 rounded-full"
              style={{ background: "var(--deep)", width: "44%" }}
            />
          </div>
          <div
            className="h-2.5 w-10 rounded-full"
            style={{ background: "var(--deep)" }}
          />
        </div>
      ))}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   LAYOUT 3 — reel-grid  (content_type 3 = Reel)
   Portrait-ratio cards in a 2/3/4-col grid
───────────────────────────────────────────────────────────────────────────── */

export function ReelCard({
  item,
  index,
  onCardClick,
}: {
  item: ContentItem;
  index: number;
  onCardClick?: () => void;
}) {
  const go = useNavigate();
  const delay = Math.min(index * 40, 640);
  const img = item.portraitImg || item.thumbnail;

  return (
    <div
      className="group flex flex-col gap-2 cursor-pointer"
      style={{
        animation: "liked-card-in 0.4s ease forwards",
        animationDelay: `${delay}ms`,
        opacity: 0,
      }}
      onClick={onCardClick ?? (() => go(item))}
    >
      <div
        className="relative overflow-hidden rounded-xl"
        style={{ aspectRatio: "9/16", background: "var(--deep)" }}
      >
        {img ? (
          <Image
            src={img}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-[1.04]"
            sizes="(max-width: 560px) 50vw, (max-width: 980px) 33vw, 25vw"
            unoptimized
          />
        ) : null}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{
            background:
              "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 50%)",
          }}
        />

        {item.duration && (
          <span
            className="absolute bottom-2 right-2 text-[9px] font-semibold px-1 py-0.5 rounded-sm font-mono text-[#ffffff]"
            style={{ background: "rgba(0,0,0,0.8)" }}
          >
            {item.duration}
          </span>
        )}

        {item.progressPct > 0 && (
          <div
            className="absolute bottom-0 left-0 right-0"
            style={{ height: 3, background: "rgba(255,255,255,0.12)" }}
          >
            <div
              style={{
                height: "100%",
                width: `${item.progressPct}%`,
                background: "var(--accent)",
              }}
            />
          </div>
        )}

        <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
          <span
            className="w-10 h-10 rounded-full flex items-center justify-center"
            style={{
              background: "rgba(var(--accent-rgb),0.92)",
              boxShadow: "0 4px 22px rgba(var(--accent-rgb),0.55)",
            }}
          >
            <Play size={15} fill="white" strokeWidth={0} className="ml-0.5" />
          </span>
        </div>
      </div>

      <p className="text-[11px] font-semibold line-clamp-2 leading-snug px-0.5" style={{ color: "var(--text-primary)" }}>
        {item.title}
      </p>
      <div className="flex items-center gap-1.5 px-0.5">
        <p className="text-[10px] truncate" style={{ color: "#777" }}>
          {item.channelName}
        </p>
        {item.progressPct > 0 && <ProgressPill pct={item.progressPct} />}
      </div>
    </div>
  );
}

export function ReelGrid({ items }: { items: ContentItem[] }) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { collapse } = useSidebar();

  const handleReelClick = (item: ContentItem) => {
    dispatch(stopAll());
    collapse();
    const queue = items.map(contentItemToMappedReel);
    dispatch(setReelQueue({ queue, startId: item.id }));
    router.push(`/reel/${item.id}`);
  };

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
      {items.map((item, i) => (
        <ReelCard
          key={item.id}
          item={item}
          index={i}
          onCardClick={() => handleReelClick(item)}
        />
      ))}
    </div>
  );
}

export function ReelGridSkeleton({ count = 10 }: { count?: number }) {
  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} className="flex flex-col gap-2 animate-pulse">
          <div
            className="rounded-xl"
            style={{ aspectRatio: "9/16", background: "var(--card)" }}
          />
          <div
            className="h-3 rounded-full"
            style={{ background: "var(--card)", width: "85%" }}
          />
          <div
            className="h-2.5 rounded-full"
            style={{ background: "var(--card)", width: "55%" }}
          />
        </div>
      ))}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   LAYOUT 4 — podcast-list  (content_type 4 = Podcast, 6 = Radio)
   Large cover art, episode info, progress bar, resume button
───────────────────────────────────────────────────────────────────────────── */

export function PodcastRow({
  item,
  index,
  onDeleteItem,
}: {
  item: ContentItem;
  index: number;
  onDeleteItem?: () => void;
}) {
  const go = useNavigate();
  const delay = Math.min(index * 50, 500);
  const isRadio = item.contentType === 6;
  const [actionCtx, setActionCtx] = useState<ContentActionContext | null>(null);

  return (
    <div
      className="group flex items-center gap-4 px-4 py-3.5 cursor-pointer transition-colors duration-150"
      style={{
        background: "transparent",
        animation: "liked-card-in 0.42s ease forwards",
        animationDelay: `${delay}ms`,
        opacity: 0,
      }}
      onMouseEnter={(e) =>
        ((e.currentTarget as HTMLElement).style.background = "var(--card)")
      }
      onMouseLeave={(e) =>
        ((e.currentTarget as HTMLElement).style.background = "transparent")
      }
      onClick={() => go(item)}
    >
      {/* Cover art */}
      <div
        className="relative shrink-0 rounded-xl overflow-hidden"
        style={{ width: 76, height: 76, 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="76px"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            {isRadio ? (
              <Radio
                size={26}
                style={{ color: "var(--accent)", opacity: 0.45 }}
                strokeWidth={1.5}
              />
            ) : (
              <Headphones
                size={26}
                style={{ color: "var(--accent)", opacity: 0.45 }}
                strokeWidth={1.5}
              />
            )}
          </div>
        )}
        {item.progressPct > 0 && (
          <div
            className="absolute bottom-0 left-0 right-0"
            style={{ height: 3, background: "rgba(0,0,0,0.5)" }}
          >
            <div
              style={{
                height: "100%",
                width: `${item.progressPct}%`,
                background:
                  item.progressPct >= 95 ? "#4ade80" : "var(--accent)",
              }}
            />
          </div>
        )}
      </div>

      {/* Info */}
      <div className="flex-1 min-w-0">
        <p className="text-xs font-bold leading-snug line-clamp-2" style={{ color: "var(--text-primary)" }}>
          {item.title}
        </p>
        <p
          className="text-[10px] font-semibold mt-0.5 truncate"
          style={{ color: "var(--accent)" }}
        >
          {item.channelName}
        </p>
        <div className="flex items-center gap-2 mt-1.5 flex-wrap">
          {item.category && (
            <span
              className="text-[9px] font-semibold px-1.5 py-0.5 rounded-full"
              style={{
                background: "var(--btn-ghost)",
                color: "#777",
                border: "1px solid var(--border)",
              }}
            >
              {item.category}
            </span>
          )}
          {item.duration && (
            <span className="text-[10px] font-mono" style={{ color: "#555" }}>
              {item.duration}
            </span>
          )}
          {item.progressPct > 0 && <ProgressPill pct={item.progressPct} />}
        </div>
        {item.progressPct > 0 && (
          <div
            className="mt-2"
            style={{
              height: 2,
              background: "var(--border)",
              borderRadius: 2,
            }}
          >
            <div
              style={{
                height: "100%",
                width: `${item.progressPct}%`,
                background:
                  item.progressPct >= 95 ? "#4ade80" : "var(--accent)",
                borderRadius: 2,
              }}
            />
          </div>
        )}
      </div>

      {/* More + optional delete — no Play/Resume: clicking the row navigates to detail */}
      <div className="flex items-center gap-1.5 shrink-0">
        <button
          className="opacity-0 group-hover:opacity-100 transition-opacity p-1.5 rounded-lg hover:bg-white/10 active:scale-90"
          onClick={(e) => {
            e.stopPropagation();
            setActionCtx({
              contentId: item.id,
              contentType: item.contentType,
              channelId: item.channelId,
              channelUserId: item.channelUserId,
              title: item.title,
              thumbnail: item.thumbnail,
              channelName: item.channelName,
            });
          }}
        >
          <MoreVertical size={13} color="#888" />
        </button>
        {onDeleteItem && (
          <button
            className="opacity-0 group-hover:opacity-100 transition-opacity p-1.5 rounded-lg hover:bg-red-500/15 active:scale-90"
            onClick={(e) => {
              e.stopPropagation();
              onDeleteItem();
            }}
          >
            <svg
              width="11"
              height="11"
              viewBox="0 0 24 24"
              fill="none"
              stroke="#f43f5e"
              strokeWidth="2.2"
              strokeLinecap="round"
            >
              <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
            </svg>
          </button>
        )}
      </div>

      {actionCtx && (
        <ContentActionsModal
          context={actionCtx}
          onClose={() => setActionCtx(null)}
        />
      )}
    </div>
  );
}

export function PodcastList({
  items,
  onDeleteItem,
}: {
  items: ContentItem[];
  onDeleteItem?: (item: ContentItem) => void;
}) {
  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{
        border: "1px solid var(--border-soft)",
        background: "transparent",
      }}
    >
      {items.map((item, i) => (
        <div key={item.id}>
          <PodcastRow
            item={item}
            index={i}
            onDeleteItem={onDeleteItem ? () => onDeleteItem(item) : undefined}
          />
          {i < items.length - 1 && (
            <div
              className="mx-4"
              style={{ height: 1, background: "var(--border-soft)" }}
            />
          )}
        </div>
      ))}
    </div>
  );
}

export function PodcastListSkeleton({ count = 5 }: { count?: number }) {
  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{ border: "1px solid var(--border-soft)" }}
    >
      {Array.from({ length: count }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-4 px-4 py-4 animate-pulse"
        >
          <div
            className="w-[76px] h-[76px] rounded-xl shrink-0"
            style={{ background: "var(--deep)" }}
          />
          <div className="flex-1 flex flex-col gap-2.5">
            <div
              className="h-3 rounded-full"
              style={{ background: "var(--deep)", width: "68%" }}
            />
            <div
              className="h-2.5 rounded-full"
              style={{ background: "var(--deep)", width: "42%" }}
            />
            <div
              className="h-1.5 rounded-full"
              style={{ background: "var(--deep)", width: "88%" }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   ContentRenderer — picks layout from active content type
───────────────────────────────────────────────────────────────────────────── */

export function ContentRenderer({
  items,
  contentTypeId,
  onDeleteItem,
}: {
  items: ContentItem[];
  contentTypeId: number;
  onDeleteItem?: (item: ContentItem) => void;
}) {
  const layout = getLayout(contentTypeId);
  if (layout === "music-list")
    return <MusicList items={items} onDeleteItem={onDeleteItem} />;
  if (layout === "reel-grid") return <ReelGrid items={items} />;
  if (layout === "podcast-list")
    return <PodcastList items={items} onDeleteItem={onDeleteItem} />;
  return <VideoGrid items={items} onDeleteItem={onDeleteItem} />;
}

export function SkeletonRenderer({
  contentTypeId,
  count,
}: {
  contentTypeId: number;
  count?: number;
}) {
  const layout = getLayout(contentTypeId);
  if (layout === "music-list") return <MusicListSkeleton count={count ?? 7} />;
  if (layout === "reel-grid") return <ReelGridSkeleton count={count ?? 10} />;
  if (layout === "podcast-list")
    return <PodcastListSkeleton count={count ?? 5} />;
  return <VideoGridSkeleton count={count ?? 8} />;
}

/* ─────────────────────────────────────────────────────────────────────────────
   Reusable Tab Bar
───────────────────────────────────────────────────────────────────────────── */

export function ContentTabBar({
  tabIds,
  activeId,
  onChange,
}: {
  tabIds: number[];
  activeId: number;
  onChange: (id: number) => void;
}) {
  return (
    <div
      className="sticky z-20 border-b"
      style={{
        top: "56px",
        background: "var(--bg)",
        borderColor: "var(--border-soft)",
      }}
    >
      <div className="relative">
        <div className="flex gap-2 overflow-x-auto scrollbar-hide px-5 py-3">
          {tabIds.map((id) => {
            const cfg = CONTENT_TYPE_MAP[id];
            if (!cfg) return null;
            const isActive = activeId === id;
            return (
              <button
                key={id}
                onClick={() => onChange(id)}
                className="shrink-0 flex items-center gap-1.5 h-[30px] px-3 rounded-2xl text-[11px] font-semibold whitespace-nowrap transition-all duration-150"
                style={{
                  background: isActive ? "var(--accent)" : "var(--card)",
                  color: isActive ? "#fff" : "#888",
                  border: isActive
                    ? "1px solid transparent"
                    : "1px solid var(--border)",
                  boxShadow: isActive
                    ? "0 2px 12px rgba(var(--accent-rgb),0.35)"
                    : "none",
                }}
              >
                <span style={{ fontSize: 12 }}>{cfg.emoji}</span>
                {cfg.label}
              </button>
            );
          })}
        </div>
        <div
          className="absolute right-0 top-0 bottom-0 w-8 pointer-events-none z-10"
          style={{
            background: "linear-gradient(270deg, var(--bg) 40%, transparent)",
          }}
        />
      </div>
    </div>
  );
}
