"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchChannelDetails,
  fetchChannelContent,
  toggleFollow,
  toggleBlock,
  setActiveContentType,
  optimisticToggleFollow,
  selectChannelDetail,
  selectChannelLoaded,
  selectChannelContent,
  selectActiveContentType,
  selectChannelLoading,
  selectContentLoading,
} from "@/store/slices/channelSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { useToast } from "@/lib/toast";
import type { ChannelContentItem } from "@/types/api/channel.types";

// ── Helpers ───────────────────────────────────────────────────────────────────
function isValidImg(url?: string) {
  return !!url && !url.includes("no_img");
}
function fmtNum(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
  return String(n);
}
function fmtRelTime(d: string) {
  const diff = Date.now() - new Date(d).getTime();
  const h = Math.floor(diff / 3_600_000);
  if (h < 1) return `${Math.floor(diff / 60_000)}m`;
  if (h < 24) return `${h}h`;
  return `${Math.floor(h / 24)}d`;
}

// ── Content tab definitions ───────────────────────────────────────────────────
const TABS = [
  { type: 1, label: "Articles", icon: "📰" },
  { type: 2, label: "Clips",    icon: "🎬" },
  { type: 3, label: "Live",     icon: "📡" },
  { type: 4, label: "Shows",    icon: "📺" },
  { type: 8, label: "Polls",    icon: "📊" },
];

