"use client";

import { useEffect, useState, useRef } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { SubscriberListSheet } from "@/components/profile/SubscriberListSheet";
import {
  fetchProfile,
  fetchChannelContent,
  fetchChannelFeed,
  fetchUserRentContent,
} from "@/store/slices/profileSlice";
import { setTrack, setQueue } from "@/store/slices/playerSlice";
import { selectRentItem } from "@/store/slices/rentSlice";
import {
  formatDuration as fmtDur,
  formatViews as fmtViews,
} from "@/utils/format";
import type { MusicItem } from "@/services/musicSectionService";
import {
  RawChannelContent,
  RawFeedContent,
  RawRentContent,
} from "@/services/profileService";
import {
  formatDuration,
  formatViews,
  formatRelativeDate,
} from "@/utils/format";
import { CT } from "@/config/contentTypes";
import { contentMgmtService } from "@/services/contentActionService";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { DeleteConfirmModal } from "@/components/shared/DeleteConfirmModal";
import { PlaylistDetailModal } from "@/components/playlist/PlaylistDetailModal";
import { CreatePlaylistModal } from "@/components/playlist/CreatePlaylistModal";
import { playlistService } from "@/services/playlistService";
import Cookies from "js-cookie";
import {
  Video,
  Film,
  Music,
  Mic,
  Newspaper,
  DollarSign,
  Play,
  Heart,
  MessageCircle,
  Eye,
  Clock,
  CheckCircle,
  Edit3,
  Share2,
  PlaySquare,
  Plus,
} from "lucide-react";

/* ─── converter: RawChannelContent → MusicItem ───────────────────────────── */
function toMusicItem(raw: RawChannelContent): MusicItem {
  return {
    id: String(raw.id),
    contentType: raw.content_type,
    title: raw.title,
    thumbnail: raw.portrait_img || raw.landscape_img,
    landscapeImg: raw.landscape_img,
    audioUrl: raw.content,
    channelName: raw.channel_name,
    channelImage: raw.channel_image,
    duration:
      raw.content_duration > 0 ? formatDuration(raw.content_duration) : "",
    durationMs: raw.content_duration,
    views: formatViews(raw.total_view),
    likes: String(raw.total_like),
    category: raw.category_name,
    language: raw.language_name,
    isDownload: false,
    isRent: false,
    rentPrice: 0,
  };
}

/* ─── Tab config ──────────────────────────────────────────────────────────── */
const TABS = [
  { key: "video", label: "Videos", icon: Video, contentType: CT.VIDEO },
  { key: "music", label: "Music", icon: Music, contentType: CT.MUSIC },
  { key: "reels", label: "Reels", icon: Film, contentType: CT.REEL },
  {
    key: "playlist",
    label: "Playlist",
    icon: PlaySquare,
    contentType: CT.PLAYLIST,
  },
  { key: "podcast", label: "Podcasts", icon: Mic, contentType: CT.PODCAST },
  { key: "feeds", label: "Feeds", icon: Newspaper, contentType: null },
  { key: "rent", label: "Rented", icon: DollarSign, contentType: null },
];

/* ─── Skeleton helpers ────────────────────────────────────────────────────── */
function CardSkeleton() {
  return (
    <div
      className="rounded-xl overflow-hidden"
      style={{ background: "var(--card)" }}
    >
      <div
        className="animate-pulse"
        style={{ aspectRatio: "16/9", background: "var(--deep)" }}
      />
      <div className="p-3 flex flex-col gap-2">
        <div
          className="h-3 rounded-full animate-pulse"
          style={{ background: "var(--deep)", width: "85%" }}
        />
        <div
          className="h-2.5 rounded-full animate-pulse"
          style={{ background: "var(--deep)", width: "55%" }}
        />
      </div>
    </div>
  );
}

