"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchContentDetail,
  fetchRelatedContent,
  optimisticLike,
  optimisticBookmark,
  toggleLike,
  toggleBookmark,
  selectContentDetail,
  selectContentLoading,
  selectContentLoaded,
  selectRelatedContent,
  type CacheKey,
} from "@/store/slices/contentDetailSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { addView } from "@/lib/utils/addView";
import { useToast } from "@/lib/toast";
import { usePermission } from "@/hooks/usePermission";
import CommentDrawer from "@/features/common/components/CommentDrawer";
import ReportModal from "@/features/common/components/ReportModal";
import PremiumGate from "@/features/common/components/PremiumGate";
import type { ContentDetailItem } from "@/types/api/contentDetail.types";

// ── Helpers ───────────────────────────────────────────────────────────────────
function isValidImg(url?: string) {
  return !!url && !url.includes("no_img");
}
function fmtViews(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 m = Math.floor(diff / 60_000);
  const h = Math.floor(m / 60);
  if (m < 60) return `${m}m ago`;
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

const TYPE_LABELS: Record<number, string> = {
  1: "Article",
  2: "Clip",
  3: "Live",
  4: "Show",
};

// ── Hero image (best available) ───────────────────────────────────────────────
function HeroImage({ item, type }: { item: ContentDetailItem; type: number }) {
  const img =
    type === 2
      ? isValidImg(item.portrait_img)
        ? item.portrait_img
        : null
      : isValidImg(item.web_image)
        ? item.web_image
        : isValidImg(item.landscape_img)
          ? item.landscape_img
          : isValidImg(item.portrait_img)
            ? item.portrait_img
            : null;

  if (type === 2 && item.video) {
    return (
      <div
        style={{
          background: "#000",
          maxHeight: 500,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <video
          src={item.video}
          controls
          autoPlay={false}
          poster={img ?? undefined}
          style={{
            width: "100%",
            maxHeight: 500,
            objectFit: "contain",
            display: "block",
          }}
        />
      </div>
    );
  }

  // No valid image — render a branded placeholder so the hero area is never empty
  if (!img) {
    return (
      <div
        style={{
          width: "100%",
          aspectRatio: "16/9",
          maxHeight: 460,
          background:
            "linear-gradient(135deg, #0f172a 0%, #1e1b4b 50%, #0f172a 100%)",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          gap: "0.75rem",
          overflow: "hidden",
          position: "relative",
        }}
      >
        {/* decorative pattern */}
        <div
          style={{
            position: "absolute",
            inset: 0,
            backgroundImage:
              "radial-gradient(circle at 30% 40%, rgba(193,39,45,0.15) 0%, transparent 50%), radial-gradient(circle at 70% 60%, rgba(59,130,246,0.08) 0%, transparent 50%)",
          }}
        />
        <svg
          width="48"
          height="48"
          viewBox="0 0 24 24"
          fill="none"
          stroke="rgba(255,255,255,0.18)"
          strokeWidth="1"
          style={{ flexShrink: 0 }}
        >
          <rect x="3" y="3" width="18" height="18" rx="2" />
          <circle cx="8.5" cy="8.5" r="1.5" />
          <path d="M21 15l-5-5L5 21" />
        </svg>
        <span
          style={{
            fontSize: "0.75rem",
            fontFamily: "var(--mono, monospace)",
            color: "rgba(255,255,255,0.25)",
            letterSpacing: "0.1em",
            textTransform: "uppercase",
          }}
        >
          No image available
        </span>
      </div>
    );
  }

  return (
    <div
      style={{
        position: "relative",
        width: "100%",
        aspectRatio: "16/9",
        maxHeight: 460,
        overflow: "hidden",
        background: "#0f172a",
      }}
    >
      <Image
        src={img}
        alt={item.title}
        fill
        style={{ objectFit: "cover" }}
        priority
        unoptimized
      />
      {/* Subtle gradient for text legibility if used as hero */}
      <div
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          right: 0,
          height: "40%",
          background:
            "linear-gradient(to top, rgba(0,0,0,0.35) 0%, transparent 100%)",
        }}
      />
    </div>
  );
}

// ── Channel attribution bar ───────────────────────────────────────────────────
function ChannelBar({
  item,
  contentType,
}: {
  item: ContentDetailItem;
  contentType: number;
}) {
  const channelImg = isValidImg(item.channel_image) ? item.channel_image : null;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: "0.625rem" }}>
      <Link
        href={`/channel/${item.channel_id}`}
        style={{
          display: "flex",
          alignItems: "center",
          gap: "0.5rem",
          textDecoration: "none",
        }}
      >
        <div
          style={{
            flexShrink: 0,
            width: 32,
            height: 32,
            borderRadius: "50%",
            overflow: "hidden",
            position: "relative",
            background: "var(--brand-08, rgba(193,39,45,0.08))",
          }}
        >
          {channelImg ? (
            <Image
              src={channelImg}
              alt=""
              fill
              style={{ objectFit: "cover" }}
              unoptimized
            />
          ) : (
            <span
              style={{
                position: "absolute",
                inset: 0,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 12,
                fontWeight: 800,
                color: "var(--brand, #C1272D)",
              }}
            >
              {item.channel_name?.charAt(0)}
            </span>
          )}
        </div>
        <span
          style={{
            fontWeight: 700,
            fontSize: "0.875rem",
            color: "var(--ink, #0e0e11)",
          }}
        >
          {item.channel_name}
        </span>
        {item.is_verified === 1 && (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="12" fill="var(--brand, #C1272D)" />
            <path
              d="M7 12l3 3 7-7"
              stroke="#fff"
              strokeWidth="2.5"
              strokeLinecap="round"
            />
          </svg>
        )}
      </Link>
      <span
        style={{
          fontSize: "0.75rem",
          color: "var(--text-3, #9ca3af)",
          fontFamily: "var(--mono, monospace)",
        }}
      >
        {fmtRelTime(item.created_at)}
      </span>
      {/* Type badge */}
      <span
        style={{
          fontSize: 9,
          fontWeight: 800,
          letterSpacing: "0.08em",
          textTransform: "uppercase",
          padding: "2px 7px",
          borderRadius: 4,
          background:
            contentType === 3
              ? "rgba(237,32,39,0.1)"
              : "var(--brand-08, rgba(193,39,45,0.08))",
          color:
            contentType === 3
              ? "var(--live, #ed2027)"
              : "var(--brand, #C1272D)",
          display: "flex",
          alignItems: "center",
          gap: 4,
        }}
      >
        {contentType === 3 && (
          <span
            style={{
              width: 5,
              height: 5,
              borderRadius: "50%",
              background: "var(--live, #ed2027)",
              flexShrink: 0,
            }}
          />
        )}
        {TYPE_LABELS[contentType] ?? "Content"}
      </span>
    </div>
  );
}

