"use client";

import { useCallback, useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import Image from "next/image";
import {
  Heart,
  MessageCircle,
  Share2,
  ChevronLeft,
  ChevronRight,
  BadgeCheck,
  Rss,
  AlertCircle,
  X,
  Send,
  MoreHorizontal,
  Trash2,
  Flag,
  Pencil,
  Check,
  CornerDownRight,
  ChevronDown,
  Loader2,
  Plus,
} from "lucide-react";
import { MotionSection, MotionItem } from "@/components/motion/MotionSection";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchFeed, toggleLike } from "@/store/slices/feedSlice";
import {
  FeedPost,
  FeedMediaItem,
  FeedHashtag,
  FeedComment,
  feedService,
  formatlike,
} from "@/services/feedService";
import {
  reportService,
  type ReportReason,
} from "@/services/contentActionService";
import { useSubscribe } from "@/hooks/useSubscribe";
import { useShare } from "@/hooks/useShare";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import { DeleteConfirmModal } from "@/components/shared/DeleteConfirmModal";
import { useLoginPrompt } from "@/lib/LoginPromptContext";
import Cookies from "js-cookie";
import { useTranslation } from "@/i18n";

/* ─────────────────────────────────────────────────────────────────────────────
   Image carousel (per post)
───────────────────────────────────────────────────────────────────────────── */