/* ─── Playlist card ───────────────────────────────────────────────────────── */
function PlaylistCard({
  item,
  index,
  onDeleted,
  onEdited,
}: {
  item: RawChannelContent;
  index: number;
  onDeleted: (id: string) => void;
  onEdited: (id: string, title: string) => void;
}) {
  const [showDetail, setShowDetail] = useState(false);
  const myChannelId = Cookies.get("channel_id") ?? "";
  const images: string[] =
    (item as RawChannelContent & { playlist_image?: string[] })
      .playlist_image ?? [];
  const delay = Math.min(index * 60, 600);

  const playlist = {
    id: String(item.id),
    title: item.title,
    channelId: item.channel_id || myChannelId,
    playlistType:
      (item as RawChannelContent & { playlist_type?: number }).playlist_type ??
      1,
    images,
    coverImg: images[0] || "",
  };

  return (
    <>
      <div
        className="group rounded-xl overflow-hidden cursor-pointer transition-all duration-200 hover:-translate-y-1"
        style={{
          background: "var(--card)",
          border: "1px solid var(--border)",
          animation: `prof-card-in 400ms cubic-bezier(0.16,1,0.3,1) both`,
          animationDelay: `${delay}ms`,
          opacity: 0,
        }}
        onClick={() => setShowDetail(true)}
      >
        {/* Mosaic */}
        <div
          className="relative overflow-hidden"
          style={{ aspectRatio: "16/9", background: "var(--deep)" }}
        >
          {images.length === 0 ? (
            <div className="absolute inset-0 flex items-center justify-center">
              <Play
                size={28}
                color="rgba(var(--accent-rgb),0.3)"
                strokeWidth={1.5}
              />
            </div>
          ) : images.length === 1 ? (
            <Image
              src={images[0]}
              alt={item.title}
              fill
              className="object-cover"
              unoptimized
              sizes="33vw"
            />
          ) : (
            <div className="grid grid-cols-2 w-full h-full gap-0.5">
              {Array.from({ length: 4 }).map((_, i) => (
                <div
                  key={i}
                  className="relative overflow-hidden"
                  style={{ background: "var(--deep)" }}
                >
                  {images[i] && (
                    <Image
                      src={images[i]}
                      alt=""
                      fill
                      className="object-cover"
                      unoptimized
                      sizes="16vw"
                    />
                  )}
                </div>
              ))}
            </div>
          )}
          <div
            className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
            style={{ background: "rgba(0,0,0,0.35)" }}
          >
            <span
              className="w-10 h-10 rounded-full flex items-center justify-center"
              style={{
                background: "rgba(var(--accent-rgb),0.92)",
                boxShadow: "0 4px 18px rgba(var(--accent-rgb),0.5)",
              }}
            >
              <Play size={16} fill="white" strokeWidth={0} className="ml-0.5" />
            </span>
          </div>
        </div>
        <div className="p-3">
          <p
            className="text-xs font-semibold line-clamp-2 leading-snug"
            style={{ color: "var(--text-primary)" }}
          >
            {item.title}
          </p>
          <p className="text-[10px] mt-1" style={{ color: "#555" }}>
            {images.length} item{images.length !== 1 ? "s" : ""}
          </p>
        </div>
      </div>

      {showDetail && (
        <PlaylistDetailModal
          playlist={playlist}
          onClose={() => setShowDetail(false)}
          onDeleted={(id) => {
            onDeleted(id);
            setShowDetail(false);
          }}
          onEdited={(id, title) => {
            onEdited(id, title);
          }}
        />
      )}
    </>
  );
}