// ── Action bar ─────────────────────────────────────────────────────────────────
function ActionBar({
  item,
  contentType,
  cacheKey,
  userId,
  onComment,
  onReport,
}: {
  item: ContentDetailItem;
  contentType: number;
  cacheKey: CacheKey;
  userId: number;
  onComment: () => void;
  onReport: () => void;
}) {
  const dispatch = useAppDispatch();
  const { success, error: showError } = useToast();
  const { requireLogin } = usePermission();

  const liked = item.is_user_like === 1;
  const bookmarked = item.is_user_bookmark === 1;

  async function handleLike() {
    if (!requireLogin("like")) return;
    dispatch(optimisticLike(cacheKey));
    const res = await dispatch(
      toggleLike({
        type: contentType,
        contentId: item.id,
        userId,
        currentLiked: liked,
      }),
    );
    if (toggleLike.fulfilled.match(res)) {
      success(res.payload.message || (liked ? "Unliked" : "Liked"));
    } else {
      dispatch(optimisticLike(cacheKey)); // rollback
      showError("Failed to update like");
    }
  }

  async function handleBookmark() {
    if (!requireLogin("bookmark")) return;
    dispatch(optimisticBookmark(cacheKey));
    const res = await dispatch(
      toggleBookmark({
        type: contentType,
        contentId: item.id,
        userId,
        currentBookmarked: bookmarked,
      }),
    );
    if (toggleBookmark.fulfilled.match(res)) {
      success(
        res.payload.message ||
          (bookmarked ? "Bookmark Removed" : "Bookmark Added"),
      );
    } else {
      dispatch(optimisticBookmark(cacheKey)); // rollback
      showError("Failed to update bookmark");
    }
  }

  const btnStyle = (
    active: boolean,
    activeColor = "var(--brand, #C1272D)",
  ): React.CSSProperties => ({
    display: "flex",
    alignItems: "center",
    gap: "0.375rem",
    padding: "0.5rem 0.875rem",
    borderRadius: 8,
    background: active ? "var(--brand-08, rgba(193,39,45,0.08))" : "none",
    border: "none",
    cursor: "pointer",
    fontSize: "0.8125rem",
    fontFamily: "var(--mono, monospace)",
    color: active ? activeColor : "var(--text-2, #6b7280)",
    fontWeight: active ? 700 : 400,
    transition: "all 0.15s",
  });

  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: "0.25rem",
        padding: "0.75rem 0",
        borderTop: "1px solid var(--border, #e5e7eb)",
        borderBottom: "1px solid var(--border, #e5e7eb)",
        marginTop: "1.25rem",
        flexWrap: "wrap",
      }}
    >
      {/* Like */}
      {item.is_like !== 0 && (
        <button onClick={handleLike} style={btnStyle(liked)}>
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill={liked ? "var(--brand, #C1272D)" : "none"}
            stroke={liked ? "var(--brand, #C1272D)" : "currentColor"}
            strokeWidth="2"
          >
            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
          </svg>
          {item.total_like > 0 ? fmtViews(item.total_like) : "Like"}
        </button>
      )}

      {/* Comment */}
      {item.is_comment !== 0 && (
        <button onClick={onComment} style={btnStyle(false)}>
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8z" />
          </svg>
          {item.total_comment && item.total_comment > 0
            ? item.total_comment
            : "Comment"}
        </button>
      )}

      {/* Bookmark */}
      {item.is_bookmark !== 0 && (
        <button
          onClick={handleBookmark}
          style={btnStyle(bookmarked, "#3b82f6")}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill={bookmarked ? "#3b82f6" : "none"}
            stroke={bookmarked ? "#3b82f6" : "currentColor"}
            strokeWidth="2"
          >
            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
          </svg>
          {bookmarked ? "Saved" : "Save"}
        </button>
      )}

      {/* Share */}
      <button
        style={{ ...btnStyle(false), marginLeft: "auto" }}
        onClick={() => {
          if (navigator.share) {
            navigator.share({ title: item.title, url: window.location.href });
          }
        }}
      >
        <svg
          width="15"
          height="15"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
        >
          <circle cx="18" cy="5" r="3" />
          <circle cx="6" cy="12" r="3" />
          <circle cx="18" cy="19" r="3" />
          <path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4" />
        </svg>
        Share
      </button>

      {/* Report */}
      <button onClick={onReport} style={btnStyle(false)}>
        <svg
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
        >
          <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" />
          <line x1="4" y1="22" x2="4" y2="15" />
        </svg>
        Report
      </button>
    </div>
  );
}