// ── Content Cards ─────────────────────────────────────────────────────────────
function ArticleCard({ item }: { item: ChannelContentItem }) {
  const img = isValidImg(item.web_image) ? item.web_image
    : isValidImg(item.landscape_img) ? item.landscape_img
    : isValidImg(item.portrait_img) ? item.portrait_img : null;
  return (
    <Link href={`/detail/${item.id}`} style={{ display: "flex", gap: "0.875rem", padding: "0.875rem 0", borderBottom: "1px solid var(--border)", textDecoration: "none", color: "inherit" }}>
      <div style={{ flexShrink: 0, width: 100, height: 68, borderRadius: 7, overflow: "hidden", position: "relative", background: "#e5e7eb" }}>
        {img && <Image src={img} alt="" fill style={{ objectFit: "cover" }} unoptimized />}
        {item.is_premium === 1 && (
          <span style={{ position: "absolute", top: 3, right: 3, background: "#b45309", color: "#fff", fontSize: 7, fontWeight: 700, padding: "1px 4px", borderRadius: 2 }}>PREMIUM</span>
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        {item.category && <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--brand)", display: "block", marginBottom: 3 }}>{item.category}</span>}
        <h4 style={{ fontSize: "0.875rem", fontWeight: 600, lineHeight: 1.4, margin: "0 0 5px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", color: "var(--ink)" }}>{item.title}</h4>
        <div style={{ fontSize: "0.688rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)", display: "flex", gap: "0.375rem" }}>
          <span>{fmtRelTime(item.created_at)}</span>
          {item.total_view > 0 && <><span>·</span><span>{fmtNum(item.total_view)}</span></>}
        </div>
      </div>
    </Link>
  );
}

function ClipCard({ item }: { item: ChannelContentItem }) {
  const img = isValidImg(item.portrait_img) ? item.portrait_img : null;
  return (
    <Link href={`/detail/${item.id}`} style={{ textDecoration: "none", color: "inherit" }}>
      <div style={{ aspectRatio: "9/16", borderRadius: 10, overflow: "hidden", position: "relative", background: "#1a1a2e", marginBottom: "0.5rem" }}>
        {img && <Image src={img} alt="" fill style={{ objectFit: "cover" }} unoptimized />}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 50%)" }} />
        <div style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)", width: 40, height: 40, background: "rgba(255,255,255,0.2)", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", backdropFilter: "blur(4px)" }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><polygon points="6 4 20 12 6 20" /></svg>
        </div>
        <div style={{ position: "absolute", bottom: 10, left: 10, right: 10 }}>
          <p style={{ fontSize: "0.75rem", fontWeight: 600, color: "#fff", margin: 0, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{item.title}</p>
        </div>
      </div>
      <div style={{ fontSize: "0.688rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)" }}>{fmtRelTime(item.created_at)} · {fmtNum(item.total_view)}</div>
    </Link>
  );
}

function LiveCard({ item }: { item: ChannelContentItem }) {
  const img = isValidImg(item.web_image) ? item.web_image
    : isValidImg(item.landscape_img) ? item.landscape_img : null;
  const href = item.live_url ?? `/detail/${item.id}`;
  const isExternal = href.startsWith("http");
  const inner = (
    <>
      <div style={{ flexShrink: 0, width: 110, height: 70, borderRadius: 7, overflow: "hidden", position: "relative", background: "#1e1b4b" }}>
        {img && <Image src={img} alt="" fill style={{ objectFit: "cover" }} unoptimized />}
        <span style={{ position: "absolute", top: 5, left: 5, background: "var(--live)", color: "#fff", fontSize: 8, fontWeight: 800, padding: "2px 6px", borderRadius: 3, display: "flex", alignItems: "center", gap: 3 }}>
          <span style={{ width: 4, height: 4, background: "#fff", borderRadius: "50%" }} />LIVE
        </span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <h4 style={{ fontSize: "0.875rem", fontWeight: 600, lineHeight: 1.4, margin: "0 0 5px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", color: "var(--ink)" }}>{item.title}</h4>
        <div style={{ fontSize: "0.688rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)", display: "flex", gap: "0.375rem", alignItems: "center" }}>
          <span>{fmtRelTime(item.created_at)}</span>
          {isExternal && <><span>·</span><svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" /><polyline points="15 3 21 3 21 9" /><line x1="10" y1="14" x2="21" y2="3" /></svg></>}
        </div>
      </div>
    </>
  );
  const sharedStyle: React.CSSProperties = { display: "flex", gap: "0.875rem", padding: "0.875rem 0", borderBottom: "1px solid var(--border)", textDecoration: "none", color: "inherit" };
  if (isExternal) {
    return <a href={href} target="_blank" rel="noopener noreferrer" style={sharedStyle}>{inner}</a>;
  }
  return <Link href={href} style={sharedStyle}>{inner}</Link>;
}

function ShowCard({ item }: { item: ChannelContentItem }) {
  const img = isValidImg(item.landscape_img) ? item.landscape_img
    : isValidImg(item.web_image) ? item.web_image
    : isValidImg(item.portrait_img) ? item.portrait_img : null;
  return (
    <Link href={`/detail/${item.id}`} style={{ textDecoration: "none", color: "inherit" }}>
      <div style={{ aspectRatio: "16/9", borderRadius: 10, overflow: "hidden", position: "relative", background: "#0f172a", marginBottom: "0.625rem" }}>
        {img && <Image src={img} alt={item.title} fill style={{ objectFit: "cover" }} unoptimized />}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.55) 0%, transparent 60%)" }} />
        <div style={{ position: "absolute", bottom: 10, left: 12, right: 12 }}>
          <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: "0.07em", textTransform: "uppercase", color: "rgba(255,255,255,0.8)", display: "block", marginBottom: 3 }}>Show</span>
        </div>
      </div>
      <h4 style={{ fontSize: "0.875rem", fontWeight: 600, lineHeight: 1.4, margin: "0 0 4px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", color: "var(--ink)" }}>{item.title}</h4>
      <div style={{ fontSize: "0.688rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)" }}>{fmtRelTime(item.created_at)}</div>
    </Link>
  );
}

function PollCard({ item }: { item: ChannelContentItem }) {
  const opts = [
    { k: "a", label: item.option_a, pct: item.percentage_option_a ?? "0", count: item.option_a_count ?? 0 },
    { k: "b", label: item.option_b, pct: item.percentage_option_b ?? "0", count: item.option_b_count ?? 0 },
    { k: "c", label: item.option_c, pct: item.percentage_option_c ?? "0", count: item.option_c_count ?? 0 },
    { k: "d", label: item.option_d, pct: item.percentage_option_d ?? "0", count: item.option_d_count ?? 0 },
  ].filter((o) => !!o.label);
  const maxPct = Math.max(...opts.map((o) => parseFloat(o.pct) || 0));
  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, padding: "1.125rem" }}>
      <h4 style={{ fontSize: "0.9375rem", fontWeight: 700, lineHeight: 1.4, margin: "0 0 1rem", color: "var(--ink)" }}>{item.question}</h4>
      <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem", marginBottom: "0.75rem" }}>
        {opts.map((opt) => {
          const p = parseFloat(opt.pct) || 0;
          const lead = p === maxPct && p > 0;
          return (
            <div key={opt.k} style={{ position: "relative", height: 36, borderRadius: 7, background: lead ? "var(--brand-light)" : "#f3f4f6", overflow: "hidden", border: `1px solid ${lead ? "var(--brand)" : "transparent"}` }}>
              <div style={{ position: "absolute", left: 0, top: 0, height: "100%", width: `${p}%`, background: lead ? "rgba(193,39,45,0.1)" : "rgba(0,0,0,0.03)", transition: "width 0.5s" }} />
              <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 10px" }}>
                <span style={{ fontSize: "0.8125rem", fontWeight: lead ? 700 : 500, color: lead ? "var(--brand)" : "var(--ink)" }}>{opt.label}</span>
                <span style={{ fontSize: "0.75rem", fontFamily: "var(--mono)", fontWeight: 700, color: lead ? "var(--brand)" : "var(--text-secondary)" }}>{opt.pct}%</span>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ fontSize: "0.688rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)", display: "flex", justifyContent: "space-between" }}>
        <span>{item.total_opinions ?? 0} votes</span>
        {item.closing_date && <span>Closes {item.closing_date}</span>}
      </div>
    </div>
  );
}

