"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { clearReelQueue } from "@/store/slices/reelQueueSlice";
import { reelsListService } from "@/services/reelsListService";
import { ReelsPlayer } from "./ReelsPlayer";
import { GiftModal } from "./GiftModal";
import { CommentSection } from "@/components/shared/CommentSection";
import { ContentActionsModal } from "@/components/shared/ContentActionsModal";
import { CT } from "@/config/contentTypes";
import { useAddView } from "@/hooks/useAddView";
import { useLikeDislike } from "@/hooks/useLikeDislike";
import { useShare } from "@/hooks/useShare";
import type { MappedReel } from "@/services/reelsListService";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";

/* ── Shared heart SVG ────────────────────────────────────────────────────── */
const HeartSvg = ({ liked, size = 26 }: { liked: boolean; size?: number }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill={liked ? "var(--accent)" : "none"}
    stroke={liked ? "var(--accent)" : "#fff"}
    strokeWidth="1.8"
    strokeLinecap="round"
    strokeLinejoin="round"
    style={{ transition: "fill 0.2s, stroke 0.2s" }}
  >
    <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>
);

/* ── Desktop like button ─────────────────────────────────────────────────── */
function ReelLikeBtn({ reel }: { reel: MappedReel }) {
  const { liked, totalLikes, handleLike } = useLikeDislike({
    contentId: reel.id,
    contentType: reel.contentType,
    initialLikes: reel.totalLikeCount,
    initialDislikes: reel.totalDislikeCount,
    initialReaction: reel.isUserLikeDislike,
  });
  return (
    <div className="reels-action-stack" onClick={handleLike}>
      <div className="reels-action-icon">
        <HeartSvg liked={liked} size={28} />
      </div>
      <span className="reels-action-count">
        {totalLikes > 0 ? totalLikes.toLocaleString() : reel.likes}
      </span>
    </div>
  );
}

/* ── Mobile like button (inside video overlay) ───────────────────────────── */
function ReelLikeBtnMobile({ reel }: { reel: MappedReel }) {
  const { liked, totalLikes, handleLike } = useLikeDislike({
    contentId: reel.id,
    contentType: reel.contentType,
    initialLikes: reel.totalLikeCount,
    initialDislikes: reel.totalDislikeCount,
    initialReaction: reel.isUserLikeDislike,
  });
  return (
    <div className="rma-item" onClick={handleLike}>
      <div className="rma-btn">
        <HeartSvg liked={liked} size={26} />
      </div>
      <span className="rma-count">
        {(totalLikes > 0 ? totalLikes : Number(reel.likes)).toLocaleString()}
      </span>
    </div>
  );
}

const FILTERS = ["For You", "Trending", "Following"] as const;

/** Load more reels when this many items remain before the end */
const PRELOAD_THRESHOLD = 2;

/* ── skeleton ────────────────────────────────────────────────────────────── */