// ── Stats bar ─────────────────────────────────────────────────────────────────
function StatsBar({ item }: { item: ContentDetailItem }) {
  return (
    <div
      style={{
        display: "flex",
        gap: "1.25rem",
        padding: "0.625rem 0",
        flexWrap: "wrap",
      }}
    >
      {item.total_view > 0 && (
        <span
          style={{
            fontSize: "0.8125rem",
            fontFamily: "var(--mono, monospace)",
            color: "var(--text-2, #6b7280)",
            display: "flex",
            alignItems: "center",
            gap: 4,
          }}
        >
          <svg
            width="13"
            height="13"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <circle cx="12" cy="12" r="3" />
            <path d="M2 12s4-8 10-8 10 8 10 8-4 8-10 8S2 12 2 12z" />
          </svg>
          {fmtViews(item.total_view)} views
        </span>
      )}
      {item.language && (
        <span
          style={{
            fontSize: "0.8125rem",
            fontFamily: "var(--mono, monospace)",
            color: "var(--text-2, #6b7280)",
          }}
        >
          {item.language}
        </span>
      )}
      {item.category && (
        <span
          style={{
            fontSize: "0.8125rem",
            fontFamily: "var(--mono, monospace)",
            color: "var(--brand, #C1272D)",
            fontWeight: 600,
          }}
        >
          {item.category}
        </span>
      )}
      {item.city && (
        <span
          style={{
            fontSize: "0.8125rem",
            fontFamily: "var(--mono, monospace)",
            color: "var(--text-2, #6b7280)",
          }}
        >
          📍 {item.city}
        </span>
      )}
    </div>
  );
}