function ProfileSkeleton() {
  return (
    <div>
      <div
        className="animate-pulse"
        style={{ height: 280, background: "var(--card)" }}
      />
      <div className="px-6 pb-6" style={{ marginTop: -56 }}>
        <div
          className="w-28 h-28 rounded-full animate-pulse"
          style={{ background: "var(--deep)", border: "4px solid var(--bg)" }}
        />
        <div className="mt-4 flex flex-col gap-3">
          <div
            className="h-6 w-48 rounded-full animate-pulse"
            style={{ background: "var(--card)" }}
          />
          <div
            className="h-4 w-32 rounded-full animate-pulse"
            style={{ background: "var(--card)" }}
          />
          <div className="flex gap-6 mt-2">
            {[1, 2, 3].map((i) => (
              <div key={i} className="flex flex-col gap-1">
                <div
                  className="h-5 w-10 rounded-full animate-pulse"
                  style={{ background: "var(--card)" }}
                />
                <div
                  className="h-3 w-14 rounded-full animate-pulse"
                  style={{ background: "var(--card)" }}
                />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─── Content card ────────────────────────────────────────────────────────── */
function ContentCard({
  item,
  index,
  allItems,
  onDeleted,
}: {
  item: RawChannelContent;
  index: number;
  allItems: RawChannelContent[];
  onDeleted?: (id: string) => void;
}) {
  const [hovered, setHovered] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const dispatch = useAppDispatch();
  const router = useRouter();

  const isReel = item.content_type === CT.REEL;
  const isMusic = item.content_type === CT.MUSIC;

  const handleClick = () => {
    if (isMusic) {
      dispatch(setTrack(toMusicItem(item)));
      dispatch(setQueue(allItems.map(toMusicItem)));
      return;
    }
    if (isReel) {
      router.push(`/reel/${item.id}`);
      return;
    }
    if (item.content_type === CT.PODCAST) {
      router.push(`/content/${CT.PODCAST}/${item.id}`);
      return;
    }
    router.push(`/video/${item.id}`);
  };

  /* aspect ratio: reels compact 3/4, music square, others landscape */
  const ratio = isReel ? "3/4" : isMusic ? "1/1" : "16/9";
  const img = isReel
    ? item.portrait_img || item.landscape_img
    : item.landscape_img || item.portrait_img;

  return (
    <div
      className="group rounded-xl overflow-hidden cursor-pointer"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border)",
        animation: `prof-card-in 400ms cubic-bezier(0.16,1,0.3,1) both`,
        animationDelay: `${Math.min(index * 60, 600)}ms`,
        transition:
          "border-color 200ms ease, transform 200ms ease, box-shadow 200ms ease",
      }}
      onClick={handleClick}
      onMouseEnter={(e) => {
        setHovered(true);
        (e.currentTarget as HTMLElement).style.borderColor =
          "rgba(var(--accent-rgb),0.4)";
        (e.currentTarget as HTMLElement).style.transform = "translateY(-3px)";
        (e.currentTarget as HTMLElement).style.boxShadow =
          "0 12px 32px rgba(0,0,0,0.4)";
      }}
      onMouseLeave={(e) => {
        setHovered(false);
        (e.currentTarget as HTMLElement).style.borderColor = "var(--border)";
        (e.currentTarget as HTMLElement).style.transform = "translateY(0)";
        (e.currentTarget as HTMLElement).style.boxShadow = "none";
      }}
    >
      <div className="relative overflow-hidden" style={{ aspectRatio: ratio }}>
        {img ? (
          <Image
            src={img}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300"
            style={{ transform: hovered ? "scale(1.06)" : "scale(1)" }}
            sizes="(max-width: 640px) 100vw, 33vw"
            unoptimized
          />
        ) : (
          <div
            className="absolute inset-0 flex items-center justify-center"
            style={{ background: "var(--deep)" }}
          >
            {isMusic && (
              <Music
                size={28}
                color="rgba(var(--accent-rgb),0.3)"
                strokeWidth={1.2}
              />
            )}
          </div>
        )}

        {/* Gradient overlay */}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{
            background:
              "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 50%)",
          }}
        />

        {/* Play button on hover */}
        <div
          className="absolute inset-0 flex items-center justify-center transition-opacity duration-200"
          style={{ opacity: hovered ? 1 : 0 }}
        >
          <div
            className="w-12 h-12 rounded-full flex items-center justify-center"
            style={{
              background: "rgba(var(--accent-rgb),0.9)",
              boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.5)",
            }}
          >
            <Play size={20} fill="white" className="text-[#ffffff] ml-0.5" />
          </div>
        </div>

        {/* Duration badge */}
        {item.content_duration > 0 && !isReel && (
          <span
            className="absolute bottom-2 right-2 text-[#ffffff] text-xs font-bold px-1.5 py-0.5 rounded font-mono"
            style={{ background: "rgba(0,0,0,0.85)", fontSize: "10px" }}
          >
            {formatDuration(item.content_duration)}
          </span>
        )}

        {/* Rent badge */}
        {item.is_rent === 1 && (
          <span
            className="absolute top-2 left-2 text-[#ffffff] text-xs font-bold px-2 py-0.5 rounded-full"
            style={{
              background:
                "linear-gradient(90deg,var(--accent-gold),var(--accent))",
              fontSize: "10px",
            }}
          >
            RENT
          </span>
        )}

        {/* Content type badge */}
        {item.content_type === CT.REEL && (
          <span
            className="absolute top-2 right-2 text-[#ffffff] font-black px-1.5 py-0.5 rounded"
            style={{
              background: "var(--accent)",
              fontSize: "9px",
              letterSpacing: "0.06em",
            }}
          >
            REEL
          </span>
        )}
        {item.content_type === CT.MUSIC && (
          <span
            className="absolute top-2 right-2 text-[#ffffff] font-black px-1.5 py-0.5 rounded"
            style={{
              background: "#7c3aed",
              fontSize: "9px",
              letterSpacing: "0.06em",
            }}
          >
            MUSIC
          </span>
        )}
      </div>

      <div className="p-3">
        <p
          className="text-xs font-semibold line-clamp-2 leading-snug"
          style={{ letterSpacing: "-0.01em", color: "var(--text-primary)" }}
        >
          {item.title}
        </p>
        <div className="flex items-center gap-3 mt-2" style={{ color: "#777" }}>
          <span className="flex items-center gap-1 text-xs">
            <Eye size={11} /> {formatViews(item.total_view)}
          </span>
          <span className="flex items-center gap-1 text-xs">
            <Heart size={11} /> {item.total_like}
          </span>
          <span className="flex items-center gap-1 text-xs">
            <MessageCircle size={11} /> {item.total_comment}
          </span>
        </div>
        <p className="mt-1 text-xs" style={{ color: "#555", fontSize: "10px" }}>
          {formatRelativeDate(item.created_at)}
        </p>
        {/* Delete button — only on own content */}
        {onDeleted && (
          <button
            className="mt-2 flex items-center gap-1 text-[10px] font-semibold transition-colors hover:text-red-400 active:scale-95"
            style={{ color: "#f43f5e55" }}
            onClick={(e) => {
              e.stopPropagation();
              setShowDeleteConfirm(true);
            }}
          >
            <svg
              width="10"
              height="10"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2.2"
              strokeLinecap="round"
            >
              <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
            </svg>
            Delete
          </button>
        )}
      </div>

      {showDeleteConfirm && (
        <DeleteConfirmModal
          title="Delete Content"
          description={`"${item.title}" will be permanently deleted. This cannot be undone.`}
          confirmLabel="Delete"
          onConfirm={async () => {
            await contentMgmtService.deleteContent({
              contentId: String(item.id),
              contentType: item.content_type,
            });
            onDeleted?.(String(item.id));
            setShowDeleteConfirm(false);
          }}
          onCancel={() => setShowDeleteConfirm(false)}
        />
      )}
    </div>
  );
}