function ReelsPageSkeleton() {
  return (
    <div className="reels-stage">
      {/* Center column */}
      <div className="reels-reel-col">
        <div className="reels-reel-frame">
          {/* Video area */}
          <div
            className="reels-reel animate-pulse"
            style={{ background: "var(--deep)" }}
          >
            {/* shimmer overlay */}
            <div
              className="absolute inset-0"
              style={{
                background:
                  "linear-gradient(110deg, transparent 30%, rgba(255,255,255,0.04) 50%, transparent 70%)",
                backgroundSize: "200% 100%",
                animation: "shimmer 1.6s infinite linear",
              }}
            />

            {/* Bottom creator row */}
            <div className="reels-overlay" style={{ pointerEvents: "none" }}>
              <div className="reels-creator-row">
                <div
                  className="w-8 h-8 rounded-full animate-pulse"
                  style={{
                    background: "rgba(255,255,255,0.12)",
                    flexShrink: 0,
                  }}
                />
                <div
                  className="h-3 rounded-full animate-pulse"
                  style={{ background: "rgba(255,255,255,0.12)", width: 96 }}
                />
                <div
                  className="h-7 w-20 rounded-full animate-pulse"
                  style={{ background: "rgba(255,255,255,0.08)" }}
                />
              </div>
              <div className="flex flex-col gap-2 px-1 mt-3">
                <div
                  className="h-3 rounded-full animate-pulse"
                  style={{ background: "rgba(255,255,255,0.10)", width: "85%" }}
                />
                <div
                  className="h-3 rounded-full animate-pulse"
                  style={{ background: "rgba(255,255,255,0.08)", width: "60%" }}
                />
              </div>
              <div className="reels-sound mt-3">
                <div
                  className="h-3 rounded-full animate-pulse"
                  style={{ background: "rgba(255,255,255,0.08)", width: 120 }}
                />
              </div>
            </div>

            {/* Progress bar */}
            <div className="reels-progress">
              <div
                className="reels-progress-fill animate-pulse"
                style={{ width: "42%", background: "rgba(255,255,255,0.2)" }}
              />
            </div>
          </div>

          {/* Right action bar */}
          <div className="reels-actions">
            {/* Avatar */}
            <div className="reels-action-stack">
              <div
                className="w-10 h-10 rounded-full animate-pulse"
                style={{ background: "rgba(255,255,255,0.10)" }}
              />
            </div>
            {/* Action icons */}
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="reels-action-stack">
                <div
                  className="w-10 h-10 rounded-full animate-pulse"
                  style={{ background: "rgba(255,255,255,0.08)" }}
                />
                <div
                  className="h-2.5 w-8 rounded-full animate-pulse mt-1"
                  style={{ background: "rgba(255,255,255,0.06)" }}
                />
              </div>
            ))}
          </div>

          {/* Nav buttons */}
          <div className="reels-nav">
            <div
              className="reels-nav-btn animate-pulse"
              style={{ background: "rgba(255,255,255,0.06)" }}
            />
            <div
              className="reels-nav-btn animate-pulse"
              style={{ background: "rgba(255,255,255,0.06)" }}
            />
          </div>
        </div>
      </div>

      {/* Right panel */}
      <div className="reels-panel">
        <div className="reels-panel-head">
          {/* Title */}
          <div
            className="h-4 w-24 rounded-full animate-pulse"
            style={{ background: "var(--card)" }}
          />
          {/* Filter chips */}
          <div className="reels-chips">
            {FILTERS.map((f) => (
              <div
                key={f}
                className="h-7 rounded-full animate-pulse"
                style={{ width: f.length * 8 + 16, background: "var(--card)" }}
              />
            ))}
          </div>
        </div>

        {/* List cards */}
        <div className="reels-list">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="reels-list-card">
              {/* Thumb */}
              <div
                className="reels-list-thumb animate-pulse"
                style={{ background: "var(--deep)" }}
              />
              {/* Meta */}
              <div className="reels-list-meta">
                <div
                  className="h-3 rounded-full animate-pulse mb-2"
                  style={{ background: "var(--card)", width: "70%" }}
                />
                <div
                  className="h-2.5 rounded-full animate-pulse mb-1"
                  style={{ background: "var(--card)", width: "90%" }}
                />
                <div
                  className="h-2.5 rounded-full animate-pulse"
                  style={{ background: "var(--card)", width: "55%" }}
                />
                <div className="reels-list-stats mt-2">
                  <div
                    className="h-2 rounded-full animate-pulse"
                    style={{ background: "var(--card)", width: 36 }}
                  />
                  <div
                    className="h-2 rounded-full animate-pulse"
                    style={{ background: "var(--card)", width: 28 }}
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

interface ReelsPageProps {
  initialId?: string;
}