function ContentCard({ item, contentType }: { item: ChannelContentItem; contentType: number }) {
  switch (contentType) {
    case 2: return <ClipCard item={item} />;
    case 3: return <LiveCard item={item} />;
    case 4: return <ShowCard item={item} />;
    case 8: return <PollCard item={item} />;
    default: return <ArticleCard item={item} />;
  }
}

function ContentSkeleton({ type }: { type: number }) {
  if (type === 2 || type === 4) {
    return (
      <div style={{ aspectRatio: type === 2 ? "9/16" : "16/9", borderRadius: 10, background: "#e5e7eb" }} />
    );
  }
  return (
    <div style={{ display: "flex", gap: "0.875rem", padding: "0.875rem 0", borderBottom: "1px solid var(--border)" }}>
      <div style={{ flexShrink: 0, width: 100, height: 68, borderRadius: 7, background: "#e5e7eb" }} />
      <div style={{ flex: 1 }}>
        <div style={{ height: 9, width: "25%", background: "#e5e7eb", borderRadius: 4, marginBottom: 7 }} />
        <div style={{ height: 13, width: "90%", background: "#e5e7eb", borderRadius: 4, marginBottom: 5 }} />
        <div style={{ height: 9, width: "40%", background: "#e5e7eb", borderRadius: 4 }} />
      </div>
    </div>
  );
}

// ── Main Shell ────────────────────────────────────────────────────────────────
interface Props { channelId: number; }

const DESC_LIMIT = 120;

