import React, { useEffect, useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useTranslation } from "react-i18next";
import { loadAuth } from "../../auth/authStorage";
import {
  fetchPostLikeState,
  recordPostShare,
  togglePostLike,
  updatePostVisibility,
  fetchProfile,
  editPost,
  deletePost,
} from "../../api/client";
import { useAuth } from "../../auth/AuthContext";
import { trackEvent } from "../../utils/analytics";
import { BlurImage, GalleryImage } from "../ui/BlurImage";

// ─────────────────────────────────────────────────────────────────────────────
// Utilities
// ─────────────────────────────────────────────────────────────────────────────

function isAuthed() {
  try {
    const auth = loadAuth();
    return !!(auth && auth.access_token);
  } catch {
    return false;
  }
}

function requestAuth(message) {
  try {
    window.dispatchEvent(
      new CustomEvent("sociowire:auth-required", {
        detail: { message, mode: "login" },
      })
    );
  } catch {}
  trackEvent("auth_required", { context: "wall", mode: "login" });
}

function formatRelativeTime(createdAt) {
  try {
    if (!createdAt) return "now";
    const d = createdAt instanceof Date ? createdAt : new Date(String(createdAt));
    if (Number.isNaN(d.getTime())) return "now";
    const s = Math.floor((Date.now() - d.getTime()) / 1000);
    if (s < 60) return "now";
    const m = Math.floor(s / 60);
    if (m < 60) return `${m}m`;
    const h = Math.floor(m / 60);
    if (h < 48) return `${h}h`;
    const days = Math.floor(h / 24);
    return `${days}d`;
  } catch {
    return "now";
  }
}

function formatCount(value) {
  const n = Number(value);
  if (!Number.isFinite(n)) return "0";
  if (n < 1000) return String(Math.max(0, Math.floor(n)));
  if (n < 1000000) return `${(n / 1000).toFixed(1)}k`;
  return `${(n / 1000000).toFixed(1)}m`;
}

function categoryLabel(post) {
  const c = (post?.category || "NEWS").toString().toUpperCase();
  if (c === "EVENT") return "EVENTS";
  return c;
}

function categoryIconClass(post) {
  const c = (post?.category || "NEWS").toString().toUpperCase();
  switch (c) {
    case "EVENT":
    case "EVENTS":
      return "fa-regular fa-calendar";
    case "FRIENDS":
      return "fa-solid fa-user-group";
    case "MARKET":
      return "fa-solid fa-store";
    default:
      return "fa-regular fa-newspaper";
  }
}

function getCategoryBadgeClass(category) {
  const c = (category || "NEWS").toString().toUpperCase();
  switch (c) {
    case "BREAKING":
      return "badge-breaking";
    case "MARKET":
      return "badge-market";
    case "FRIENDS":
      return "badge-friends";
    case "EVENT":
    case "EVENTS":
      return "badge-events";
    case "LIVE":
      return "badge-live";
    default:
      return "badge-news";
  }
}

function normalizeImageUrl(raw) {
  const v = (raw || "").toString().trim();
  if (!v) return "";
  const lower = v.toLowerCase();
  if (["null", "undefined", "none", "false", "0", "self", "default"].includes(lower)) return "";
  if (lower.startsWith("data:")) return "";
  if (lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("//") || lower.startsWith("/") || lower.startsWith("./")) {
    return v;
  }
  return "";
}

// Avatar cache
const wallAvatarCache = new Map();
const wallAvatarInflight = new Map();

async function getAvatarForUser(name) {
  const key = (name || "").toLowerCase().trim();
  if (!key) return "";
  if (wallAvatarCache.has(key)) return wallAvatarCache.get(key);
  if (wallAvatarInflight.has(key)) return wallAvatarInflight.get(key);
  const p = (async () => {
    const profile = await fetchProfile(name);
    const url = profile?.avatar_url ? String(profile.avatar_url) : "";
    wallAvatarCache.set(key, url);
    wallAvatarInflight.delete(key);
    return url;
  })().catch(() => {
    wallAvatarCache.set(key, "");
    wallAvatarInflight.delete(key);
    return "";
  });
  wallAvatarInflight.set(key, p);
  return p;
}

// ─────────────────────────────────────────────────────────────────────────────
// Animation Variants
// ─────────────────────────────────────────────────────────────────────────────

const cardVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.98 },
  visible: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { duration: 0.4, ease: [0.16, 1, 0.3, 1] },
  },
  hover: {
    y: -4,
    scale: 1.005,
    transition: { duration: 0.3, ease: "easeOut" },
  },
  tap: { scale: 0.995 },
};

const buttonVariants = {
  hover: { scale: 1.05, y: -1 },
  tap: { scale: 0.95 },
};

const statsVariants = {
  initial: { scale: 1 },
  pulse: {
    scale: [1, 1.2, 1],
    transition: { duration: 0.3 },
  },
};

// ─────────────────────────────────────────────────────────────────────────────
// Sub-components
// ─────────────────────────────────────────────────────────────────────────────

function ActionButton({ icon, label, active, danger, onClick, children }) {
  return (
    <motion.button
      type="button"
      className={`
        inline-flex items-center gap-2 px-4 py-2 rounded-full
        text-sm font-semibold
        transition-colors duration-200
        ${active
          ? "bg-gradient-to-r from-accent-dark/25 to-purple-500/20 border-accent/40 text-accent shadow-glow-sm"
          : danger
            ? "bg-surface-800/60 border-red-500/30 text-red-400 hover:bg-red-500/15 hover:text-red-300"
            : "bg-surface-800/60 border-surface-600/20 text-surface-300 hover:bg-accent/15 hover:border-accent/30 hover:text-accent"
        }
        border backdrop-blur-sm
      `}
      onClick={onClick}
      variants={buttonVariants}
      whileHover="hover"
      whileTap="tap"
    >
      <i className={icon} />
      {label && <span>{label}</span>}
      {children}
    </motion.button>
  );
}

function StatItem({ icon, count, onClick }) {
  const [didPulse, setDidPulse] = useState(false);

  return (
    <motion.span
      className="flex items-center gap-1.5 text-surface-500 hover:text-surface-300 cursor-pointer transition-colors"
      onClick={onClick}
      variants={statsVariants}
      animate={didPulse ? "pulse" : "initial"}
      onAnimationComplete={() => setDidPulse(false)}
    >
      <i className={icon} />
      <span className="text-sm">{formatCount(count)}</span>
    </motion.span>
  );
}

function ImageFallback({ category, iconClass }) {
  return (
    <div className="w-full h-64 flex items-center justify-center bg-gradient-to-br from-surface-800/95 via-surface-850/98 to-surface-900">
      <div className="flex flex-col items-center gap-3 text-accent/70">
        <motion.i
          className={`${iconClass} text-5xl opacity-60`}
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 0.6 }}
          transition={{ duration: 0.4 }}
        />
        <span className="text-xs font-bold uppercase tracking-widest opacity-70">
          {category}
        </span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Main Component
// ─────────────────────────────────────────────────────────────────────────────