/* ─── Feed post card ──────────────────────────────────────────────────────── */
function FeedCard({ item, index }: { item: RawFeedContent; index: number }) {
  const [imgIdx, setImgIdx] = useState(0);
  const images = item.feed_content.filter((c) => c.image);

  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border)",
        animation: `prof-feed-in 450ms cubic-bezier(0.16,1,0.3,1) both`,
        animationDelay: `${Math.min(index * 80, 640)}ms`,
      }}
    >
      {/* Image carousel */}
      {images.length > 0 && (
        <div
          className="relative overflow-hidden"
          style={{ aspectRatio: "4/3" }}
        >
          <Image
            src={images[imgIdx].image}
            alt="Feed"
            fill
            className="object-cover"
            sizes="(max-width: 640px) 100vw, 50vw"
            unoptimized
          />
          {images.length > 1 && (
            <>
              <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5">
                {images.map((_, i) => (
                  <button
                    key={i}
                    onClick={() => setImgIdx(i)}
                    className="rounded-full transition-all duration-150"
                    style={{
                      width: i === imgIdx ? 16 : 6,
                      height: 6,
                      background:
                        i === imgIdx ? "var(--accent)" : "var(--border)",
                    }}
                  />
                ))}
              </div>
              {imgIdx > 0 && (
                <button
                  onClick={() => setImgIdx((p) => p - 1)}
                  className="absolute left-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full flex items-center justify-center"
                  style={{ background: "rgba(0,0,0,0.55)" }}
                >
                  <svg
                    width="14"
                    height="14"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="#fff"
                    strokeWidth="2.5"
                  >
                    <polyline points="15 18 9 12 15 6" />
                  </svg>
                </button>
              )}
              {imgIdx < images.length - 1 && (
                <button
                  onClick={() => setImgIdx((p) => p + 1)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full flex items-center justify-center"
                  style={{ background: "rgba(0,0,0,0.55)" }}
                >
                  <svg
                    width="14"
                    height="14"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="#fff"
                    strokeWidth="2.5"
                  >
                    <polyline points="9 18 15 12 9 6" />
                  </svg>
                </button>
              )}
              <span
                className="absolute top-3 right-3 text-[#ffffff] font-bold text-xs px-2 py-0.5 rounded-full"
                style={{ background: "rgba(0,0,0,0.6)", fontSize: "11px" }}
              >
                {imgIdx + 1}/{images.length}
              </span>
            </>
          )}
        </div>
      )}

      <div className="p-4">
        {/* Description */}
        <p
          className="text-sm leading-relaxed line-clamp-2"
          style={{ color: "#ccc" }}
        >
          {item.description}
        </p>

        {/* Hashtags */}
        {item.hastegs.length > 0 && (
          <div className="flex flex-wrap gap-1.5 mt-2">
            {item.hastegs.slice(0, 4).map((h) => (
              <span
                key={h.id}
                className="text-xs font-medium px-2 py-0.5 rounded-full"
                style={{
                  background: "rgba(var(--accent-rgb),0.1)",
                  color: "var(--accent)",
                  fontSize: "11px",
                }}
              >
                #{h.name}
              </span>
            ))}
          </div>
        )}

        {/* Stats */}
        <div
          className="flex items-center gap-4 mt-3 pt-3"
          style={{ borderTop: "1px solid var(--border)" }}
        >
          <button
            className="flex items-center gap-1.5 text-xs transition-colors hover:text-orange-400"
            style={{ color: "#888" }}
          >
            <Heart size={14} /> {item.total_like}
          </button>
          {item.is_comment === 1 && (
            <button
              className="flex items-center gap-1.5 text-xs transition-colors hover:text-orange-400"
              style={{ color: "#888" }}
            >
              <MessageCircle size={14} /> {item.total_comment}
            </button>
          )}
          <span
            className="ml-auto flex items-center gap-1 text-xs"
            style={{ color: "#555" }}
          >
            <Clock size={11} /> {formatRelativeDate(item.created_at)}
          </span>
        </div>
      </div>
    </div>
  );
}