export default function ChannelDetailShell({ channelId }: Props) {
  const dispatch = useAppDispatch();
  const { success, error: showError } = useToast();
  const fetchedRef = useRef(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [userId, setUserId] = useState(0);
  const [descExpanded, setDescExpanded] = useState(false);
  useEffect(() => { setUserId(getStoredUser()?.id ?? 0); }, []);
  const channel = useAppSelector(selectChannelDetail(channelId));
  const isLoaded = useAppSelector(selectChannelLoaded(channelId));
  const isLoadingDetails = useAppSelector(selectChannelLoading);
  const isLoadingContent = useAppSelector(selectContentLoading);
  const activeType = useAppSelector(selectActiveContentType);
  const contentItems = useAppSelector(selectChannelContent(channelId, activeType));

  useEffect(() => {
    if (!isLoaded && !fetchedRef.current && channelId > 0) {
      fetchedRef.current = true;
      dispatch(fetchChannelDetails({ channelId, userId }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!channelId || channelId <= 0) return;
    if (contentItems === null) {
      dispatch(fetchChannelContent({ channelId, contentType: activeType, userId }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeType, channelId]);

  function handleTabSwitch(type: number) {
    dispatch(setActiveContentType(type));
  }

  async function handleFollow() {
    if (!userId) return;
    const wasFollowing = channel?.is_follow === 1;
    dispatch(optimisticToggleFollow(channelId));
    const res = await dispatch(toggleFollow({ channelId, userId, currentIsFollow: channel?.is_follow ?? 0 }));
    if (toggleFollow.fulfilled.match(res)) {
      success(wasFollowing ? "Unfollowed channel" : "Following channel");
    } else {
      dispatch(optimisticToggleFollow(channelId)); // rollback
      showError("Failed to update follow status");
    }
  }

  async function handleBlock() {
    if (!userId) return;
    const res = await dispatch(toggleBlock({ channelId, userId }));
    setMenuOpen(false);
    if (toggleBlock.fulfilled.match(res)) {
      success("Channel blocked");
    } else {
      showError("Failed to block channel");
    }
  }

  const coverImg = isValidImg(channel?.landscape_img) ? channel?.landscape_img : null;
  const logoImg = isValidImg(channel?.portrait_img) ? channel?.portrait_img : null;

  const isGrid = activeType === 2 || activeType === 4;
  const isPoll = activeType === 8;

  return (
    <main>
      {/* ── Cover ── */}
      <div style={{ position: "relative", height: 220, background: "#0f172a", overflow: "hidden" }}>
        {coverImg && <Image src={coverImg} alt="" fill style={{ objectFit: "cover" }} priority unoptimized />}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.2) 60%, transparent 100%)" }} />
      </div>

      {/* ── Channel identity row ── */}
      <div style={{ background: "var(--surface)", borderBottom: "1px solid var(--border)" }}>
        <div className="wrap">
          <div style={{ display: "flex", gap: "1.25rem", alignItems: "flex-end", marginTop: "-44px", paddingBottom: "1.25rem", position: "relative", zIndex: 1 }}>
            {/* Logo */}
            <div style={{ flexShrink: 0, width: 88, height: 88, borderRadius: "50%", border: "3px solid var(--surface)", overflow: "hidden", position: "relative", background: "var(--brand-light)", boxShadow: "0 2px 12px rgba(0,0,0,0.15)" }}>
              {logoImg
                ? <Image src={logoImg} alt={channel?.name ?? ""} fill style={{ objectFit: "cover" }} unoptimized />
                : <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <span style={{ fontSize: "2rem", fontWeight: 800, color: "var(--brand)" }}>
                      {channel?.name?.charAt(0) ?? "?"}
                    </span>
                  </div>
              }
            </div>

            {/* Name + meta + actions */}
            <div style={{ flex: 1, minWidth: 0, paddingTop: 48 }}>
              <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: "1rem" }}>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.25rem" }}>
                    <h1 style={{ fontSize: "clamp(1.25rem, 3vw, 1.75rem)", fontWeight: 800, margin: 0, color: "var(--ink)", fontFamily: "var(--sans)" }}>
                      {channel?.name ?? "Loading…"}
                    </h1>
                    {channel?.is_verified === 1 && (
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
                        <circle cx="12" cy="12" r="12" fill="var(--brand)" />
                        <path d="M7 12l3 3 7-7" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    )}
                  </div>
                  <div style={{ fontSize: "0.8125rem", color: "var(--text-secondary)" }}>
                    {channel?.ch_user_name}
                    {channel && <span style={{ marginLeft: "0.5rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)" }}>· {fmtNum(channel.followers)} followers</span>}
                  </div>
                </div>

                {/* Follow + menu */}
                <div style={{ display: "flex", gap: "0.5rem", alignItems: "center", flexShrink: 0 }}>
                  <button
                    onClick={handleFollow}
                    style={{
                      padding: "0.5rem 1.25rem",
                      borderRadius: 8,
                      fontWeight: 700,
                      fontSize: "0.875rem",
                      cursor: userId ? "pointer" : "default",
                      border: channel?.is_follow === 1 ? "1.5px solid var(--border)" : "none",
                      background: channel?.is_follow === 1 ? "transparent" : "var(--brand)",
                      color: channel?.is_follow === 1 ? "var(--ink)" : "#fff",
                      transition: "all 0.15s",
                    }}
                  >
                    {channel?.is_follow === 1 ? "Following" : "Follow"}
                  </button>

                  {/* Three-dot menu */}
                  <div style={{ position: "relative" }}>
                    <button
                      onClick={() => setMenuOpen((v) => !v)}
                      style={{ background: "var(--background)", border: "1px solid var(--border)", borderRadius: 8, width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}
                    >
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <circle cx="12" cy="5" r="1.5" fill="currentColor" />
                        <circle cx="12" cy="12" r="1.5" fill="currentColor" />
                        <circle cx="12" cy="19" r="1.5" fill="currentColor" />
                      </svg>
                    </button>
                    {menuOpen && (
                      <div style={{ position: "absolute", right: 0, top: "calc(100% + 4px)", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, minWidth: 160, boxShadow: "0 4px 20px rgba(0,0,0,0.1)", zIndex: 50 }}>
                        <button
                          onClick={handleBlock}
                          style={{ display: "block", width: "100%", padding: "0.625rem 1rem", textAlign: "left", background: "none", border: "none", cursor: "pointer", fontSize: "0.875rem", color: "var(--brand)", fontWeight: 600 }}
                        >
                          🚫 Block channel
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Stats row */}
              {channel && (
                <div style={{ display: "flex", gap: "1.5rem", marginTop: "0.875rem", flexWrap: "wrap" }}>
                  {[
                    { label: "Articles", value: channel.total_article },
                    { label: "Clips",    value: channel.total_clips },
                    { label: "Live",     value: channel.total_live_news },
                    { label: "Shows",    value: channel.total_shows },
                    { label: "Polls",    value: channel.total_opinion_poll },
                  ].map((s) => (
                    <div key={s.label} style={{ textAlign: "center" }}>
                      <div style={{ fontWeight: 800, fontSize: "1rem", fontFamily: "var(--mono)", color: "var(--ink)" }}>{fmtNum(s.value)}</div>
                      <div style={{ fontSize: "0.688rem", color: "var(--text-tertiary)", letterSpacing: "0.04em" }}>{s.label}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* Description */}
              {channel?.description && (() => {
                const desc = channel.description;
                const isLong = desc.length > DESC_LIMIT;
                const displayText = isLong && !descExpanded
                  ? desc.slice(0, DESC_LIMIT).trimEnd()
                  : desc;
                return (
                  <p style={{ marginTop: "0.75rem", fontSize: "0.875rem", color: "var(--text-secondary)", lineHeight: 1.55, maxWidth: 520, margin: "0.75rem 0 0" }}>
                    {displayText}
                    {isLong && !descExpanded && (
                      <>
                        {"… "}
                        <button
                          onClick={() => setDescExpanded(true)}
                          style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontSize: "0.875rem", fontWeight: 600, color: "var(--brand)", lineHeight: "inherit" }}
                        >
                          Read more
                        </button>
                      </>
                    )}
                    {isLong && descExpanded && (
                      <>
                        {" "}
                        <button
                          onClick={() => setDescExpanded(false)}
                          style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontSize: "0.875rem", fontWeight: 600, color: "var(--brand)", lineHeight: "inherit" }}
                        >
                          Read less
                        </button>
                      </>
                    )}
                  </p>
                );
              })()}
            </div>
          </div>
        </div>
      </div>

      {/* ── Content tabs ── */}
      <div style={{ background: "var(--surface)", borderBottom: "1px solid var(--border)", position: "sticky", top: 72, zIndex: 30 }}>
        <div className="wrap">
          <div style={{ display: "flex", gap: 0, overflowX: "auto", scrollbarWidth: "none" }}>
            {TABS.map((tab) => (
              <button
                key={tab.type}
                onClick={() => handleTabSwitch(tab.type)}
                style={{
                  flexShrink: 0,
                  padding: "0.875rem 1.25rem",
                  background: "none",
                  border: "none",
                  borderBottom: activeType === tab.type ? "2.5px solid var(--brand)" : "2.5px solid transparent",
                  color: activeType === tab.type ? "var(--brand)" : "var(--text-secondary)",
                  fontWeight: activeType === tab.type ? 700 : 500,
                  fontSize: "0.875rem",
                  cursor: "pointer",
                  transition: "all 0.15s",
                  display: "flex",
                  alignItems: "center",
                  gap: "0.375rem",
                }}
              >
                <span>{tab.icon}</span>
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* ── Content ── */}
      <div className="wrap" style={{ paddingTop: "1.5rem", paddingBottom: "3rem" }}>
        {isLoadingContent && contentItems === null ? (
          <div style={isGrid ? { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: "1rem" } : {}}>
            {Array.from({ length: 6 }).map((_, i) => <ContentSkeleton key={i} type={activeType} />)}
          </div>
        ) : !contentItems || contentItems.length === 0 ? (
          <div style={{ textAlign: "center", padding: "3rem 0", color: "var(--text-secondary)" }}>
            <p style={{ fontWeight: 600 }}>No {TABS.find((t) => t.type === activeType)?.label ?? "content"} yet</p>
          </div>
        ) : (
          <div style={
            isGrid
              ? { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: "1rem" }
              : isPoll
              ? { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: "1.25rem" }
              : {}
          }>
            {contentItems.map((item) => (
              <ContentCard key={item.id} item={item} contentType={activeType} />
            ))}
          </div>
        )}
      </div>
    </main>
  );
}