// ── Skeleton loader ───────────────────────────────────────────────────────────
function DetailSkeleton() {
  return (
    <div style={{ maxWidth: 760, margin: "0 auto" }}>
      <div
        style={{
          height: 280,
          borderRadius: 10,
          background: "#e5e7eb",
          marginBottom: "1.5rem",
        }}
      />
      <div
        style={{
          height: 14,
          width: "25%",
          background: "#e5e7eb",
          borderRadius: 4,
          marginBottom: 16,
        }}
      />
      <div
        style={{
          height: 28,
          background: "#e5e7eb",
          borderRadius: 4,
          marginBottom: 8,
        }}
      />
      <div
        style={{
          height: 28,
          width: "80%",
          background: "#e5e7eb",
          borderRadius: 4,
          marginBottom: 24,
        }}
      />
      {Array.from({ length: 5 }).map((_, i) => (
        <div
          key={i}
          style={{
            height: 14,
            background: "#e5e7eb",
            borderRadius: 4,
            marginBottom: 8,
            width: i % 3 === 2 ? "60%" : "100%",
          }}
        />
      ))}
    </div>
  );
}

// ── Main shell ────────────────────────────────────────────────────────────────
interface Props {
  contentType: number;
  contentId: number;
}

export default function ContentDetailShell({ contentType, contentId }: Props) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const fetchedRef = useRef(false);
  const [userId, setUserId] = useState(0);
  const [commentOpen, setCommentOpen] = useState(false);
  const [reportOpen, setReportOpen] = useState(false);

  useEffect(() => {
    setUserId(getStoredUser()?.id ?? 0);
  }, []);

  const cacheKey: CacheKey = `${contentType}_${contentId}`;
  const item = useAppSelector(selectContentDetail(contentType, contentId));
  const loaded = useAppSelector(selectContentLoaded(contentType, contentId));
  const loading = useAppSelector(selectContentLoading);
  const related = useAppSelector(selectRelatedContent(contentType, contentId));

  useEffect(() => {
    if (!loaded && !fetchedRef.current) {
      fetchedRef.current = true;
      dispatch(fetchContentDetail({ type: contentType, contentId, userId }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Fetch related content + fire view tracking once the main item is loaded
  useEffect(() => {
    if (!item) return;
    // Track the view — fire once per content load
    addView(contentType, contentId, userId);
    // Fetch related content only for article=1 and show=4
    if (related === null && (contentType === 1 || contentType === 4)) {
      dispatch(
        fetchRelatedContent({
          type: contentType,
          contentId,
          languageId: item.language_id ?? 1,
          userId,
        }),
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [item?.id]);

  // Report type: map content type to report type (clips=2, article=1, show=4; live news falls back to 1)
  const reportType = contentType === 2 ? 2 : contentType === 4 ? 4 : 1;

  if (loading && !item) {
    return (
      <main
        style={{
          minHeight: "60vh",
          padding: "1.5rem 0 3rem",
          background: "var(--bg, #f8f9fb)",
        }}
      >
        <div className="wrap">
          <DetailSkeleton />
        </div>
      </main>
    );
  }

  if (!loading && !item) {
    return (
      <main
        style={{
          minHeight: "60vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "var(--bg, #f8f9fb)",
        }}
      >
        <div style={{ textAlign: "center", padding: "2rem" }}>
          <p
            style={{
              fontWeight: 700,
              fontSize: "1.125rem",
              marginBottom: "0.5rem",
              color: "var(--ink, #0e0e11)",
            }}
          >
            Content not found
          </p>
          <button
            onClick={() => router.back()}
            style={{
              color: "var(--brand, #C1272D)",
              background: "none",
              border: "none",
              cursor: "pointer",
              fontWeight: 600,
              fontSize: "0.875rem",
            }}
          >
            ← Go back
          </button>
        </div>
      </main>
    );
  }

  if (!item) return null;

  return (
    <>
      <main
        style={{
          minHeight: "60vh",
          background: "var(--bg, #f8f9fb)",
          paddingBottom: "3rem",
        }}
      >
        {/* Hero media */}
        <HeroImage item={item} type={contentType} />

        <div
          className="wrap"
          style={{ margin: "0 auto", paddingTop: "1.5rem" }}
        >
          {/* Back + breadcrumb */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "0.5rem",
              marginBottom: "1rem",
              fontSize: "0.8125rem",
              color: "var(--text-2, #6b7280)",
            }}
          >
            <button
              onClick={() => router.back()}
              style={{
                background: "none",
                border: "none",
                cursor: "pointer",
                color: "var(--text-2, #6b7280)",
                display: "flex",
                alignItems: "center",
                gap: 4,
                fontWeight: 600,
                fontSize: "0.8125rem",
              }}
            >
              <svg
                width="14"
                height="14"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2.5"
              >
                <path d="M19 12H5M12 5l-7 7 7 7" />
              </svg>
              Back
            </button>
            {item.category && (
              <>
                <span>/</span>
                <Link
                  href={`/category/${item.category.toLowerCase()}`}
                  style={{
                    color: "var(--brand, #C1272D)",
                    textDecoration: "none",
                    fontWeight: 600,
                  }}
                >
                  {item.category}
                </Link>
              </>
            )}
          </div>

          {/* Channel bar */}
          <div style={{ marginBottom: "1rem" }}>
            <ChannelBar item={item} contentType={contentType} />
          </div>

          {/* Title */}
          <h1
            style={{
              fontSize: "clamp(1.375rem, 3vw, 2rem)",
              fontWeight: 800,
              lineHeight: 1.25,
              letterSpacing: "-0.02em",
              color: "var(--ink, #0e0e11)",
              marginBottom: "0.75rem",
              fontFamily: "var(--serif, Georgia, serif)",
            }}
          >
            {item.title}
          </h1>

          {/* Stats */}
          <StatsBar item={item} />

          {/* Premium badge */}
          {item.is_premium === 1 && (
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "0.375rem",
                padding: "0.375rem 0.875rem",
                background: "#fef3c7",
                border: "1px solid #fcd34d",
                borderRadius: 6,
                marginBottom: "0.875rem",
                fontSize: "0.8125rem",
                fontWeight: 700,
                color: "#b45309",
              }}
            >
              ⭐ Premium content
            </div>
          )}

          {/* Short description (article) */}
          {item.short_description && (
            <p
              style={{
                fontSize: "1.0625rem",
                lineHeight: 1.65,
                color: "var(--text-2, #6b7280)",
                marginBottom: "1.25rem",
                fontFamily: "var(--serif, Georgia, serif)",
                fontStyle: "italic",
                borderLeft: "3px solid var(--brand, #C1272D)",
                paddingLeft: "1rem",
              }}
            >
              {item.short_description}
            </p>
          )}

          {/* Live News external link */}
          {contentType === 3 && item.live_url && (
            <a
              href={item.live_url}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                display: "flex",
                alignItems: "center",
                gap: "0.625rem",
                padding: "0.875rem 1rem",
                background: "rgba(237,32,39,0.06)",
                border: "1.5px solid var(--live, #ed2027)",
                borderRadius: 10,
                textDecoration: "none",
                color: "var(--live, #ed2027)",
                fontWeight: 700,
                marginBottom: "1.25rem",
              }}
            >
              <span
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: "50%",
                  background: "var(--live, #ed2027)",
                  animation: "pulse 1.5s infinite",
                  flexShrink: 0,
                }}
              />
              Read full live coverage
              <svg
                width="14"
                height="14"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                style={{ marginLeft: "auto" }}
              >
                <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>
            </a>
          )}

          {/* Audio player */}
          {item.audio && (
            <div
              style={{
                padding: "0.875rem 1rem",
                background: "var(--surf, #ffffff)",
                border: "1px solid var(--border, #e5e7eb)",
                borderRadius: 10,
                marginBottom: "1.25rem",
              }}
            >
              <p
                style={{
                  fontSize: "0.8125rem",
                  fontWeight: 700,
                  color: "var(--text-2, #6b7280)",
                  marginBottom: "0.5rem",
                }}
              >
                🎧 Audio version
              </p>
              <audio
                src={item.audio}
                controls
                style={{ width: "100%", height: 40 }}
              />
            </div>
          )}

          {/* Actions */}
          <ActionBar
            item={item}
            contentType={contentType}
            cacheKey={cacheKey}
            userId={userId}
            onComment={() => setCommentOpen(true)}
            onReport={() => setReportOpen(true)}
          />

          {/* HTML body — gated for premium content */}
          {item.description &&
            (item.is_premium === 1 ? (
              <PremiumGate blur>
                <div
                  className="article-body"
                  style={{
                    marginTop: "1.5rem",
                    lineHeight: 1.75,
                    fontSize: "1rem",
                    color: "var(--ink, #0e0e11)",
                    fontFamily: "var(--serif, Georgia, serif)",
                  }}
                  dangerouslySetInnerHTML={{ __html: item.description }}
                />
              </PremiumGate>
            ) : (
              <div
                className="article-body"
                style={{
                  marginTop: "1.5rem",
                  lineHeight: 1.75,
                  fontSize: "1rem",
                  color: "var(--ink, #0e0e11)",
                  fontFamily: "var(--serif, Georgia, serif)",
                }}
                dangerouslySetInnerHTML={{ __html: item.description }}
              />
            ))}

          {/* Hashtags */}
          {item.hashtag && item.hashtag.length > 0 && (
            <div
              style={{
                display: "flex",
                flexWrap: "wrap",
                gap: "0.5rem",
                marginTop: "1.75rem",
                paddingTop: "1.25rem",
                borderTop: "1px solid var(--border, #e5e7eb)",
              }}
            >
              {item.hashtag.map((h) => (
                <Link
                  key={h.id}
                  href={`/search?q=${encodeURIComponent(h.name)}`}
                  style={{
                    padding: "0.3rem 0.75rem",
                    background: "var(--brand-08, rgba(193,39,45,0.08))",
                    color: "var(--brand, #C1272D)",
                    fontSize: "0.8125rem",
                    fontWeight: 600,
                    borderRadius: 99,
                    textDecoration: "none",
                  }}
                >
                  #{h.name.trim()}
                </Link>
              ))}
            </div>
          )}

          {/* Bottom actions repeated */}
          <div style={{ marginTop: "1.75rem" }}>
            <ActionBar
              item={item}
              contentType={contentType}
              cacheKey={cacheKey}
              userId={userId}
              onComment={() => setCommentOpen(true)}
              onReport={() => setReportOpen(true)}
            />
          </div>
        </div>

        {/* ── Related Content ── only for Article & Show */}
        {(contentType === 1 || contentType === 4) &&
          related &&
          related.length > 0 && (
            <div
              className="wrap"
              style={{
                margin: "0 auto",
                paddingTop: "2rem",
                paddingBottom: "1rem",
              }}
            >
              <h2
                style={{
                  fontSize: "1.125rem",
                  fontWeight: 800,
                  color: "var(--ink, #0e0e11)",
                  marginBottom: "1rem",
                  paddingBottom: "0.625rem",
                  borderBottom: "2px solid var(--brand, #C1272D)",
                  display: "inline-block",
                }}
              >
                Related {contentType === 4 ? "Shows" : "Articles"}
              </h2>

              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "0.75rem",
                }}
              >
                {related.slice(0, 8).map((r) => {
                  const thumb = isValidImg(r.web_image)
                    ? r.web_image
                    : isValidImg(r.landscape_img)
                      ? r.landscape_img
                      : isValidImg(r.portrait_img)
                        ? r.portrait_img
                        : null;
                  return (
                    <Link
                      key={r.id}
                      href={`/detail/${r.id}?type=${contentType}`}
                      style={{
                        display: "flex",
                        gap: "0.875rem",
                        alignItems: "flex-start",
                        padding: "0.875rem",
                        background: "var(--surf, #ffffff)",
                        border: "1px solid var(--border, #e5e7eb)",
                        borderRadius: 10,
                        textDecoration: "none",
                        color: "inherit",
                        transition: "box-shadow 0.15s",
                      }}
                      onMouseEnter={(e) =>
                        (e.currentTarget.style.boxShadow =
                          "0 2px 12px rgba(0,0,0,0.08)")
                      }
                      onMouseLeave={(e) =>
                        (e.currentTarget.style.boxShadow = "none")
                      }
                    >
                      {/* Thumbnail */}
                      <div
                        style={{
                          flexShrink: 0,
                          width: 96,
                          height: 68,
                          borderRadius: 7,
                          overflow: "hidden",
                          position: "relative",
                          background: "#e5e7eb",
                        }}
                      >
                        {thumb && (
                          <Image
                            src={thumb}
                            alt=""
                            fill
                            style={{ objectFit: "cover" }}
                            unoptimized
                          />
                        )}
                        {r.is_premium === 1 && (
                          <span
                            style={{
                              position: "absolute",
                              top: 3,
                              right: 3,
                              background: "#b45309",
                              color: "#fff",
                              fontSize: 7,
                              fontWeight: 700,
                              padding: "1px 4px",
                              borderRadius: 2,
                            }}
                          >
                            PRO
                          </span>
                        )}
                      </div>

                      {/* Content */}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        {r.category && (
                          <span
                            style={{
                              fontSize: 9,
                              fontWeight: 800,
                              letterSpacing: "0.08em",
                              textTransform: "uppercase",
                              color: "var(--brand, #C1272D)",
                              display: "block",
                              marginBottom: 4,
                            }}
                          >
                            {r.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, #0e0e11)",
                          }}
                        >
                          {r.title}
                        </h4>
                        <div
                          style={{
                            display: "flex",
                            gap: "0.5rem",
                            fontSize: "0.7rem",
                            fontFamily: "var(--mono, monospace)",
                            color: "var(--text-3, #9ca3af)",
                          }}
                        >
                          {r.channel_name && <span>{r.channel_name}</span>}
                          {r.total_view > 0 && (
                            <>
                              <span>·</span>
                              <span>{fmtViews(r.total_view)} views</span>
                            </>
                          )}
                        </div>
                      </div>
                    </Link>
                  );
                })}
              </div>
            </div>
          )}
      </main>

      {/* Comments */}
      <CommentDrawer
        open={commentOpen}
        onClose={() => setCommentOpen(false)}
        type={contentType}
        contentId={contentId}
        title={item.title}
      />

      {/* Report */}
      <ReportModal
        open={reportOpen}
        onClose={() => setReportOpen(false)}
        type={reportType}
        contentId={contentId}
      />
    </>
  );
}