/* ─── Rent card ───────────────────────────────────────────────────────────── */
function RentCard({ item, index }: { item: RawRentContent; index: number }) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";

  const handleClick = () => {
    dispatch(
      selectRentItem({
        id: String(item.id),
        contentType: item.content_type,
        title: item.title,
        description: item.description || "",
        thumbnail: item.landscape_img,
        portraitImg: item.portrait_img,
        videoUrl: item.content,
        contentUploadType: item.content_upload_type,
        duration:
          item.content_duration > 0 ? fmtDur(item.content_duration) : "",
        durationMs: item.content_duration,
        views: fmtViews(item.total_view),
        likes: String(item.total_like),
        totalLike: item.total_like,
        totalDislike: item.total_dislike,
        isUserLikeDislike: item.is_user_like_dislike ?? 0,
        uploadedAt: "",
        channelName: item.channel_name,
        channelImage: item.channel_image,
        channelId: item.channel_id ?? "",
        channelUserId: String(item.user_id ?? ""),
        category: item.category_name,
        language: item.language_name,
        rentPrice: item.rent_price,
        rentDay: 0,
        isOwned: item.is_buy === 1,
        isDownload: false,
        canComment: item.is_comment === 1,
        isSubscribed: item.is_subscribe === 1,
      }),
    );
    router.push(`/rent/play/${item.id}`);
  };

  return (
    <div
      onClick={handleClick}
      className="rounded-xl overflow-hidden block group cursor-pointer"
      style={{
        background: "var(--card)",
        border: "1px solid rgba(var(--accent-gold-rgb),0.2)",
        animation: `prof-card-in 400ms cubic-bezier(0.16,1,0.3,1) both`,
        animationDelay: `${Math.min(index * 60, 480)}ms`,
        transition: "box-shadow 200ms ease, transform 200ms ease",
      }}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLElement).style.transform = "translateY(-3px)";
        (e.currentTarget as HTMLElement).style.boxShadow =
          "0 0 24px rgba(var(--accent-gold-rgb),0.2), 0 12px 32px rgba(0,0,0,0.4)";
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLElement).style.transform = "translateY(0)";
        (e.currentTarget as HTMLElement).style.boxShadow = "none";
      }}
    >
      <div className="relative overflow-hidden" style={{ aspectRatio: "16/9" }}>
        {item.landscape_img || item.portrait_img ? (
          <Image
            src={item.landscape_img || item.portrait_img}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-105"
            sizes="33vw"
            unoptimized
          />
        ) : (
          <div
            className="absolute inset-0"
            style={{ background: "var(--deep)" }}
          />
        )}
        <div
          className="absolute inset-0"
          style={{
            background:
              "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 50%)",
          }}
        />

        {/* Gold rent badge */}
        <div
          className="absolute top-2 left-2 flex items-center gap-1.5 px-2 py-1 rounded-full"
          style={{
            background:
              "linear-gradient(90deg,var(--accent-gold),var(--accent))",
            boxShadow: "0 2px 8px rgba(var(--accent-gold-rgb),0.4)",
          }}
        >
          <DollarSign size={10} className="text-[#ffffff]" />
          <span
            className="text-[#ffffff] font-black"
            style={{ fontSize: "10px" }}
          >
            {sym}
            {item.rent_price}
          </span>
        </div>

        {item.is_buy === 1 && (
          <div
            className="absolute top-2 right-2 flex items-center gap-1 px-2 py-1 rounded-full"
            style={{
              background: "rgba(34,197,94,0.2)",
              border: "1px solid rgba(34,197,94,0.4)",
            }}
          >
            <CheckCircle size={10} className="text-green-400" />
            <span
              className="text-green-400 font-bold"
              style={{ fontSize: "10px" }}
            >
              Rented
            </span>
          </div>
        )}

        {item.content_duration > 0 && (
          <span
            className="absolute bottom-2 right-2 text-[#ffffff] font-bold px-1.5 py-0.5 rounded font-mono"
            style={{ background: "rgba(0,0,0,0.85)", fontSize: "10px" }}
          >
            {formatDuration(item.content_duration)}
          </span>
        )}
      </div>

      <div className="p-3">
        <p
          className="text-xs font-semibold line-clamp-2 leading-snug"
          style={{ color: "var(--text-primary)" }}
        >
          {item.title}
        </p>
        <div className="flex items-center gap-2 mt-2" style={{ color: "#777" }}>
          <span className="flex items-center gap-1 text-xs">
            <Eye size={11} /> {formatViews(item.total_view)}
          </span>
          <span className="text-xs ml-auto" style={{ fontSize: "10px" }}>
            {formatRelativeDate(item.created_at)}
          </span>
        </div>
      </div>
    </div>
  );
}

/* ─── Empty state ─────────────────────────────────────────────────────────── */
function EmptyTab({ label }: { label: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-24 gap-4">
      <div
        className="w-20 h-20 rounded-full flex items-center justify-center"
        style={{ background: "rgba(var(--accent-rgb),0.08)" }}
      >
        <Film size={32} style={{ color: "var(--accent)", opacity: 0.5 }} />
      </div>
      <p className="text-sm font-medium" style={{ color: "#555" }}>
        No {label} yet
      </p>
    </div>
  );
}