function MediaCarousel({ media }: { media: FeedMediaItem[] }) {
  const [idx, setIdx] = useState(0);
  const n = media.length;

  const prev = useCallback(() => setIdx((i) => (i - 1 + n) % n), [n]);
  const next = useCallback(() => setIdx((i) => (i + 1) % n), [n]);

  const current = media[idx];
  if (!current) return null;

  return (
    <div
      className="relative overflow-hidden"
      style={{ background: "var(--deep)" }}
    >
      {/* Media area — square-ish ratio (4:3), max 340px */}
      <div
        className="relative w-full"
        style={{ height: "min(340px, 75vw)", minHeight: 180 }}
      >
        {current.image &&
        current.image !==
          "https://dttube.divinetechs.com/public/assets/imgs/no_img.png" ? (
          <Image
            src={current.image}
            alt=""
            fill
            className="object-cover"
            unoptimized
            sizes="(max-width: 680px) 100vw, 560px"
          />
        ) : (
          <div
            className="w-full h-full flex items-center justify-center"
            style={{ background: "var(--deep)" }}
          >
            <Rss
              size={32}
              style={{ color: "rgba(var(--accent-rgb),0.3)" }}
              strokeWidth={1.5}
            />
          </div>
        )}

        {/* Counter badge */}
        {n > 1 && (
          <div
            className="absolute top-3 right-3 text-[10px] font-bold px-2 py-0.5 rounded-full"
            style={{
              background: "rgba(0,0,0,0.65)",
              color: "white",
              backdropFilter: "blur(6px)",
            }}
          >
            {idx + 1} / {n}
          </div>
        )}

        {/* Prev / Next */}
        {n > 1 && (
          <>
            <button
              onClick={prev}
              className="absolute left-2 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full flex items-center justify-center transition-all duration-150 hover:scale-105"
              style={{
                background: "rgba(0,0,0,0.55)",
                border: "1px solid rgba(255,255,255,0.12)",
                backdropFilter: "blur(8px)",
              }}
            >
              <ChevronLeft size={15} color="white" strokeWidth={2} />
            </button>
            <button
              onClick={next}
              className="absolute right-2 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full flex items-center justify-center transition-all duration-150 hover:scale-105"
              style={{
                background: "rgba(0,0,0,0.55)",
                border: "1px solid rgba(255,255,255,0.12)",
                backdropFilter: "blur(8px)",
              }}
            >
              <ChevronRight size={15} color="white" strokeWidth={2} />
            </button>
          </>
        )}
      </div>

      {/* Dot indicators */}
      {n > 1 && (
        <div className="flex items-center justify-center gap-1.5 py-2.5">
          {Array.from({ length: n }).map((_, i) => (
            <button
              key={i}
              onClick={() => setIdx(i)}
              className="rounded-full transition-all duration-250"
              style={{
                width: i === idx ? 16 : 6,
                height: 6,
                background: i === idx ? "var(--accent)" : "var(--border)",
              }}
            />
          ))}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Expandable description with hashtags
───────────────────────────────────────────────────────────────────────────── */

const DESC_LIMIT = 180;

function PostDescription({
  text,
  hashtags,
}: {
  text: string;
  hashtags: FeedHashtag[];
}) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(false);
  const isTruncatable = text.length > DESC_LIMIT;
  const displayed =
    expanded || !isTruncatable ? text : text.slice(0, DESC_LIMIT) + "…";

  // Strip inline #tags from description body
  const clean = displayed.replace(/#\w+/g, "").trim();

  return (
    <div className="px-4 pb-2">
      <p
        className="text-sm leading-relaxed"
        style={{ color: "var(--text-primary)" }}
      >
        {clean}
        {!expanded && isTruncatable && (
          <button
            className="ml-1 font-semibold text-[12px] transition-colors"
            style={{ color: "var(--accent)" }}
            onClick={() => setExpanded(true)}
          >
            {t("feeds_more")}
          </button>
        )}
      </p>

      {/* Hashtag pills */}
      {hashtags.length > 0 && (
        <div className="flex flex-wrap gap-1.5 mt-2.5">
          {hashtags.map((h) => (
            <span
              key={h.id}
              className="text-[11px] font-semibold px-2 py-0.5 rounded-full cursor-pointer transition-all duration-150 hover:brightness-110 active:scale-95"
              style={{
                background: "rgba(var(--accent-rgb),0.1)",
                color: "var(--accent)",
                border: "1px solid rgba(var(--accent-rgb),0.2)",
              }}
            >
              #{h.name}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Feed comment sheet — uses get_feed_comment + add_feed_comment APIs
───────────────────────────────────────────────────────────────────────────── */

/* ── Single feed comment row with edit / delete / reply ─────────────────── */

function FeedCommentRow({
  c,
  myUserId,
  feedId,
  onDelete,
  onUpdate,
  onAddReply,
}: {
  c: FeedComment;
  myUserId: string;
  feedId: string;
  onDelete: (id: string) => void;
  onUpdate: (id: string, text: string) => void;
  onAddReply: (reply: FeedComment) => void;
}) {
  const isOwn = c.userId === myUserId;
  const { t } = useTranslation();
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(c.comment);
  const [savingEdit, setSavingEdit] = useState(false);
  const [showReplyInput, setShowReplyInput] = useState(false);
  const [replyText, setReplyText] = useState("");
  const [showReplies, setShowReplies] = useState(false);
  const [replies, setReplies] = useState<FeedComment[]>([]);
  const [loadingReplies, setLoadingReplies] = useState(false);

  const handleSaveEdit = async () => {
    if (!editText.trim() || savingEdit) return;
    setSavingEdit(true);
    try {
      await feedService.editFeedComment({
        commentId: c.id,
        comment: editText.trim(),
      });
      onUpdate(c.id, editText.trim());
      setIsEditing(false);
    } catch {
      /* silently */
    }
    setSavingEdit(false);
  };

  const handleDelete = async () => {
    try {
      await feedService.deleteFeedComment(c.id);
      onDelete(c.id);
    } catch {
      /* */
    }
  };

  const handleShowReplies = async () => {
    const next = !showReplies;
    setShowReplies(next);
    if (next && replies.length === 0 && c.totalReply > 0) {
      setLoadingReplies(true);
      feedService
        .getFeedReplies(c.id)
        .then(setReplies)
        .finally(() => setLoadingReplies(false));
    }
  };

  const handleReply = async () => {
    if (!replyText.trim()) return;
    const opt: FeedComment = {
      id: `opt-${Date.now()}`,
      feedId,
      userId: myUserId,
      parentId: c.id,
      channelName: "You",
      avatar: "",
      comment: replyText.trim(),
      createdAt: "just now",
      totalReply: 0,
    };
    setReplies((prev) => [...prev, opt]);
    setReplyText("");
    setShowReplyInput(false);
    setShowReplies(true);
    onAddReply(opt);
    try {
      await feedService.addFeedComment({
        feedId,
        comment: opt.comment,
        commentId: c.id,
      });
    } catch {
      setReplies((prev) => prev.filter((r) => r.id !== opt.id));
    }
  };

  return (
    <div>
      <div className="flex items-start gap-2.5 py-2">
        <div
          className="w-8 h-8 rounded-full shrink-0 flex items-center justify-center text-xs font-bold overflow-hidden"
          style={{ background: "var(--deep)", color: "var(--text-primary)" }}
        >
          {c.avatar ? (
            <img src={c.avatar} alt="" className="w-full h-full object-cover" />
          ) : (
            (c.channelName[0] || "U").toUpperCase()
          )}
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-baseline gap-2 mb-0.5">
            <span
              className="text-[12px] font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              {c.channelName}
            </span>
            <span className="text-[10px]" style={{ color: "#555" }}>
              {c.createdAt}
            </span>
          </div>
          {isEditing ? (
            <div>
              <textarea
                className="w-full bg-transparent text-[12px] outline-none rounded-xl px-3 py-2 resize-none"
                style={{
                  color: "var(--text-primary)",
                  border: "1px solid rgba(var(--accent-rgb),0.4)",
                  background: "var(--deep)",
                  minHeight: 56,
                }}
                value={editText}
                onChange={(e) => setEditText(e.target.value)}
                autoFocus
              />
              <div className="flex gap-2 mt-1.5">
                <button
                  onClick={handleSaveEdit}
                  disabled={savingEdit}
                  className="flex items-center gap-1 text-[10px] font-bold px-2.5 py-1 rounded-full active:scale-95 disabled:opacity-40"
                  style={{
                    background: "rgba(var(--accent-rgb),0.15)",
                    color: "var(--accent)",
                  }}
                >
                  {savingEdit ? (
                    <Loader2 size={9} className="animate-spin" />
                  ) : (
                    <Check size={9} strokeWidth={2.5} />
                  )}
                  {savingEdit ? "…" : t("feeds_save")}
                </button>
                <button
                  onClick={() => {
                    setIsEditing(false);
                    setEditText(c.comment);
                  }}
                  className="text-[10px] px-2.5 py-1 rounded-full"
                  style={{ color: "#666" }}
                >
                  {t("subscriptions_cancel")}
                </button>
              </div>
            </div>
          ) : (
            <p
              className="text-[12px] leading-relaxed"
              style={{ color: "var(--text-primary)" }}
            >
              {c.comment}
            </p>
          )}
          {!isEditing && (
            <div className="flex items-center gap-3 mt-1">
              <button
                className="flex items-center gap-1 text-[10px] transition-colors"
                style={{ color: "#666" }}
                onClick={() => setShowReplyInput((v) => !v)}
              >
                <CornerDownRight size={10} strokeWidth={2} /> {t("feeds_reply")}
              </button>
              {c.totalReply > 0 && (
                <button
                  className="flex items-center gap-1 text-[10px]"
                  style={{ color: "var(--accent)" }}
                  onClick={handleShowReplies}
                >
                  <ChevronDown
                    size={10}
                    strokeWidth={2}
                    style={{
                      transform: showReplies ? "rotate(180deg)" : "none",
                      transition: "transform 0.2s",
                    }}
                  />
                  {showReplies
                    ? t("feeds_hide")
                    : `${c.totalReply} repl${c.totalReply === 1 ? "y" : "ies"}`}
                </button>
              )}
              {isOwn && (
                <>
                  <button
                    className="text-[10px] flex items-center gap-1 transition-colors"
                    style={{ color: "#666" }}
                    onClick={() => setIsEditing(true)}
                  >
                    <Pencil size={9} strokeWidth={2} /> {t("feeds_edit")}
                  </button>
                  <button
                    className="text-[10px] flex items-center gap-1 transition-colors"
                    style={{ color: "#f43f5e66" }}
                    onClick={handleDelete}
                  >
                    <Trash2 size={9} strokeWidth={2} /> {t("feeds_delete")}
                  </button>
                </>
              )}
            </div>
          )}
          {showReplyInput && (
            <div className="flex items-center gap-2 mt-2">
              <input
                className="flex-1 bg-transparent outline-none text-[11px] rounded-full px-3 py-1.5"
                style={{
                  color: "var(--text-primary)",
                  border: "1px solid var(--border)",
                  background: "var(--deep)",
                }}
                placeholder={`Reply to ${c.channelName}…`}
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") handleReply();
                }}
                autoFocus
              />
              <button
                onClick={handleReply}
                disabled={!replyText.trim()}
                className="active:scale-90 disabled:opacity-30"
              >
                <Send
                  size={13}
                  color={replyText.trim() ? "var(--accent)" : "#555"}
                />
              </button>
            </div>
          )}
          {showReplies && (
            <div
              className="mt-2 pl-3"
              style={{ borderLeft: "1px solid var(--border)" }}
            >
              {loadingReplies ? (
                <div className="flex justify-center py-2">
                  <Loader2
                    size={14}
                    className="animate-spin"
                    color="rgba(var(--accent-rgb),0.5)"
                  />
                </div>
              ) : (
                replies.map((r) => (
                  <div key={r.id} className="flex items-start gap-2 py-1.5">
                    <div
                      className="w-6 h-6 rounded-full shrink-0 flex items-center justify-center text-[10px] font-bold overflow-hidden"
                      style={{
                        background: "var(--deep)",
                        color: "var(--text-primary)",
                      }}
                    >
                      {r.avatar ? (
                        <img
                          src={r.avatar}
                          alt=""
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        (r.channelName[0] || "U").toUpperCase()
                      )}
                    </div>
                    <div>
                      <span
                        className="text-[11px] font-bold mr-1.5"
                        style={{ color: "var(--text-primary)" }}
                      >
                        {r.channelName}
                      </span>
                      <span
                        className="text-[11px]"
                        style={{ color: "var(--text-primary)" }}
                      >
                        {r.comment}
                      </span>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function FeedCommentSheet({
  feedId,
  onClose,
}: {
  feedId: string;
  onClose: () => void;
}) {
  const [comments, setComments] = useState<FeedComment[]>([]);
  const [loading, setLoading] = useState(true);
  const [text, setText] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { t } = useTranslation();
  const myUserId = Cookies.get("user_id") ?? "";

  useEffect(() => {
    document.body.style.overflow = "hidden";
    feedService
      .getFeedComments(feedId)
      .then(setComments)
      .catch(() => {})
      .finally(() => setLoading(false));
    return () => {
      document.body.style.overflow = "";
    };
  }, [feedId]);

  const handleSubmit = async () => {
    if (!text.trim() || submitting) return;
    setSubmitting(true);
    const opt: FeedComment = {
      id: `opt-${Date.now()}`,
      feedId,
      userId: myUserId,
      parentId: "0",
      channelName: "You",
      avatar: "",
      comment: text.trim(),
      createdAt: "just now",
      totalReply: 0,
    };
    setComments((prev) => [opt, ...prev]);
    setText("");
    try {
      await feedService.addFeedComment({ feedId, comment: opt.comment });
    } catch {
      setComments((prev) => prev.filter((c) => c.id !== opt.id));
    }
    setSubmitting(false);
  };

  const topLevel = comments.filter((c) => c.parentId === "0");

  return createPortal(
    <>
      <div
        className="fixed inset-0 z-[200]"
        style={{ background: "rgba(0,0,0,0.72)", backdropFilter: "blur(8px)" }}
        onClick={onClose}
      />
      <div
        className="fixed z-[201] bottom-0 left-0 right-0 flex flex-col"
        style={{
          maxWidth: "680px",
          margin: "0 auto",
          maxHeight: "82vh",
          background: "var(--sheet-bg)",
          borderRadius: "20px 20px 0 0",
          border: "1px solid var(--sheet-border)",
          borderBottom: "none",
          animation: "feed-cs-up 0.35s cubic-bezier(0.32,1.2,0.56,1) both",
        }}
      >
        <div className="flex justify-center pt-2.5">
          <div
            className="w-9 h-[3px] rounded-full"
            style={{ background: "var(--sheet-handle)" }}
          />
        </div>
        <div
          className="flex items-center justify-between px-5 py-3 shrink-0"
          style={{ borderBottom: "1px solid var(--border)" }}
        >
          <span
            className="text-sm font-bold"
            style={{ color: "var(--text-primary)" }}
          >
            {t("feeds_comments")}{" "}
            {topLevel.length > 0 && `· ${topLevel.length}`}
          </span>
          <button
            onClick={onClose}
            className="w-7 h-7 rounded-full flex items-center justify-center"
            style={{ background: "var(--btn-ghost-hover)" }}
          >
            <X size={13} color="#888" />
          </button>
        </div>
        <div
          className="flex-1 overflow-y-auto px-4 pt-1 pb-2"
          style={{ scrollbarWidth: "none" }}
        >
          {loading ? (
            <div className="flex justify-center py-8">
              <Loader2
                size={20}
                className="animate-spin"
                color="rgba(var(--accent-rgb),0.6)"
              />
            </div>
          ) : topLevel.length === 0 ? (
            <p className="text-center py-8 text-xs" style={{ color: "#555" }}>
              {t("feeds_noComments")}
            </p>
          ) : (
            <div
              className="flex flex-col divide-y"
              style={{ borderColor: "var(--border-soft)" }}
            >
              {topLevel.map((c) => (
                <FeedCommentRow
                  key={c.id}
                  c={c}
                  myUserId={myUserId}
                  feedId={feedId}
                  onDelete={(id) =>
                    setComments((prev) => prev.filter((x) => x.id !== id))
                  }
                  onUpdate={(id, txt) =>
                    setComments((prev) =>
                      prev.map((x) =>
                        x.id === id ? { ...x, comment: txt } : x,
                      ),
                    )
                  }
                  onAddReply={(r) => setComments((prev) => [...prev, r])}
                />
              ))}
            </div>
          )}
        </div>
        <div
          className="px-4 pb-6 pt-2 shrink-0"
          style={{ borderTop: "1px solid var(--border)" }}
        >
          <div
            className="flex items-center gap-2 px-3 py-2 rounded-2xl"
            style={{
              background: "var(--deep)",
              border: "1px solid var(--border)",
            }}
          >
            <input
              className="flex-1 bg-transparent outline-none text-[12px]"
              style={{ color: "var(--text-primary)" }}
              placeholder={t("feeds_writeComment")}
              value={text}
              onChange={(e) => setText(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  handleSubmit();
                }
              }}
            />
            <button
              onClick={handleSubmit}
              disabled={!text.trim() || submitting}
              className="active:scale-90 disabled:opacity-30 transition-all"
            >
              {submitting ? (
                <Loader2
                  size={14}
                  className="animate-spin"
                  color="var(--accent)"
                />
              ) : (
                <Send
                  size={14}
                  color={text.trim() ? "var(--accent)" : "#555"}
                  strokeWidth={2}
                />
              )}
            </button>
          </div>
        </div>
      </div>
      <style>{`@keyframes feed-cs-up { from{transform:translateY(100%)} to{transform:translateY(0)} }`}</style>
    </>,
    document.body,
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Feed post card
───────────────────────────────────────────────────────────────────────────── */

function PostCard({
  post,
  index,
  onDeleted,
}: {
  post: FeedPost;
  index: number;
  onDeleted?: (id: string) => void;
}) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { t } = useTranslation();
  const { open: openLoginPrompt } = useLoginPrompt();
  const myUserId = Cookies.get("user_id") ?? "";
  const isOwn = !!myUserId && post.userId === myUserId;
  const [likeAnimating, setLikeAnimating] = useState(false);
  const [commentOpen, setCommentOpen] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showReportModal, setShowReportModal] = useState(false);
  const [reportReasons, setReportReasons] = useState<ReportReason[]>([]);
  const [reportStep, setReportStep] = useState<"reasons" | "message">(
    "reasons",
  );
  const { share, copied: feedCopied } = useShare();
  const [selectedReason, setSelectedReason] = useState<ReportReason | null>(
    null,
  );
  const [reportMsg, setReportMsg] = useState("");
  const [submittingReport, setSubmittingReport] = useState(false);
  void index; // stagger handled by MotionItem wrapper

  const {
    subscribed,
    loading: subLoading,
    toggle: toggleSubscribe,
  } = useSubscribe(post.userId, post.isSubscriber, post.userType);

  const handleLike = async () => {
    if (!myUserId) {
      openLoginPrompt();
      return;
    }
    dispatch(toggleLike(post.id));
    const newLiked = !post.isLiked;
    if (newLiked) {
      setLikeAnimating(true);
      setTimeout(() => setLikeAnimating(false), 400);
    }
    try {
      await feedService.likeUnlikeFeed(post.id);
    } catch {
      dispatch(toggleLike(post.id));
    }
  };

  const handleCommentOpen = () => {
    if (!myUserId) {
      openLoginPrompt();
      return;
    }
    setCommentOpen(true);
  };

  return (
    <>
      <article
        className="rounded-2xl w-full max-w-4xl mx-auto"
        style={{
          background: "var(--card)",
          border: "1px solid var(--border-soft)",
          boxShadow: "0 2px 16px rgba(0,0,0,0.22)",
          overflow: "visible",
        }}
      >
        {/* ── Header ──────────────────────────────────────────────────────── */}
        <div className="flex items-center justify-between px-4 py-3.5">
          <div className="flex items-center gap-3 min-w-0">
            {/* Avatar */}
            <div
              className="relative w-10 h-10 rounded-full overflow-hidden shrink-0"
              style={{
                border: "2px solid rgba(var(--accent-rgb),0.45)",
                background: "var(--deep)",
                boxShadow: "0 0 0 3px rgba(var(--accent-rgb),0.08)",
              }}
            >
              {post.profileImg ? (
                <Image
                  src={post.profileImg}
                  alt={post.channelName}
                  fill
                  className="object-cover"
                  unoptimized
                  sizes="40px"
                />
              ) : (
                <div
                  className="w-full h-full flex items-center justify-center text-sm font-black"
                  style={{
                    background: "var(--deep)",
                    color: "var(--text-primary)",
                  }}
                >
                  {post.channelName[0]?.toUpperCase()}
                </div>
              )}
            </div>

            {/* Name + time */}
            <div className="min-w-0">
              <div className="flex items-center gap-1.5">
                <p
                  className="text-[13px] font-bold truncate leading-tight"
                  style={{ color: "var(--text-primary)" }}
                >
                  {post.channelName}
                </p>
                {post.isSubscriber && (
                  <BadgeCheck
                    size={13}
                    style={{ color: "var(--accent)", flexShrink: 0 }}
                    strokeWidth={2}
                  />
                )}
              </div>
              <p className="text-[10px] mt-0.5" style={{ color: "#666" }}>
                {post.createdAt}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2 shrink-0">
            {/* Subscribe */}
            {!isOwn && (
              <button
                onClick={toggleSubscribe}
                disabled={subLoading}
                className="text-[10px] font-bold px-3 py-1.5 rounded-full transition-all duration-150 active:scale-95 disabled:opacity-50"
                style={
                  subscribed
                    ? {
                        background: "rgba(var(--accent-rgb),0.08)",
                        color: "rgba(var(--accent-rgb),0.7)",
                        border: "1px solid rgba(var(--accent-rgb),0.15)",
                      }
                    : {
                        background: "rgba(var(--accent-rgb),0.12)",
                        color: "var(--accent)",
                        border: "1px solid rgba(var(--accent-rgb),0.25)",
                      }
                }
              >
                {subLoading
                  ? "…"
                  : subscribed
                    ? t("feeds_subscribed")
                    : t("feeds_subscribe")}
              </button>
            )}
            {/* 3-dot menu */}
            <div className="relative">
              <button
                onClick={() => setShowMenu((v) => !v)}
                className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:bg-white/10 active:scale-90"
                style={{ background: "var(--btn-ghost)" }}
              >
                <MoreHorizontal size={13} color="#888" />
              </button>
              {showMenu && (
                <div
                  className="absolute right-0 top-8 z-50 flex flex-col min-w-[140px] rounded-xl overflow-hidden"
                  style={{
                    background: "var(--card)",
                    border: "1px solid var(--border)",
                    boxShadow: "0 8px 28px rgba(0,0,0,0.5)",
                    animation: "feed-menu-in 0.2s ease both",
                  }}
                  onMouseLeave={() => setShowMenu(false)}
                >
                  {isOwn ? (
                    <button
                      className="flex items-center gap-2.5 px-4 py-3 text-[12px] font-semibold text-left transition-all hover:bg-white/5 active:scale-95 w-full"
                      style={{ color: "#f43f5e" }}
                      onClick={() => {
                        setShowMenu(false);
                        setShowDeleteConfirm(true);
                      }}
                    >
                      <Trash2 size={13} strokeWidth={2} />{" "}
                      {t("feeds_deletePost")}
                    </button>
                  ) : (
                    <button
                      className="flex items-center gap-2.5 px-4 py-3 text-[12px] font-semibold text-left transition-all hover:bg-white/5 active:scale-95 w-full"
                      style={{ color: "#aaa" }}
                      onClick={() => {
                        setShowMenu(false);
                        setReportStep("reasons");
                        setSelectedReason(null);
                        setReportMsg("");
                        reportService
                          .getReasons()
                          .then(setReportReasons)
                          .catch(() => {});
                        setShowReportModal(true);
                      }}
                    >
                      <Flag size={13} strokeWidth={2} /> {t("feeds_reportPost")}
                    </button>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* ── Media ─────────────────────────────────────────────────────── */}
        {post.media.length > 0 && (
          <div style={{ overflow: "hidden" }}>
            <MediaCarousel media={post.media} />
          </div>
        )}

        {/* ── Like count ────────────────────────────────────────────────── */}
        {post.totalLikes > 0 && (
          <div className="px-4 pt-3 pb-1">
            <div className="flex items-center gap-1.5">
              <Heart
                size={13}
                fill="var(--accent)"
                strokeWidth={0}
                style={{ color: "var(--accent)" }}
              />
              <span
                className="text-[12px] font-semibold"
                style={{ color: "var(--text-muted)" }}
              >
                {formatlike(post.totalLikes)}{" "}
                {post.totalLikes === 1
                  ? t("feeds_like_singular")
                  : t("feeds_like_plural")}
              </span>
            </div>
          </div>
        )}

        {/* ── Description + hashtags ────────────────────────────────────── */}
        {post.description && (
          <PostDescription text={post.description} hashtags={post.hashtags} />
        )}
        <button
          onClick={() => router.push(`/feed/${post.id}`)}
          className="mx-4 mb-2 text-[10px] font-semibold transition-colors"
          style={{ color: "#555" }}
        >
          {t("feeds_viewFull")}
        </button>

        {/* Divider */}
        <div
          className="mx-4 my-1"
          style={{ height: 1, background: "var(--border-soft)" }}
        />

        {/* ── Action bar ────────────────────────────────────────────────── */}
        <div className="flex items-center px-2 py-1.5">
          {/* Like */}
          <button
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl transition-all duration-150 active:scale-95 flex-1 justify-center"
            style={{
              color: post.isLiked ? "var(--accent)" : "#888",
              background: "transparent",
            }}
            onMouseEnter={(e) =>
              ((e.currentTarget as HTMLElement).style.background =
                "rgba(var(--accent-rgb),0.07)")
            }
            onMouseLeave={(e) =>
              ((e.currentTarget as HTMLElement).style.background =
                "transparent")
            }
            onClick={handleLike}
          >
            <Heart
              size={17}
              fill={post.isLiked ? "var(--accent)" : "none"}
              strokeWidth={post.isLiked ? 0 : 1.8}
              style={{
                color: post.isLiked ? "var(--accent)" : "#888",
                animation: likeAnimating ? "heart-pop 0.38s ease" : "none",
              }}
            />
            <span className="text-[12px] font-semibold">{t("feeds_like")}</span>
          </button>

          {/* Comment */}
          {post.canComment && (
            <button
              className="flex items-center gap-1.5 px-3 py-2 rounded-xl transition-all duration-150 active:scale-95 flex-1 justify-center"
              style={{ color: commentOpen ? "var(--accent)" : "#888" }}
              onMouseEnter={(e) =>
                ((e.currentTarget as HTMLElement).style.background =
                  "var(--btn-ghost)")
              }
              onMouseLeave={(e) =>
                ((e.currentTarget as HTMLElement).style.background =
                  "transparent")
              }
              onClick={handleCommentOpen}
            >
              <MessageCircle size={17} strokeWidth={1.8} />
              <span className="text-[12px] font-semibold">
                {post.totalComments > 0
                  ? post.totalComments
                  : t("feeds_comment")}
              </span>
            </button>
          )}

          {/* Feed comment sheet */}
          {post.canComment && commentOpen && (
            <FeedCommentSheet
              feedId={post.id}
              onClose={() => setCommentOpen(false)}
            />
          )}

          {/* Share */}
          <button
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl transition-all duration-150 active:scale-95 flex-1 justify-center"
            style={{ color: feedCopied ? "var(--accent)" : "#888" }}
            onClick={() =>
              share({
                title: post.title || post.channelName || "Post",
                path: `/feed/${post.id} ${post.channelName}`,
              })
            }
            onMouseEnter={(e) =>
              ((e.currentTarget as HTMLElement).style.background =
                "var(--btn-ghost)")
            }
            onMouseLeave={(e) =>
              ((e.currentTarget as HTMLElement).style.background =
                "transparent")
            }
          >
            <Share2 size={17} strokeWidth={1.8} />
            <span className="text-[12px] font-semibold">
              {feedCopied ? t("feeds_copied") : t("feeds_share")}
            </span>
          </button>
        </div>

        {/* Delete feed confirm */}
        {showDeleteConfirm && (
          <DeleteConfirmModal
            title="Delete Post"
            description="This post will be permanently deleted and cannot be recovered."
            confirmLabel="Delete"
            onConfirm={async () => {
              await feedService.deleteFeed(post.id);
              setShowDeleteConfirm(false);
              onDeleted?.(post.id);
            }}
            onCancel={() => setShowDeleteConfirm(false)}
          />
        )}

        <style>{`
        @keyframes feed-menu-in { from{opacity:0;transform:scale(0.9) translateY(-6px)} to{opacity:1;transform:scale(1) translateY(0)} }
      `}</style>
      </article>

      {showReportModal &&
        createPortal(
          <>
            <div
              className="fixed inset-0 z-[200]"
              style={{
                background: "rgba(0,0,0,0.74)",
                backdropFilter: "blur(10px)",
              }}
              onClick={() => {
                setShowReportModal(false);
                setReportStep("reasons");
                setReportMsg("");
              }}
            />
            <div
              className="fixed z-[201] bottom-0 left-0 right-0 flex flex-col"
              style={{
                maxWidth: "680px",
                margin: "0 auto",
                maxHeight: "80vh",
                background: "var(--sheet-bg)",
                borderRadius: "20px 20px 0 0",
                border: "1px solid var(--sheet-border)",
                borderBottom: "none",
                animation:
                  "feed-cs-up 0.35s cubic-bezier(0.32,1.2,0.56,1) both",
              }}
            >
              <div className="flex justify-center pt-2.5">
                <div
                  className="w-9 h-[3px] rounded-full"
                  style={{ background: "var(--sheet-handle)" }}
                />
              </div>
              <div
                className="flex items-center gap-3 px-5 py-3 shrink-0"
                style={{ borderBottom: "1px solid var(--border)" }}
              >
                {reportStep === "message" && (
                  <button
                    onClick={() => setReportStep("reasons")}
                    className="w-7 h-7 rounded-full flex items-center justify-center"
                    style={{ background: "var(--btn-ghost-hover)" }}
                  >
                    <svg
                      width="12"
                      height="12"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="#aaa"
                      strokeWidth="2.5"
                      strokeLinecap="round"
                    >
                      <polyline points="15 18 9 12 15 6" />
                    </svg>
                  </button>
                )}
                <span
                  className="text-sm font-bold flex-1"
                  style={{ color: "var(--text-primary)" }}
                >
                  {reportStep === "reasons"
                    ? "Report Post"
                    : selectedReason?.reason}
                </span>
                <button
                  onClick={() => {
                    setShowReportModal(false);
                    setReportStep("reasons");
                    setReportMsg("");
                  }}
                  className="w-7 h-7 rounded-full flex items-center justify-center"
                  style={{ background: "var(--btn-ghost-hover)" }}
                >
                  <X size={13} color="#888" />
                </button>
              </div>
              <div className="flex-1 overflow-y-auto">
                {reportStep === "reasons" ? (
                  <div className="py-1">
                    {reportReasons.map((r) => (
                      <button
                        key={r.id}
                        onClick={() => {
                          setSelectedReason(r);
                          setReportStep("message");
                        }}
                        className="flex items-center gap-3 px-5 py-3.5 w-full text-left transition-all hover:bg-black/5 dark:hover:bg-white/5 active:scale-[0.98]"
                      >
                        <div
                          className="w-1.5 h-1.5 rounded-full"
                          style={{ background: "rgba(244,63,94,0.6)" }}
                        />
                        <span
                          className="text-[13px]"
                          style={{ color: "var(--text-primary)" }}
                        >
                          {r.reason}
                        </span>
                        <svg
                          className="ml-auto"
                          width="12"
                          height="12"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="#444"
                          strokeWidth="2"
                          strokeLinecap="round"
                        >
                          <polyline points="9 18 15 12 9 6" />
                        </svg>
                      </button>
                    ))}
                  </div>
                ) : (
                  <div className="px-5 py-4 flex flex-col gap-4">
                    <textarea
                      className="w-full px-4 py-3 rounded-xl text-sm outline-none resize-none"
                      style={{
                        color: "var(--text-primary)",
                        background: "var(--deep)",
                        border: "1.5px solid rgba(244,63,94,0.35)",
                        caretColor: "#f43f5e",
                        minHeight: 80,
                      }}
                      placeholder={t("feeds_describeIssue")}
                      value={reportMsg}
                      onChange={(e) => setReportMsg(e.target.value)}
                      autoFocus
                    />
                    <button
                      disabled={!reportMsg.trim() || submittingReport}
                      onClick={async () => {
                        setSubmittingReport(true);
                        try {
                          await feedService.reportFeed({
                            reportUserId: post.userId,
                            feedId: post.id,
                            message: `${selectedReason?.reason}: ${reportMsg.trim()}`,
                          });
                          setShowReportModal(false);
                          setReportStep("reasons");
                          setReportMsg("");
                        } catch {
                          /* */
                        }
                        setSubmittingReport(false);
                      }}
                      className="w-full h-12 rounded-xl text-sm font-black text-[#ffffff] flex items-center justify-center gap-2 active:scale-[0.98] disabled:opacity-30"
                      style={{
                        background: "linear-gradient(135deg,#f43f5e,#dc2626)",
                        boxShadow: "0 4px 20px rgba(244,63,94,0.3)",
                      }}
                    >
                      {submittingReport ? (
                        <Loader2 size={16} className="animate-spin" />
                      ) : (
                        <>
                          <Flag size={15} strokeWidth={2.5} />{" "}
                          {t("feeds_submitReport")}
                        </>
                      )}
                    </button>
                  </div>
                )}
              </div>
            </div>
          </>,
          document.body,
        )}
    </>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Skeleton
───────────────────────────────────────────────────────────────────────────── */

function PostSkeleton() {
  return (
    <div
      className="rounded-2xl w-full max-w-4xl mx-auto"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border-soft)",
      }}
    >
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-3.5">
        <div
          className="w-10 h-10 rounded-full shrink-0"
          style={{ background: "var(--deep)" }}
        />
        <div className="flex-1 flex flex-col gap-2">
          <div
            className="h-3 rounded-full"
            style={{ background: "var(--deep)", width: "45%" }}
          />
          <div
            className="h-2.5 rounded-full"
            style={{ background: "var(--deep)", width: "28%" }}
          />
        </div>
      </div>
      {/* Image placeholder */}
      <div
        style={{
          height: "min(340px, 75vw)",
          minHeight: 180,
          background: "var(--deep)",
        }}
      />
      {/* Description lines */}
      <div className="px-4 pt-3 pb-2 flex flex-col gap-2">
        <div
          className="h-3 rounded-full"
          style={{ background: "var(--deep)", width: "88%" }}
        />
        <div
          className="h-3 rounded-full"
          style={{ background: "var(--deep)", width: "72%" }}
        />
        <div
          className="h-3 rounded-full"
          style={{ background: "var(--deep)", width: "55%" }}
        />
      </div>
      {/* Action bar */}
      <div
        className="flex items-center gap-3 px-4 py-3"
        style={{ borderTop: "1px solid var(--border-soft)" }}
      >
        <div
          className="h-7 rounded-full"
          style={{ background: "var(--deep)", width: 72 }}
        />
        <div
          className="h-7 rounded-full"
          style={{ background: "var(--deep)", width: 72 }}
        />
        <div
          className="h-7 rounded-full"
          style={{ background: "var(--deep)", width: 60 }}
        />
        <div
          className="ml-auto h-7 w-7 rounded-full"
          style={{ background: "var(--deep)" }}
        />
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   FeedsPage
───────────────────────────────────────────────────────────────────────────── */

export default function FeedsPage() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { t } = useTranslation();
  const { posts, isLoading, isLoadingMore, error, hasMore, currentPage } =
    useAppSelector((s) => s.feed);
  const [deletedFeedIds, setDeletedFeedIds] = useState<Set<string>>(new Set());

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

  const handleLoadMore = useCallback(() => {
    dispatch(fetchFeed(currentPage + 1));
  }, [dispatch, currentPage]);

  const sentinelRef = useInfiniteScroll({
    hasMore,
    isLoading: isLoading || isLoadingMore,
    onLoadMore: handleLoadMore,
  });

  return (
    <>
      {/* ── Header ──────────────────────────────────────────────────────── */}
      <div
        className="relative px-5 pt-6 pb-5 overflow-hidden"
        style={{
          background:
            "linear-gradient(180deg,rgba(var(--accent-rgb),0.06) 0%,transparent 100%)",
          borderBottom: "1px solid var(--border-soft)",
        }}
      >
        <div
          className="absolute top-2 right-6 w-32 h-32 rounded-full pointer-events-none"
          style={{
            background:
              "radial-gradient(circle,rgba(var(--accent-rgb),0.1) 0%,transparent 70%)",
          }}
        />
        <div className="flex items-center gap-3.5">
          <div
            className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
            style={{
              background: "rgba(var(--accent-rgb),0.11)",
              border: "1px solid rgba(var(--accent-rgb),0.2)",
            }}
          >
            <Rss
              size={20}
              style={{ color: "var(--accent)" }}
              strokeWidth={1.8}
            />
          </div>
          <div>
            <h1
              className="text-base font-black tracking-tight leading-tight"
              style={{ color: "var(--text-primary)" }}
            >
              {t("feeds_title")}
            </h1>
            <p className="text-[11px] mt-0.5" style={{ color: "#666" }}>
              {t("feeds_subtitle")}
            </p>
          </div>
        </div>
      </div>

      {/* ── Floating Create Post button ─────────────────────────────────── */}
      <button
        onClick={() => router.push("/upload")}
        className="fixed z-40 flex items-center justify-center w-13 h-13 rounded-full shadow-2xl transition-all duration-200 hover:scale-110 active:scale-95"
        style={{
          bottom: 88,
          right: 20,
          width: 52,
          height: 52,
          background: "var(--accent)",
          boxShadow: "0 6px 28px rgba(var(--accent-rgb),0.5)",
        }}
        aria-label="Create post"
      >
        <Plus size={22} color="white" strokeWidth={2.5} />
      </button>

      {/* ── Content ─────────────────────────────────────────────────────── */}
      <div className="px-4 py-5 pb-28 ">
        {isLoading ? (
          <>
            <div className="flex flex-col gap-5 ">
              {Array.from({ length: 4 }).map((_, i) => (
                <PostSkeleton key={i} />
              ))}
            </div>
          </>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <AlertCircle size={36} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>
              {error}
            </p>
            <button
              onClick={() => dispatch(fetchFeed(1))}
              className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              {t("state_tryAgain")}
            </button>
          </div>
        ) : posts.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-5">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center"
              style={{
                background: "rgba(var(--accent-rgb),0.07)",
                border: "1px solid rgba(var(--accent-rgb),0.14)",
              }}
            >
              <Rss
                size={34}
                style={{ color: "var(--accent)", opacity: 0.4 }}
                strokeWidth={1.2}
              />
            </div>
            <div className="text-center">
              <p
                className="text-sm font-semibold"
                style={{ color: "var(--text-primary)" }}
              >
                {t("feeds_noPosts")}
              </p>
              <p className="text-xs mt-1" style={{ color: "#555" }}>
                {t("feeds_subscribeToSee")}
              </p>
            </div>
          </div>
        ) : (
          <>
            <MotionSection className="flex flex-col gap-5">
              {posts
                .filter((p) => !deletedFeedIds.has(p.id))
                .map((post, i) => (
                  <MotionItem key={post.id}>
                    <PostCard
                      post={post}
                      index={i}
                      onDeleted={(id) =>
                        setDeletedFeedIds(
                          (prev) => new Set(Array.from(prev).concat(id)),
                        )
                      }
                    />
                  </MotionItem>
                ))}
            </MotionSection>

            {/* Sentinel */}
            <div ref={sentinelRef} className="h-1 mt-5" />

            {/* Loading more */}
            {isLoadingMore && (
              <div className="flex flex-col gap-5 mt-5">
                <PostSkeleton />
                <PostSkeleton />
              </div>
            )}

            {/* End of feed */}
            {!hasMore && posts.length > 0 && !isLoading && !isLoadingMore && (
              <div className="flex items-center justify-center gap-2 py-10 mt-2">
                <div
                  className="h-px flex-1"
                  style={{ background: "var(--border-soft)" }}
                />
                <div className="flex items-center gap-1.5">
                  <Rss size={11} style={{ color: "#444" }} strokeWidth={1.5} />
                  {/* <span
                    className="text-[11px] font-medium"
                    style={{ color: "#444" }}
                  >
                    You're all caught up
                  </span> */}
                </div>
                <div
                  className="h-px flex-1"
                  style={{ background: "var(--border-soft)" }}
                />
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