export default function ReelsPage({ initialId }: ReelsPageProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { share, copied: reelCopied } = useShare();

  const goToCreator = useCallback(
    (channelUserId: string) => {
      if (channelUserId) router.push(`/profile/${channelUserId}`);
    },
    [router],
  );

  /* snapshot queue at first render before any effects run */
  const reelQueueSelector = useAppSelector((s) => s.reelQueue);
  const initQueueRef = useRef({
    queue: reelQueueSelector.queue,
    startId: reelQueueSelector.startId,
  });

  /* local reel list — populated from queue or API */
  const [reels, setReels] = useState<MappedReel[]>([]);
  const [apiPage, setApiPage] = useState(0);
  const [apiHasMore, setApiHasMore] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  const [idx, setIdx] = useState(0);
  const [playing, setPlaying] = useState(true);
  const [muted, setMuted] = useState(false);
  const [progress, setProgress] = useState(0); // 0 → 1
  const [filter, setFilter] = useState<(typeof FILTERS)[number]>("For You");
  const [captionOpen, setCaptionOpen] = useState(false);
  const [commentReelId, setCommentReelId] = useState<string | null>(null);
  const [giftOpen, setGiftOpen] = useState(false);
  const [reelActionsOpen, setReelActionsOpen] = useState(false);
  const stageRef = useRef<HTMLDivElement>(null);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const touchStartY = useRef(0);
  const touchStartX = useRef(0);
  const touchStartTime = useRef(0);
  const isSwiping = useRef(false);

  /* fetch a page from the API and append/replace local reels */
  const fetchPage = useCallback(async (page: number) => {
    if (page === 1) setIsLoading(true);
    else setIsLoadingMore(true);
    try {
      const res = await reelsListService.getReelsList(page);
      const mapped = res.result.map(reelsListService.mapReel);
      setReels((prev) => (page === 1 ? mapped : [...prev, ...mapped]));
      setApiPage(res.current_page);
      setApiHasMore(res.more_page);
    } catch {
      /* silently ignore load-more failures */
    } finally {
      setIsLoading(false);
      setIsLoadingMore(false);
    }
  }, []);

  /* mount: use queue if available, otherwise fetch page 1 */
  useEffect(() => {
    const { queue, startId } = initQueueRef.current;
    if (queue.length > 0) {
      setReels(queue);
      setIsLoading(false);
      setApiPage(0); // not fetched from API yet
      setApiHasMore(true);
      const found = startId ? queue.findIndex((r) => r.id === startId) : -1;
      if (found >= 0) setIdx(found);
      dispatch(clearReelQueue());
    } else {
      fetchPage(1);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /* for direct /reel/[id] URL visits without a queue: seek to initialId once loaded */
  useEffect(() => {
    if (
      !initialId ||
      reels.length === 0 ||
      initQueueRef.current.queue.length > 0
    )
      return;
    const found = reels.findIndex((r) => r.id === initialId);
    if (found >= 0) setIdx(found);
  }, [initialId, reels]);

  /* load more from API when approaching the end of the current list */
  useEffect(() => {
    if (reels.length === 0 || isLoading || isLoadingMore) return;
    if (idx >= reels.length - PRELOAD_THRESHOLD && apiHasMore) {
      const nextPage = apiPage === 0 ? 1 : apiPage + 1;
      fetchPage(nextPage);
    }
  }, [
    idx,
    reels.length,
    apiHasMore,
    apiPage,
    isLoading,
    isLoadingMore,
    fetchPage,
  ]);

  /* keyboard navigation */
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "ArrowDown")
        setIdx((i) => Math.min(reels.length - 1, i + 1));
      else if (e.key === "ArrowUp") setIdx((i) => Math.max(0, i - 1));
      else if (e.key === " ") {
        e.preventDefault();
        setPlaying((p) => !p);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [reels.length]);

  /* scroll-wheel navigation */
  useEffect(() => {
    const el = stageRef.current;
    if (!el) return;
    let cooldown = false;
    const onWheel = (e: WheelEvent) => {
      if (cooldown || Math.abs(e.deltaY) < 20) return;
      cooldown = true;
      setTimeout(() => {
        cooldown = false;
      }, 380);
      if (e.deltaY > 0) setIdx((i) => Math.min(reels.length - 1, i + 1));
      else setIdx((i) => Math.max(0, i - 1));
    };
    el.addEventListener("wheel", onWheel, { passive: true });
    return () => el.removeEventListener("wheel", onWheel);
  }, [reels.length]);

  /* touch-swipe navigation (mobile) */
  useEffect(() => {
    const el = stageRef.current;
    if (!el) return;

    const onTouchStart = (e: TouchEvent) => {
      touchStartY.current = e.touches[0].clientY;
      touchStartX.current = e.touches[0].clientX;
      touchStartTime.current = Date.now();
      isSwiping.current = false;
    };

    const onTouchMove = (e: TouchEvent) => {
      const dy = Math.abs(e.touches[0].clientY - touchStartY.current);
      const dx = Math.abs(e.touches[0].clientX - touchStartX.current);
      // Mark as a vertical swipe once moved enough vertically
      if (dy > 10 && dy > dx) isSwiping.current = true;
    };

    const onTouchEnd = (e: TouchEvent) => {
      if (!isSwiping.current) return;
      const endY = e.changedTouches[0].clientY;
      const deltaY = touchStartY.current - endY; // positive = swipe up
      const elapsed = Date.now() - touchStartTime.current;
      // Min 55px swipe within 700ms
      if (Math.abs(deltaY) < 55 || elapsed > 700) return;
      if (deltaY > 0) setIdx((i) => Math.min(reels.length - 1, i + 1));
      else setIdx((i) => Math.max(0, i - 1));
    };

    el.addEventListener("touchstart", onTouchStart, { passive: true });
    el.addEventListener("touchmove", onTouchMove, { passive: true });
    el.addEventListener("touchend", onTouchEnd, { passive: true });
    return () => {
      el.removeEventListener("touchstart", onTouchStart);
      el.removeEventListener("touchmove", onTouchMove);
      el.removeEventListener("touchend", onTouchEnd);
    };
  }, [reels.length]);

  const handleListLoadMore = useCallback(() => {
    fetchPage(apiPage === 0 ? 1 : apiPage + 1);
  }, [fetchPage, apiPage]);

  const listSentinelRef = useInfiniteScroll({
    hasMore: apiHasMore,
    isLoading: isLoadingMore,
    onLoadMore: handleListLoadMore,
    rootRef: listRef,
  });

  /* reset caption on reel change */
  useEffect(() => {
    setCaptionOpen(false);
  }, [idx]);

  /* Fire add_view whenever the active reel changes — must be before any early returns */
  useAddView(3, reels[idx]?.id);

  /* ── loading / empty states ─────────────────────────────────────────── */

  if (isLoading && reels.length === 0) {
    return <ReelsPageSkeleton />;
  }

  if (!isLoading && reels.length === 0) {
    return (
      <div className="reels-stage flex items-center justify-center">
        <p className="text-sm" style={{ color: "#888" }}>
          No reels available
        </p>
      </div>
    );
  }

  const reel = reels[idx];
  if (!reel) return null;

  return (
    <div className="reels-stage" ref={stageRef}>
      {/* ── Center column ──────────────────────────────────────────────── */}
      <div className="reels-reel-col">
        <div className="reels-reel-frame">
          {/* Reel player — tap toggles play, swipe navigates */}
          <div
            className="reels-reel"
            onClick={() => {
              if (isSwiping.current) return; // ignore tap if user was swiping
              setPlaying((p) => !p);
            }}
          >
            {/* <Image
              src={reel.image}
              alt={reel.caption}
              fill
              className="object-cover"
              unoptimized
              sizes="min(520px, 100vw)"
              priority
            /> */}
            <ReelsPlayer
              url={reel.videoUrl}
              isPlaying={playing}
              muted={muted}
              setProgress={setProgress}
              videoRef={videoRef}
            />

            {/* Dark gradient overlay — matches Flutter black.withValues(alpha:0.25) */}
            <div className="reels-dark-overlay" />

            {/* Mute button */}
            <button
              className="reels-mute-btn"
              onClick={(e) => {
                e.stopPropagation();
                setMuted((m) => !m);
              }}
            >
              {muted ? (
                <svg
                  width="18"
                  height="18"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="#fff"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polygon
                    points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"
                    fill="#fff"
                    stroke="none"
                  />
                  <line x1="22" y1="9" x2="16" y2="15" />
                  <line x1="16" y1="9" x2="22" y2="15" />
                </svg>
              ) : (
                <svg
                  width="18"
                  height="18"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="#fff"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polygon
                    points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"
                    fill="#fff"
                    stroke="none"
                  />
                  <path d="M15.5 8.5a5 5 0 0 1 0 7" />
                  <path d="M19 5a9 9 0 0 1 0 14" />
                </svg>
              )}
            </button>

            {/* Big play overlay */}
            {!playing && (
              <div className="reels-bigplay">
                <svg
                  width="32"
                  height="32"
                  viewBox="0 0 24 24"
                  fill="#fff"
                  style={{ marginLeft: 4 }}
                >
                  <path d="M8 5v14l11-7z" />
                </svg>
              </div>
            )}

            {/* Bottom overlay */}
            <div className="reels-overlay">
              <div className="reels-creator-row">
                <div
                  className="reels-avatar cursor-pointer active:scale-90 transition-transform"
                  style={{ background: `hsl(${reel.hue}, 50%, 30%)` }}
                  onClick={(e) => {
                    e.stopPropagation();
                    goToCreator(reel.channelUserId);
                  }}
                >
                  {reel.channelImage ? (
                    <img
                      src={reel.channelImage}
                      alt={reel.creator}
                      className="w-full h-full object-cover rounded-full"
                    />
                  ) : (
                    reel.initial
                  )}
                </div>
                <span
                  className="reels-handle cursor-pointer hover:text-orange-400 transition-colors"
                  onClick={(e) => {
                    e.stopPropagation();
                    goToCreator(reel.channelUserId);
                  }}
                >
                  {reel.creator}
                </span>
                <button
                  className="reels-connect-btn"
                  onClick={(e) => {
                    e.stopPropagation();
                    goToCreator(reel.channelUserId);
                  }}
                >
                  View
                </button>
              </div>

              <div
                className={`reels-caption${captionOpen ? " expanded" : ""}`}
                onClick={(e) => {
                  e.stopPropagation();
                  setCaptionOpen((o) => !o);
                }}
              >
                {reel.caption}
                {!captionOpen && reel.caption.length > 80 && (
                  <span className="reels-caption-more">&nbsp;…more</span>
                )}
              </div>

              <div className="reels-sound" onClick={(e) => e.stopPropagation()}>
                <div className="reels-sound-disc" />
                <span className="reels-sound-text">{reel.sound}</span>
              </div>
            </div>

            {/* ── Mobile-only action overlay (Flutter Stack equivalent) ─────── */}
            <div
              className="reels-mobile-actions"
              onClick={(e) => e.stopPropagation()}
            >
              {/* Creator avatar */}
              <div
                className="rma-item"
                onClick={() => goToCreator(reel.channelUserId)}
              >
                <div
                  className="rma-avatar"
                  style={{ background: `hsl(${reel.hue}, 50%, 30%)` }}
                >
                  {reel.channelImage ? (
                    <img
                      src={reel.channelImage}
                      alt={reel.creator}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    reel.initial
                  )}
                </div>
              </div>

              {/* Like */}
              <ReelLikeBtnMobile key={`mob-${reel.id}`} reel={reel} />

              {/* Gift */}
              <div className="rma-item" onClick={() => setGiftOpen(true)}>
                <div className="rma-btn">
                  <svg
                    width="22"
                    height="22"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="#f59e0b"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <polyline points="20 12 20 22 4 22 4 12" />
                    <rect x="2" y="7" width="20" height="5" />
                    <line x1="12" y1="22" x2="12" y2="7" />
                    <path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z" />
                    <path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z" />
                  </svg>
                </div>
                <span className="rma-label" style={{ color: "#f59e0b" }}>
                  Gift
                </span>
              </div>

              {/* Comment */}
              <div
                className="rma-item"
                onClick={() => setCommentReelId(reel.id)}
              >
                <div className="rma-btn">
                  <svg
                    width="22"
                    height="22"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="#fff"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                  </svg>
                </div>
                <span className="rma-count">{reel.comments}</span>
              </div>

              {/* Share */}
              <div
                className="rma-item"
                onClick={() =>
                  share({
                    title: reel.caption || reel.channelName,
                    path: `/reel/${reel.id}`,
                  })
                }
              >
                <div
                  className="rma-btn"
                  style={{ color: reelCopied ? "var(--accent)" : undefined }}
                >
                  <svg
                    width="22"
                    height="22"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke={reelCopied ? "var(--accent)" : "#fff"}
                    strokeWidth="1.8"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
                    <polyline points="16 6 12 2 8 6" />
                    <line x1="12" y1="2" x2="12" y2="15" />
                  </svg>
                </div>
                <span
                  className="rma-label"
                  style={{ color: reelCopied ? "var(--accent)" : undefined }}
                >
                  {reelCopied ? "Copied!" : "Share"}
                </span>
              </div>

              {/* More */}
              <div
                className="rma-item"
                onClick={() => setReelActionsOpen(true)}
              >
                <div className="rma-btn">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff">
                    <circle cx="12" cy="5" r="1.6" />
                    <circle cx="12" cy="12" r="1.6" />
                    <circle cx="12" cy="19" r="1.6" />
                  </svg>
                </div>
              </div>
            </div>

            {/* Progress bar */}
            <div
              className="reels-progress"
              onClick={(e) => {
                e.stopPropagation();

                const rect = e.currentTarget.getBoundingClientRect();
                const percent = (e.clientX - rect.left) / rect.width;

                if (videoRef.current && videoRef.current.duration) {
                  const video = videoRef.current;

                  const newTime = percent * video.duration;

                  video.currentTime = newTime;

                  // 🔥 IMPORTANT FIX
                  if (video.paused) {
                    video.play().catch(() => { });
                  }
                }
              }}
            >
              <div
                className="reels-progress-fill"
                style={{ width: `${progress * 100}%` }}
              />
            </div>
          </div>

          {/* Right action bar */}
          <div className="reels-actions">
            <div
              className="reels-action-stack cursor-pointer"
              onClick={() => goToCreator(reel.channelUserId)}
            >
              <div className="reels-action-avatar-wrap">
                <div
                  className="reels-action-avatar transition-transform active:scale-90"
                  style={{ background: `hsl(${reel.hue}, 50%, 30%)` }}
                >
                  {reel.channelImage ? (
                    <img
                      src={reel.channelImage}
                      alt={reel.creator}
                      className="w-full h-full object-cover rounded-full"
                    />
                  ) : (
                    reel.initial
                  )}
                </div>
                <span className="reels-action-plus">+</span>
              </div>
            </div>

            {/* Like */}
            <ReelLikeBtn key={reel.id} reel={reel} />

            {/* Gift */}
            <div
              className="reels-action-stack cursor-pointer"
              onClick={() => setGiftOpen(true)}
            >
              <div className="reels-action-icon">
                <svg
                  width="26"
                  height="26"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="#fff"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polyline points="20 12 20 22 4 22 4 12" />
                  <rect x="2" y="7" width="20" height="5" />
                  <line x1="12" y1="22" x2="12" y2="7" />
                  <path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z" />
                  <path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z" />
                </svg>
              </div>
              <span
                className="reels-action-label"
                style={{ color: "#f59e0b", fontSize: "9px" }}
              >
                Gift
              </span>
            </div>

            {/* Comment */}
            <div
              className="reels-action-stack cursor-pointer"
              onClick={() => setCommentReelId(reel.id)}
            >
              <div className="reels-action-icon">
                <svg
                  width="26"
                  height="26"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="#fff"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                </svg>
              </div>
              <span className="reels-action-count">{reel.comments}</span>
            </div>

            {/* Share */}
            <div
              className="reels-action-stack cursor-pointer"
              onClick={(e) => {
                e.stopPropagation();
                share({
                  title: reel.caption || reel.channelName,
                  path: `/reel/${reel.id}`,
                });
              }}
            >
              <div className="reels-action-icon" style={{ color: "#fff" }}>
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
                  <polyline points="16 6 12 2 8 6" />
                  <line x1="12" y1="2" x2="12" y2="15" />
                </svg>
              </div>
              <span
                className="reels-action-label"
                style={{ color: reelCopied ? "var(--accent)" : undefined }}
              >
                {reelCopied ? "Copied!" : "Share"}
              </span>
            </div>

            {/* More */}
            <div
              className="reels-action-stack cursor-pointer"
              onClick={() => setReelActionsOpen(true)}
            >
              <div className="reels-action-icon">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff">
                  <circle cx="12" cy="5" r="1.6" />
                  <circle cx="12" cy="12" r="1.6" />
                  <circle cx="12" cy="19" r="1.6" />
                </svg>
              </div>
            </div>

            <div className="reels-vinyl" />
          </div>

          {/* Up / Down nav */}
          <div className="reels-nav">
            <button
              className="reels-nav-btn"
              disabled={idx === 0}
              onClick={() => setIdx(Math.max(0, idx - 1))}
            >
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <polyline points="18 15 12 9 6 15" />
              </svg>
            </button>
            <button
              className="reels-nav-btn"
              disabled={idx === reels.length - 1 && !apiHasMore}
              onClick={() => setIdx(Math.min(reels.length - 1, idx + 1))}
            >
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <polyline points="6 9 12 15 18 9" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* ── Right panel ────────────────────────────────────────────────── */}
      <div className="reels-panel">
        <div className="reels-panel-head">
          <span className="reels-panel-title">More Reels</span>
          <div className="reels-chips">
            {FILTERS.map((f) => (
              <button
                key={f}
                className={`reels-chip${filter === f ? " active" : ""}`}
                onClick={() => setFilter(f)}
              >
                {f}
              </button>
            ))}
          </div>
        </div>

        <div className="reels-list" ref={listRef}>
          {reels.map((r, i) => (
            <div
              key={r.id}
              className={`reels-list-card${i === idx ? " active" : ""}`}
              onClick={() => setIdx(i)}
            >
              <div className="reels-list-thumb">
                <Image
                  src={r.image}
                  alt={r.caption}
                  fill
                  className="object-cover"
                  unoptimized
                  sizes="110px"
                />
                <div className="reels-list-play">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="#fff">
                    <path d="M8 5v14l11-7z" />
                  </svg>
                </div>
                {i === idx && (
                  <div className="reels-list-eq">
                    <span />
                    <span />
                    <span />
                  </div>
                )}
              </div>
              <div className="reels-list-meta">
                <div className="reels-list-name">
                  {r.creator}
                  <span className="reels-list-tick">
                    <svg
                      width="8"
                      height="8"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="#fff"
                      strokeWidth="4"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <polyline points="20 6 9 17 4 12" />
                    </svg>
                  </span>
                </div>
                <div className="reels-list-cap">{r.caption}</div>
                <div className="reels-list-stats">
                  <span className="reels-list-stat">
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="#888">
                      <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                    </svg>
                    {r.likes}
                  </span>
                  <span className="reels-list-stat">
                    <svg
                      width="11"
                      height="11"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="#888"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                    </svg>
                    {r.comments}
                  </span>
                </div>
              </div>
            </div>
          ))}

          {/* Sentinel triggers next page when scrolled into view */}
          <div ref={listSentinelRef} className="h-1" />
          {isLoadingMore && (
            <div className="flex justify-center py-4">
              <div
                className="w-5 h-5 rounded-full border-2 animate-spin"
                style={{
                  borderColor: "var(--accent)",
                  borderTopColor: "transparent",
                }}
              />
            </div>
          )}
        </div>
      </div>

      {/* Comment bottom sheet */}
      {commentReelId && (
        <CommentSection
          mode="sheet"
          isOpen={!!commentReelId}
          onClose={() => setCommentReelId(null)}
          contentType={3}
          contentId={commentReelId}
          totalComments={0}
          canComment
        />
      )}

      {/* Gift modal */}
      {giftOpen && reel && (
        <GiftModal reel={reel} onClose={() => setGiftOpen(false)} />
      )}

      {/* Content actions modal (Watch Later, Playlist, Report) */}
      {reelActionsOpen && reel && (
        <ContentActionsModal
          context={{
            contentId: reel.id,
            contentType: CT.REEL,
            channelId: reel.channelId,
            channelUserId: reel.channelUserId,
            title: reel.caption,
            thumbnail: reel.image,
            channelName: reel.channelName,
          }}
          onClose={() => setReelActionsOpen(false)}
        />
      )}
    </div>
  );
}