/* ─── Main ProfilePage ────────────────────────────────────────────────────── */
export default function ProfilePage() {
  const dispatch = useAppDispatch();
  const {
    profile,
    isProfileLoading,
    contentByType,
    isContentLoading,
    feeds,
    isFeedsLoading,
    rentContent,
    isRentLoading,
  } = useAppSelector((s) => s.profile);
  const authUser = useAppSelector((s) => s.auth.user);

  const [activeTab, setActiveTab] = useState("video");
  const [indicatorStyle, setIndicatorStyle] = useState({ left: 0, width: 0 });
  const [showSubscribers, setShowSubscribers] = useState(false);
  const [showCreatePlaylist, setShowCreatePlaylist] = useState(false);
  const [deletedIds, setDeletedIds] = useState<Set<string>>(new Set());
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);

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

  /* Move indicator to active tab */
  useEffect(() => {
    const idx = TABS.findIndex((t) => t.key === activeTab);
    const el = tabRefs.current[idx];
    if (el) {
      setIndicatorStyle({ left: el.offsetLeft, width: el.offsetWidth });
    }
  }, [activeTab]);

  /* Lazy-load tab content */
  useEffect(() => {
    const tab = TABS.find((t) => t.key === activeTab);
    if (!tab) return;
    const channelId = profile?.channel_id || authUser?.channel_id || "";

    if (tab.contentType !== null) {
      if (!contentByType[tab.contentType] && channelId) {
        dispatch(
          fetchChannelContent({ channelId, contentType: tab.contentType }),
        );
      }
    } else if (tab.key === "feeds") {
      if (feeds.length === 0 && channelId)
        dispatch(fetchChannelFeed(channelId));
    } else if (tab.key === "rent") {
      if (rentContent.length === 0) dispatch(fetchUserRentContent());
    }
  }, [
    activeTab,
    profile,
    authUser,
    dispatch,
    contentByType,
    feeds.length,
    rentContent.length,
  ]);

  const displayProfile = profile;
  const displayName =
    displayProfile?.full_name || authUser?.full_name || "User";
  const channelName =
    displayProfile?.channel_name || authUser?.channel_name || "";
  const avatarUrl = displayProfile?.image || authUser?.image || "";
  const coverUrl = displayProfile?.cover_img || "";
  const description = displayProfile?.description || "";
  const totalContent = displayProfile?.total_content ?? 0;
  const totalSubscribers = displayProfile?.total_subscriber ?? 0;
  const isVerified = displayProfile?.is_account_verify === 1;

  const channelId = profile?.channel_id || authUser?.channel_id || "";

  const handlePlaylistCreated = () => {
    if (channelId) {
      dispatch(fetchChannelContent({ channelId, contentType: CT.PLAYLIST }));
    }
  };

  const currentTab = TABS.find((t) => t.key === activeTab)!;
  const currentContent: RawChannelContent[] =
    currentTab.contentType !== null
      ? contentByType[currentTab.contentType] || []
      : [];
  const isCurrentLoading =
    currentTab.contentType !== null
      ? isContentLoading
      : currentTab.key === "feeds"
        ? isFeedsLoading
        : isRentLoading;

  /* Grid columns: reels compact portrait → 3-col; music square → 2-col; others landscape → 3-col */
  const gridCols =
    activeTab === "reels"
      ? "grid-cols-3 sm:grid-cols-4 md:grid-cols-5"
      : activeTab === "music"
        ? "grid-cols-2 sm:grid-cols-5 lg:grid-cols-8"
        : "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4";

  if (isProfileLoading) return <ProfileSkeleton />;

  return (
    <>
      <div style={{ animation: "prof-content-in 400ms ease both" }}>
        {/* ── Cover banner ────────────────────────────────────────────────── */}
        <div className="relative overflow-hidden" style={{ height: 260 }}>
          {coverUrl ? (
            <Image
              src={coverUrl}
              alt="Cover"
              fill
              className="object-cover"
              style={{ animation: "prof-banner-in 600ms ease both" }}
              sizes="100vw"
              unoptimized
              priority
            />
          ) : (
            <div
              className="absolute inset-0"
              style={{
                background:
                  "linear-gradient(135deg, #10002b 0%, #240046 35%, #0f3460 65%, #1a1a2e 100%)",
                animation: "prof-banner-in 600ms ease both",
              }}
            />
          )}

          {/* Overlay gradient */}
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              background:
                "linear-gradient(to bottom, rgba(26,26,46,0.1) 0%, rgba(26,26,46,0.85) 100%)",
            }}
          />

          {/* Orange accent glow */}
          <div
            className="absolute bottom-0 left-1/2 -translate-x-1/2 pointer-events-none"
            style={{
              width: 500,
              height: 200,
              background:
                "radial-gradient(ellipse, rgba(var(--accent-rgb),0.12) 0%, transparent 70%)",
            }}
          />
        </div>

        {/* ── Profile info section ─────────────────────────────────────────── */}
        <div className="px-4 sm:px-8 pb-0" style={{ marginTop: -64 }}>
          <div className="flex flex-col sm:flex-row sm:items-end gap-5">
            {/* Avatar */}
            <div
              className="relative shrink-0"
              style={{
                animation:
                  "prof-avatar-in 500ms cubic-bezier(0.34,1.56,0.64,1) 100ms both",
              }}
            >
              <div
                className="relative rounded-full overflow-hidden"
                style={{
                  width: 112,
                  height: 112,
                  border: "4px solid var(--bg)",
                  animation: "prof-orb-pulse 3s ease-in-out infinite",
                  boxShadow: "0 0 0 3px rgba(var(--accent-rgb),0.5)",
                }}
              >
                {avatarUrl ? (
                  <Image
                    src={avatarUrl}
                    alt={displayName}
                    fill
                    className="object-cover"
                    sizes="112px"
                    unoptimized
                  />
                ) : (
                  <div
                    className="absolute inset-0 flex items-center justify-center text-3xl font-black"
                    style={{
                      background: "linear-gradient(135deg, #240046, #0f3460)",
                      color: "var(--accent)",
                    }}
                  >
                    {displayName.charAt(0).toUpperCase()}
                  </div>
                )}
              </div>
              {isVerified && (
                <div
                  className="absolute bottom-1 right-1 w-7 h-7 rounded-full flex items-center justify-center"
                  style={{
                    background: "var(--accent)",
                    border: "2px solid var(--bg)",
                  }}
                >
                  <CheckCircle size={14} className="text-[#ffffff]" />
                </div>
              )}
            </div>

            {/* Name + meta */}
            <div
              className="flex-1 min-w-0 pb-1"
              style={{ animation: "prof-content-in 450ms ease 200ms both" }}
            >
              <div className="flex items-center gap-2 flex-wrap">
                <h1
                  className="text-2xl font-black tracking-tight"
                  style={{ color: "#fff" }}
                >
                  {displayName}
                </h1>
                {isVerified && (
                  <span
                    className="text-xs font-bold px-2 py-0.5 rounded-full"
                    style={{
                      background: "rgba(var(--accent-rgb),0.15)",
                      color: "var(--accent)",
                      border: "1px solid rgba(var(--accent-rgb),0.3)",
                    }}
                  >
                    Verified
                  </span>
                )}
              </div>
              {channelName && (
                <p className="text-sm mt-0.5" style={{ color: "#888" }}>
                  {channelName}
                </p>
              )}
              {description && (
                <p
                  className="text-sm mt-2 line-clamp-2 max-w-xl"
                  style={{ color: "#aaa" }}
                >
                  {description}
                </p>
              )}
            </div>

            {/* Action buttons */}
            <div
              className="flex gap-2 sm:pb-1 shrink-0"
              style={{ animation: "prof-content-in 450ms ease 300ms both" }}
            >
              <Link
                href="/profile/edit"
                className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold transition-all duration-150 active:scale-95"
                style={{
                  background: "var(--card)",
                  border: "1px solid var(--border)",
                  color: "var(--text-primary)",
                }}
              >
                <Edit3 size={14} /> Edit Profile
              </Link>
              <button
                className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold transition-all duration-150 active:scale-95"
                style={{
                  background: "rgba(var(--accent-rgb),0.1)",
                  border: "1px solid rgba(var(--accent-rgb),0.3)",
                  color: "var(--accent)",
                }}
              >
                <Share2 size={14} />
              </button>
            </div>
          </div>

          {/* Stats row */}
          <div
            className="flex gap-8 mt-5"
            style={{ animation: "prof-stat-in 450ms ease 350ms both" }}
          >
            <div className="flex flex-col">
              <span
                className="text-2xl font-black tracking-tight"
                style={{
                  letterSpacing: "-0.03em",
                  color: "var(--text-primary)",
                }}
              >
                {totalContent >= 1000
                  ? `${(totalContent / 1000).toFixed(1)}K`
                  : totalContent}
              </span>
              <span
                className="text-xs font-medium mt-0.5"
                style={{ color: "#666" }}
              >
                Content
              </span>
            </div>
            <button
              className="flex flex-col text-left active:scale-95 transition-transform"
              onClick={() => setShowSubscribers(true)}
            >
              <span
                className="text-2xl font-black tracking-tight"
                style={{
                  letterSpacing: "-0.03em",
                  color: "var(--text-primary)",
                }}
              >
                {totalSubscribers >= 1000
                  ? `${(totalSubscribers / 1000).toFixed(1)}K`
                  : totalSubscribers}
              </span>
              <span
                className="text-xs font-medium mt-0.5"
                style={{ color: "var(--accent)" }}
              >
                Subscribers ↗
              </span>
            </button>
          </div>
        </div>

        {/* ── Tab bar ──────────────────────────────────────────────────────── */}
        <div
          className="sticky top-14 z-30 mt-6 px-4 sm:px-8"
          style={{
            background: "var(--bg)",
            borderBottom: "1px solid var(--border)",
            paddingBottom: 0,
          }}
        >
          <div
            className="relative flex gap-1 overflow-x-auto scrollbar-hide"
            style={{ animation: "prof-tab-in 300ms ease both" }}
          >
            {TABS.map((tab, i) => {
              const Icon = tab.icon;
              const isActive = activeTab === tab.key;
              return (
                <button
                  key={tab.key}
                  ref={(el) => {
                    tabRefs.current[i] = el;
                  }}
                  onClick={() => setActiveTab(tab.key)}
                  className="flex items-center gap-1.5 px-4 py-3 text-xs font-semibold whitespace-nowrap transition-colors duration-150"
                  style={{
                    color: isActive ? "var(--text-muted)" : "#666",
                    background: "transparent",
                    borderBottom: "none",
                  }}
                >
                  <Icon size={13} />
                  {tab.label}
                </button>
              );
            })}

            {/* Animated indicator */}
            <div
              className="absolute bottom-0 h-0.5 rounded-full transition-all duration-250"
              style={{
                left: indicatorStyle.left,
                width: indicatorStyle.width,
                background: "var(--accent)",
                boxShadow: "0 0 8px rgba(var(--accent-rgb),0.6)",
                transition:
                  "left 250ms cubic-bezier(0.4,0,0.2,1), width 250ms cubic-bezier(0.4,0,0.2,1)",
              }}
            />
          </div>
        </div>

        {/* ── Tab content ──────────────────────────────────────────────────── */}
        <div className="px-4 sm:px-8 py-6">
          {/* Video / Short / Music / Podcast / Playlist tabs */}
          {currentTab.contentType !== null &&
            (activeTab === "playlist" ? (
              /* Playlist tab — always shows the create card */
              isCurrentLoading ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                  <button
                    onClick={() => setShowCreatePlaylist(true)}
                    className="rounded-xl flex flex-col items-center justify-center gap-3 transition-all duration-200 hover:-translate-y-1 active:scale-95"
                    style={{
                      aspectRatio: "16/9",
                      background: "rgba(var(--accent-rgb),0.06)",
                      border: "2px dashed rgba(var(--accent-rgb),0.25)",
                    }}
                  >
                    <div
                      className="w-10 h-10 rounded-full flex items-center justify-center"
                      style={{ background: "rgba(var(--accent-rgb),0.12)" }}
                    >
                      <Plus size={20} color="var(--accent)" strokeWidth={2} />
                    </div>
                    <span
                      className="text-xs font-semibold"
                      style={{ color: "var(--accent)" }}
                    >
                      New Playlist
                    </span>
                  </button>
                  {Array.from({ length: 5 }).map((_, i) => (
                    <CardSkeleton key={i} />
                  ))}
                </div>
              ) : (
                <div
                  className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"
                  key="playlist"
                >
                  {/* Create card — always first */}
                  <button
                    onClick={() => setShowCreatePlaylist(true)}
                    className="rounded-xl flex flex-col items-center justify-center gap-3 transition-all duration-200 hover:-translate-y-1 active:scale-95"
                    style={{
                      aspectRatio: "16/9",
                      background: "rgba(var(--accent-rgb),0.06)",
                      border: "2px dashed rgba(var(--accent-rgb),0.25)",
                    }}
                  >
                    <div
                      className="w-10 h-10 rounded-full flex items-center justify-center"
                      style={{ background: "rgba(var(--accent-rgb),0.12)" }}
                    >
                      <Plus size={20} color="var(--accent)" strokeWidth={2} />
                    </div>
                    <span
                      className="text-xs font-semibold"
                      style={{ color: "var(--accent)" }}
                    >
                      New Playlist
                    </span>
                  </button>

                  {currentContent
                    .filter((item) => !deletedIds.has(String(item.id)))
                    .map((item, i) => (
                      <PlaylistCard
                        key={item.id}
                        item={item}
                        index={i}
                        onDeleted={(id) =>
                          setDeletedIds(
                            (prev) => new Set(Array.from(prev).concat(id)),
                          )
                        }
                        onEdited={(_id, _title) => {}}
                      />
                    ))}
                </div>
              )
            ) : isCurrentLoading ? (
              <div className={`grid ${gridCols} gap-4`}>
                {Array.from({ length: 8 }).map((_, i) => (
                  <CardSkeleton key={i} />
                ))}
              </div>
            ) : currentContent.length === 0 ? (
              <EmptyTab label={currentTab.label} />
            ) : (
              <div className={`grid ${gridCols} gap-4`} key={activeTab}>
                {currentContent
                  .filter((item) => !deletedIds.has(String(item.id)))
                  .map((item, i) => (
                    <ContentCard
                      key={item.id}
                      item={item}
                      index={i}
                      allItems={currentContent}
                      onDeleted={(id) =>
                        setDeletedIds(
                          (prev) => new Set(Array.from(prev).concat(id)),
                        )
                      }
                    />
                  ))}
              </div>
            ))}

          {/* Feeds tab */}
          {activeTab === "feeds" &&
            (isFeedsLoading ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                {Array.from({ length: 6 }).map((_, i) => (
                  <CardSkeleton key={i} />
                ))}
              </div>
            ) : feeds.length === 0 ? (
              <EmptyTab label="Feeds" />
            ) : (
              <div
                className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5"
                key="feeds"
              >
                {feeds.map((item, i) => (
                  <FeedCard key={item.id} item={item} index={i} />
                ))}
              </div>
            ))}

          {/* Rent tab */}
          {activeTab === "rent" &&
            (isRentLoading ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {Array.from({ length: 4 }).map((_, i) => (
                  <CardSkeleton key={i} />
                ))}
              </div>
            ) : rentContent.length === 0 ? (
              <EmptyTab label="Rented Content" />
            ) : (
              <div
                className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
                key="rent"
              >
                {rentContent.map((item, i) => (
                  <RentCard key={item.id} item={item} index={i} />
                ))}
              </div>
            ))}
        </div>
      </div>

      {showSubscribers && (
        <SubscriberListSheet onClose={() => setShowSubscribers(false)} />
      )}

      {showCreatePlaylist && (
        <CreatePlaylistModal
          channelId={channelId}
          onClose={() => setShowCreatePlaylist(false)}
          onCreated={handlePlaylistCreated}
        />
      )}
    </>
  );
}