export default function PostCardNew({ post, selected, onSelect, onPostDeleted, onPostUpdated }) {
  const { t } = useTranslation();
  const [liked, setLiked] = useState(false);
  const [authed, setAuthed] = useState(isAuthed());
  const [activeImageIndex, setActiveImageIndex] = useState(0);
  const [failedImageIndices, setFailedImageIndices] = useState(() => new Set());
  const [imgFailed, setImgFailed] = useState(false);
  const [showPrivacy, setShowPrivacy] = useState(false);
  const [privacySaving, setPrivacySaving] = useState(false);
  const [privacyError, setPrivacyError] = useState("");
  const [postVisibility, setPostVisibility] = useState((post?.visibility || "public").toString());
  const [postGroupId, setPostGroupId] = useState((post?.group_id || "").toString());
  const [postUsers, setPostUsers] = useState("");
  const [applyToImages, setApplyToImages] = useState(true);
  const [counts, setCounts] = useState(() => ({
    like: post?.like_count ?? 0,
    comment: post?.comment_count ?? 0,
    share: post?.share_count ?? 0,
  }));
  const { username, token, userId } = useAuth();

  // Edit/Delete state
  const [showEditDelete, setShowEditDelete] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState("");
  const [editSnippet, setEditSnippet] = useState("");
  const [editSaving, setEditSaving] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const postId = post?.id ?? post?._id ?? 0;

  // Fetch like state
  useEffect(() => {
    let active = true;
    if (!authed || !postId) return () => {};
    fetchPostLikeState(postId).then((res) => {
      if (!active) return;
      if (res?.ok && res.liked) setLiked(true);
    });
    return () => { active = false; };
  }, [authed, postId]);

  // Auth change listener
  useEffect(() => {
    const handler = () => {
      const next = isAuthed();
      setAuthed(next);
      if (!next) setLiked(false);
    };
    window.addEventListener("sociowire:auth-changed", handler);
    return () => window.removeEventListener("sociowire:auth-changed", handler);
  }, []);

  // Sync counts
  useEffect(() => {
    setCounts({
      like: post?.like_count ?? 0,
      comment: post?.comment_count ?? 0,
      share: post?.share_count ?? 0,
    });
  }, [post?.like_count, post?.comment_count, post?.share_count]);

  useEffect(() => {
    setPostVisibility((post?.visibility || "public").toString());
    setPostGroupId((post?.group_id || "").toString());
  }, [post?.visibility, post?.group_id]);

  // Media URLs - check both media_urls (frontend) and image_urls (backend API)
  const mediaUrls = useMemo(() => {
    const list = [];
    const seen = new Set();
    const addUrl = (value) => {
      const normalized = normalizeImageUrl(value);
      if (!normalized || seen.has(normalized)) return;
      seen.add(normalized);
      list.push(normalized);
    };
    // Check media_urls (frontend sends this)
    if (Array.isArray(post?.media_urls)) {
      post.media_urls.forEach(addUrl);
    }
    // Check image_urls (backend API returns this)
    if (Array.isArray(post?.image_urls)) {
      post.image_urls.forEach(addUrl);
    }
    // Fallback to individual image fields (already deduped by seen Set)
    [post?.image_large, post?.image_medium, post?.image_small, post?.image, post?.media_url].forEach(addUrl);
    return list;
  }, [post?.media_urls, post?.image_urls, post?.image_large, post?.image_medium, post?.image_small, post?.image, post?.media_url]);

  const mediaKey = mediaUrls.join("|");

  useEffect(() => {
    setActiveImageIndex(0);
    setFailedImageIndices(new Set());
    setImgFailed(false);
  }, [mediaKey]);

  const title = post?.title || "Untitled";
  const snippet = post?.snippet || "";
  const author = (post?.author || post?.Author || "anon").toString();
  const authorId = post?.author_id || post?.authorId || null;
  const isAuthor =
    (username && author && author.toLowerCase() === username.toLowerCase()) ||
    (userId && authorId && Number(userId) === Number(authorId));
  const [authorAvatar, setAuthorAvatar] = useState("");
  const sub = (post?.sub_category || post?.subCategory || "").toString();
  const contentType = (post?.content_type || "").toString().toLowerCase();
  const isLiveContent = contentType === "camera" || contentType === "live" || contentType === "stream";
  const timeAgo = isLiveContent ? "LIVE" : formatRelativeTime(post?.created_at || post?.CreatedAt || post?.createdAt);
  const cat = categoryLabel(post);
  const badgeClass = getCategoryBadgeClass(cat);

  const metaLine = useMemo(() => {
    const parts = [];
    if (sub) parts.push(sub);
    if (post?.region) parts.push(post.region);
    return parts.join(" • ");
  }, [sub, post?.region]);

  const safeImageIndex = mediaUrls.length ? Math.min(Math.max(activeImageIndex, 0), mediaUrls.length - 1) : 0;
  const activeImage = mediaUrls[safeImageIndex] || "";
  const hasGalleryImage = Boolean(activeImage && !imgFailed);

  const findNextAvailableIndex = (current, failed) => {
    if (mediaUrls.length === 0) return -1;
    for (let offset = 1; offset <= mediaUrls.length; offset++) {
      const idx = (current + offset) % mediaUrls.length;
      if (!failed.has(idx)) return idx;
    }
    return -1;
  };

  const findPrevAvailableIndex = (current, failed) => {
    if (mediaUrls.length === 0) return -1;
    for (let offset = 1; offset <= mediaUrls.length; offset++) {
      const idx = (current - offset + mediaUrls.length) % mediaUrls.length;
      if (!failed.has(idx)) return idx;
    }
    return -1;
  };

  const handleImageError = () => {
    if (!activeImage) {
      setImgFailed(true);
      return;
    }
    const nextFailed = new Set(failedImageIndices);
    nextFailed.add(safeImageIndex);
    setFailedImageIndices(nextFailed);
    if (nextFailed.size >= mediaUrls.length) {
      setImgFailed(true);
      return;
    }
    const nextIndex = findNextAvailableIndex(safeImageIndex, nextFailed);
    if (nextIndex >= 0) setActiveImageIndex(nextIndex);
  };

  // Fetch author avatar
  useEffect(() => {
    let cancelled = false;
    const who = (author || "").trim();
    if (!who) {
      setAuthorAvatar("");
      return;
    }
    getAvatarForUser(who).then((url) => {
      if (cancelled) return;
      setAuthorAvatar(url || "");
    });
    return () => { cancelled = true; };
  }, [author]);

  // ─────────────────────────────────────────────────────────────────────────────
  // Handlers
  // ─────────────────────────────────────────────────────────────────────────────

  const handleLike = async (e) => {
    e.stopPropagation();
    if (!authed) {
      requestAuth(t("post.signInToLike"));
      return;
    }
    trackEvent("post_like", { post_id: postId, post_title: title?.slice(0, 100), post_category: cat });
    const res = await togglePostLike(postId, !liked);
    if (res?.ok) {
      setLiked(!!res.liked);
      if (res?.counts) {
        setCounts({
          like: res.counts.like_count,
          comment: res.counts.comment_count,
          share: res.counts.share_count,
        });
      }
    }
  };

  const handleComment = (e) => {
    e.stopPropagation();
    if (!authed) {
      requestAuth(t("post.signInToComment"));
      return;
    }
    trackEvent("post_comment", { post_id: postId, post_title: title?.slice(0, 100), post_category: cat });
    if (onSelect) onSelect(post);
  };

  const handleShare = async (e) => {
    e.stopPropagation();
    const shareUrl = `${window.location.origin}/p/${postId}`;
    trackEvent("post_share", { post_id: postId, post_title: title?.slice(0, 100), post_category: cat });
    try {
      if (navigator.share) {
        await navigator.share({ title: title || "SocioWire", url: shareUrl });
      } else if (navigator.clipboard) {
        await navigator.clipboard.writeText(shareUrl);
      }
    } catch {}
    const res = await recordPostShare(postId);
    if (res?.counts) {
      setCounts({
        like: res.counts.like_count,
        comment: res.counts.comment_count,
        share: res.counts.share_count,
      });
    }
  };

  const handleSavePrivacy = async () => {
    setPrivacyError("");
    setPrivacySaving(true);
    try {
      const payload = {
        visibility: postVisibility,
        group_id: postGroupId.trim(),
        users: postUsers.split(",").map((u) => u.trim()).filter(Boolean),
      };
      if (applyToImages) {
        payload.image_visibility = postVisibility;
        payload.image_group_id = postGroupId.trim();
        payload.image_users = payload.users;
      }
      await updatePostVisibility(postId, payload, token);
      setPrivacySaving(false);
    } catch {
      setPrivacyError(t("post.visibilityError"));
      setPrivacySaving(false);
    }
  };

  const handleSaveEdit = async () => {
    setEditSaving(true);
    const res = await editPost(postId, { title: editTitle.trim(), snippet: editSnippet.trim() }, token);
    setEditSaving(false);
    if (res?.ok) {
      setIsEditing(false);
      setShowEditDelete(false);
      if (onPostUpdated) onPostUpdated(res);
    }
  };

  const handleDelete = async () => {
    setDeleting(true);
    const res = await deletePost(postId, token);
    setDeleting(false);
    if (res?.ok) {
      setShowDeleteConfirm(false);
      setShowEditDelete(false);
      if (onPostDeleted) onPostDeleted(postId);
    }
  };

  // ─────────────────────────────────────────────────────────────────────────────
  // Render
  // ─────────────────────────────────────────────────────────────────────────────

  return (
    <motion.article
      className={`
        group relative overflow-hidden rounded-2xl cursor-pointer
        bg-gradient-to-br from-glass-card to-surface-800/95
        backdrop-blur-xl
        border border-white/10
        shadow-card
        transition-shadow duration-300
        ${selected ? "ring-2 ring-accent/50 border-accent/30" : ""}
      `}
      variants={cardVariants}
      initial="hidden"
      animate="visible"
      whileHover="hover"
      whileTap="tap"
      onClick={() => {
        trackEvent("post_view", {
          post_id: postId,
          post_title: title?.slice(0, 100),
          post_category: cat,
          post_author: author,
          content_type: "post",
        });
        onSelect && onSelect(post);
      }}
    >
      {/* ─────────────────────────────────────────────────────────────────────────
          Header - Hidden for polaroid, minimal for video/live
         ───────────────────────────────────────────────────────────────────────── */}
      {!(contentType === "photo" || contentType === "picture" || contentType === "image") && (
        <div className={`flex items-center gap-3 p-4 ${
          (contentType === "video" || contentType === "camera" || contentType === "live" || contentType === "stream")
            ? "pb-2"
            : ""
        }`}>
          {/* Avatar */}
          <motion.div
            className="relative w-10 h-10 sm:w-12 sm:h-12 rounded-full p-0.5 bg-gradient-to-br from-accent-dark via-purple-500 to-pink-500 shadow-glow-sm flex-shrink-0"
            whileHover={{ scale: 1.05 }}
          >
            {authorAvatar ? (
              <img
                src={authorAvatar}
                alt={author}
                className="w-full h-full rounded-full object-cover bg-surface-900"
              />
            ) : (
              <div className="w-full h-full rounded-full bg-surface-800 flex items-center justify-center text-white font-bold text-sm sm:text-lg">
                {author ? author[0]?.toUpperCase() : "U"}
              </div>
            )}
          </motion.div>

          {/* Meta */}
          <div className="flex-1 min-w-0">
            <motion.div
              className="font-semibold text-surface-100 truncate group-hover:text-accent-light transition-colors text-sm sm:text-base"
            >
              {author}
            </motion.div>
            <div className={`flex items-center gap-2 text-xs sm:text-sm ${isLiveContent ? "text-red-400 font-bold" : "text-surface-500"}`}>
              {isLiveContent && <span className="live-dot" />}
              <span>{timeAgo}</span>
            </div>
          </div>

          {/* Badge */}
          <motion.div
            className={`badge ${badgeClass}`}
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ delay: 0.1 }}
          >
            {cat}
          </motion.div>
        </div>
      )}

      {/* ─────────────────────────────────────────────────────────────────────────
          Image/Gallery - Content type specific rendering
         ───────────────────────────────────────────────────────────────────────── */}
      {contentType === "camera" || contentType === "live" || contentType === "stream" ? (
        /* LIVE/Camera: TV-style card with red pulsing dot */
        <div className="relative w-full aspect-video bg-slate-900 overflow-hidden rounded-t-2xl">
          {hasGalleryImage ? (
            <BlurImage
              src={activeImage}
              alt={title}
              className="w-full h-full object-cover"
              onError={handleImageError}
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-slate-800 to-slate-900">
              <i className="fa-solid fa-video text-4xl text-slate-600" />
            </div>
          )}
          {/* Red LIVE badge with pulsing dot */}
          <div className="absolute top-3 left-3 flex items-center gap-2 px-3 py-1.5 rounded-lg bg-red-600/95 backdrop-blur-sm shadow-lg">
            <span className="w-2.5 h-2.5 rounded-full bg-white animate-pulse shadow-[0_0_10px_rgba(255,255,255,0.9)]" />
            <span className="text-xs font-black text-white tracking-wider">LIVE</span>
          </div>
          {/* Title overlay at bottom */}
          <div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/80 to-transparent">
            <p className="text-white font-semibold text-sm line-clamp-1">{title}</p>
            <p className="text-white/70 text-xs">@{author}</p>
          </div>
          {/* Scanlines effect */}
          <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(0,0,0,0.05)_2px,rgba(0,0,0,0.05)_4px)]" />
        </div>
      ) : contentType === "video" ? (
        /* VIDEO: Card with play button overlay */
        <div className="relative w-full aspect-video bg-slate-900 overflow-hidden rounded-t-2xl group/video">
          {hasGalleryImage ? (
            <BlurImage
              src={activeImage}
              alt={title}
              className="w-full h-full object-cover transition-transform duration-500 group-hover/video:scale-105"
              onError={handleImageError}
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-slate-800 to-slate-900">
              <i className="fa-solid fa-film text-4xl text-slate-600" />
            </div>
          )}
          {/* Play button overlay */}
          <div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover/video:bg-black/30 transition-colors">
            <motion.div
              className="w-16 h-16 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center shadow-2xl"
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.95 }}
            >
              <i className="fa-solid fa-play text-slate-900 text-xl ml-1" />
            </motion.div>
          </div>
          {/* VIDEO badge */}
          <div className="absolute top-3 left-3 px-3 py-1.5 rounded-lg bg-blue-600/90 backdrop-blur-sm">
            <span className="text-xs font-black text-white tracking-wider">VIDEO</span>
          </div>
          {/* Title overlay at bottom */}
          <div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/80 to-transparent">
            <p className="text-white font-semibold text-sm line-clamp-1">{title}</p>
            <p className="text-white/70 text-xs">@{author} • {timeAgo}</p>
          </div>
        </div>
      ) : contentType === "photo" || contentType === "picture" || contentType === "image" ? (
        /* POLAROID: White frame photo style - standalone card */
        <div className="p-4">
          <div className="bg-white rounded-sm shadow-xl p-3 pb-4 transform rotate-[-1deg] hover:rotate-0 transition-transform duration-300">
            {hasGalleryImage ? (
              <BlurImage
                src={activeImage}
                alt={title}
                className="w-full aspect-square object-cover rounded-sm"
                onError={handleImageError}
              />
            ) : (
              <div className="w-full aspect-square flex items-center justify-center bg-gray-100 rounded-sm">
                <i className="fa-solid fa-image text-4xl text-gray-300" />
              </div>
            )}
            {/* Polaroid caption */}
            <div className="mt-3 px-1">
              <p className="text-gray-800 font-handwriting text-sm line-clamp-2">{title}</p>
              <p className="text-gray-500 text-xs mt-1">@{author} • {timeAgo}</p>
            </div>
          </div>
        </div>
      ) : hasGalleryImage ? (
        /* DEFAULT: Standard gallery image */
        <GalleryImage
          src={activeImage}
          alt={title}
          className="w-full h-64 sm:h-72"
          currentIndex={safeImageIndex}
          totalCount={mediaUrls.length}
          onPrev={() => {
            const prev = findPrevAvailableIndex(safeImageIndex, failedImageIndices);
            if (prev >= 0) setActiveImageIndex(prev);
          }}
          onNext={() => {
            const next = findNextAvailableIndex(safeImageIndex, failedImageIndices);
            if (next >= 0) setActiveImageIndex(next);
          }}
          onError={handleImageError}
          fallback={<ImageFallback category={cat} iconClass={categoryIconClass(post)} />}
        />
      ) : (
        <ImageFallback category={cat} iconClass={categoryIconClass(post)} />
      )}

      {/* Thumbnails */}
      <AnimatePresence>
        {mediaUrls.length > 1 && (
          <motion.div
            className="flex gap-2 p-3 bg-surface-900/50 overflow-x-auto"
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
          >
            {mediaUrls.map((url, idx) => (
              <motion.button
                key={`thumb-${idx}`}
                type="button"
                className={`
                  flex-shrink-0 w-14 h-14 rounded-xl overflow-hidden
                  border-2 transition-all duration-200
                  ${idx === safeImageIndex
                    ? "border-accent shadow-glow-sm"
                    : "border-transparent hover:border-accent/40"
                  }
                `}
                onClick={(e) => {
                  e.stopPropagation();
                  setActiveImageIndex(idx);
                }}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                <img src={url} alt="" className="w-full h-full object-cover" loading="lazy" />
              </motion.button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>

      {/* ─────────────────────────────────────────────────────────────────────────
          Body - Hidden for photo/video/camera, shown for news/default
         ───────────────────────────────────────────────────────────────────────── */}
      {!(contentType === "photo" || contentType === "picture" || contentType === "image" ||
         contentType === "video" || contentType === "camera" || contentType === "live" || contentType === "stream") && (
        <div className="p-4">
          <h3 className="text-lg font-bold text-surface-50 line-clamp-2 mb-2">
            {title}
          </h3>
          {snippet && (
            <p className="text-surface-400 text-sm leading-relaxed line-clamp-3 mb-2">
              {snippet}
            </p>
          )}
          {metaLine && (
            <div className="flex items-center gap-2 text-xs text-surface-500">
              <span className="w-1 h-1 rounded-full bg-gradient-to-r from-accent to-purple-400" />
              <span>{metaLine}</span>
            </div>
          )}
        </div>
      )}

      {/* ─────────────────────────────────────────────────────────────────────────
          Footer - Compact action bar with integrated stats
         ───────────────────────────────────────────────────────────────────────── */}
      <div className="flex items-center justify-between px-4 py-3 border-t border-white/5 bg-surface-900/30">
        {/* Main actions with counts */}
        <div className="flex items-center gap-1">
          <motion.button
            type="button"
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium transition-all
              ${liked
                ? "bg-red-500/15 text-red-400"
                : "text-surface-400 hover:bg-surface-800/60 hover:text-red-400"
              }`}
            onClick={handleLike}
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.95 }}
          >
            <i className={liked ? "fa-solid fa-heart" : "fa-regular fa-heart"} />
            <span>{formatCount(counts.like)}</span>
          </motion.button>

          <motion.button
            type="button"
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium
                       text-surface-400 hover:bg-surface-800/60 hover:text-accent transition-all"
            onClick={handleComment}
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.95 }}
          >
            <i className="fa-regular fa-comment" />
            <span>{formatCount(counts.comment)}</span>
          </motion.button>

          <motion.button
            type="button"
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium
                       text-surface-400 hover:bg-surface-800/60 hover:text-emerald-400 transition-all"
            onClick={handleShare}
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.95 }}
          >
            <i className="fa-solid fa-share-nodes" />
            <span>{formatCount(counts.share)}</span>
          </motion.button>
        </div>

        {/* Author actions */}
        {isAuthor && (
          <div className="flex items-center gap-1">
            <motion.button
              type="button"
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm transition-all
                ${showPrivacy ? "bg-accent/20 text-accent" : "text-surface-500 hover:bg-surface-800/60 hover:text-surface-300"}`}
              onClick={(e) => {
                e.stopPropagation();
                setShowPrivacy((prev) => !prev);
                setShowEditDelete(false);
              }}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <i className="fa-solid fa-lock" />
            </motion.button>
            <motion.button
              type="button"
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm transition-all
                ${showEditDelete ? "bg-accent/20 text-accent" : "text-surface-500 hover:bg-surface-800/60 hover:text-surface-300"}`}
              onClick={(e) => {
                e.stopPropagation();
                setShowEditDelete((prev) => !prev);
                setShowPrivacy(false);
                if (!showEditDelete) {
                  setEditTitle(post?.title || "");
                  setEditSnippet(post?.snippet || "");
                }
              }}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <i className="fa-solid fa-ellipsis" />
            </motion.button>
          </div>
        )}
      </div>

      {/* ─────────────────────────────────────────────────────────────────────────
          Privacy Panel
         ───────────────────────────────────────────────────────────────────────── */}
      <AnimatePresence>
        {isAuthor && showPrivacy && (
          <motion.div
            className="mx-4 mb-4 p-4 rounded-2xl bg-surface-800/80 border border-surface-600/20"
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="space-y-3">
              <div className="flex items-center gap-3 text-sm">
                <label className="text-surface-300 whitespace-nowrap font-medium">{t("common.post")}</label>
                <select
                  className="flex-1 bg-surface-900/80 border border-surface-600/30 rounded-xl px-3 py-2 text-surface-200 text-sm focus:outline-none focus:border-accent/50"
                  value={postVisibility}
                  onChange={(e) => {
                    const next = e.target.value;
                    setPostVisibility(next);
                    if (next !== "group") setPostGroupId("");
                    if (next !== "custom") setPostUsers("");
                  }}
                >
                  <option value="public">{t("post.public")}</option>
                  <option value="friends">{t("post.friendsOnly")}</option>
                  <option value="private">{t("post.private")}</option>
                  <option value="group">{t("post.group")}</option>
                  <option value="custom">{t("post.custom")}</option>
                </select>
              </div>

              {postVisibility === "group" && (
                <input
                  className="w-full bg-surface-900/80 border border-surface-600/30 rounded-xl px-3 py-2 text-surface-200 text-sm focus:outline-none focus:border-accent/50"
                  placeholder={t("post.groupId")}
                  value={postGroupId}
                  onChange={(e) => setPostGroupId(e.target.value)}
                />
              )}

              {postVisibility === "custom" && (
                <input
                  className="w-full bg-surface-900/80 border border-surface-600/30 rounded-xl px-3 py-2 text-surface-200 text-sm focus:outline-none focus:border-accent/50"
                  placeholder={t("post.usernamesComma")}
                  value={postUsers}
                  onChange={(e) => setPostUsers(e.target.value)}
                />
              )}

              <label className="flex items-center gap-2 text-sm text-surface-400 cursor-pointer">
                <input
                  type="checkbox"
                  checked={applyToImages}
                  onChange={(e) => setApplyToImages(e.target.checked)}
                  className="accent-accent"
                />
                {t("post.applyToImages")}
              </label>

              {privacyError && (
                <div className="text-xs text-red-400 bg-red-500/10 rounded-lg px-3 py-2">
                  {privacyError}
                </div>
              )}

              <ActionButton
                icon={privacySaving ? "fa-solid fa-spinner fa-spin" : "fa-solid fa-check"}
                label={privacySaving ? t("post.saving") : t("common.save")}
                onClick={handleSavePrivacy}
              />
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ─────────────────────────────────────────────────────────────────────────
          Edit/Delete Panel
         ───────────────────────────────────────────────────────────────────────── */}
      <AnimatePresence>
        {isAuthor && showEditDelete && (
          <motion.div
            className="mx-4 mb-4 p-4 rounded-2xl bg-surface-800/80 border border-surface-600/20"
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            onClick={(e) => e.stopPropagation()}
          >
            {!isEditing && !showDeleteConfirm && (
              <div className="flex gap-2">
                <ActionButton
                  icon="fa-solid fa-pen"
                  label={t("common.edit")}
                  onClick={() => setIsEditing(true)}
                />
                <ActionButton
                  icon="fa-solid fa-trash"
                  label={t("common.delete")}
                  danger
                  onClick={() => setShowDeleteConfirm(true)}
                />
              </div>
            )}

            {isEditing && (
              <div className="space-y-3">
                <input
                  type="text"
                  className="w-full bg-surface-900/80 border border-surface-600/30 rounded-xl px-4 py-3 text-surface-100 focus:outline-none focus:border-accent/50"
                  placeholder={t("post.title")}
                  value={editTitle}
                  onChange={(e) => setEditTitle(e.target.value)}
                />
                <textarea
                  className="w-full bg-surface-900/80 border border-surface-600/30 rounded-xl px-4 py-3 text-surface-200 resize-y min-h-[80px] focus:outline-none focus:border-accent/50"
                  placeholder={t("post.description")}
                  value={editSnippet}
                  onChange={(e) => setEditSnippet(e.target.value)}
                  rows={3}
                />
                <div className="flex gap-2">
                  <ActionButton
                    icon={editSaving ? "fa-solid fa-spinner fa-spin" : "fa-solid fa-check"}
                    label={editSaving ? t("post.saving") : t("common.save")}
                    onClick={handleSaveEdit}
                  />
                  <ActionButton
                    icon="fa-solid fa-xmark"
                    label={t("common.cancel")}
                    onClick={() => setIsEditing(false)}
                  />
                </div>
              </div>
            )}

            {showDeleteConfirm && (
              <div className="space-y-3">
                <p className="text-red-400 text-sm bg-red-500/10 rounded-xl px-4 py-3 text-center">
                  {t("post.deletePost")}
                </p>
                <div className="flex gap-2 justify-center">
                  <ActionButton
                    icon={deleting ? "fa-solid fa-spinner fa-spin" : "fa-solid fa-trash"}
                    label={deleting ? t("post.deleting") : t("common.delete")}
                    danger
                    onClick={handleDelete}
                  />
                  <ActionButton
                    icon="fa-solid fa-xmark"
                    label={t("common.cancel")}
                    onClick={() => setShowDeleteConfirm(false)}
                  />
                </div>
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </motion.article>
  );
}
