"use client";

import { communityTagHref } from "@/features/community/communityTag";
import CommunityPostMenu from "@/features/community/components/CommunityPostMenu";
import React, { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import HashtagText from "@/components/shared/HashtagText";
import { pickLocalized } from "@/features/shared/types/cms";
import { type PostData } from "./CommunityCard";

interface PostCardProps {
  post: PostData;
  onDelete: () => void;
  router: ReturnType<typeof useRouter>;
  selectedLanguage: string;
}

/* `t` is gone: the only strings this card rendered itself were the menu's,
   which `CommunityPostMenu` now owns and translates. */
function PostCard({ post, onDelete, router, selectedLanguage }: PostCardProps) {
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowDropdown(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleTagClick = (tag: string) => {
    // Encoded because Arabic hashtags are the common case here.
    router.push(communityTagHref(tag));
  };

  const getProfileImage = () => {
    if (post.user?.profile_pic) return post.user.profile_pic;
    const gender = post.user?.gender_display?.value_en;
    if (gender === "Male") return "/assets/profile/male_profile.svg";
    if (gender === "Female") return "/assets/profile/female_profile.svg";
    return "/assets/profile/org_profile.svg";
  };

  const title =
    (selectedLanguage === "ar" ? post.title_ar : post.title_en) ?? "";

  /* Named rather than inline, because the shared menu takes them as props.
     Both still cancel the event: the overlay link is a sibling now, but these
     buttons are inside the card and a stray default would still scroll. */
  const handleEdit = (event: React.MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    setShowDropdown(false);
    // No standalone edit route exists — the community detail page hosts the
    // real edit-post modal (`InnerPost.tsx`).
    router.push(`/community-detail/${post.id}`);
  };

  const handleDelete = (event: React.MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    setShowDropdown(false);
    onDelete();
  };

  /*
   * The card's link is a stretched overlay rather than a wrapper, for the same
   * reason as `InnerPostCard`: the owner's Edit/**Delete** menu and the
   * hashtag buttons in the body sat inside the `<a>`, which is invalid content
   * and left the delete relying on `preventDefault()` to avoid also
   * navigating. As a positioned sibling the overlay still makes the whole card
   * clickable, and everything interactive is lifted above it with
   * `relative z-10`.
   */
  return (
    <div className="mx-2 2xl:mx-3 mobilescreen:mx-[13px]">
        <div className="bg-white p-6 rounded-xl contributionboxshadow h-full relative min-h-[267px] max-h-[267px]">
          <Link
            href={`/community-detail/${post.id}`}
            className="absolute inset-0 z-0 rounded-xl"
          >
            <span className="sr-only">{title}</span>
          </Link>
          {/* The shared menu — this was the third copy of it. */}
          <CommunityPostMenu
            selectedLanguage={selectedLanguage}
            showDropdown={showDropdown}
            setShowDropdown={setShowDropdown}
            dropdownRef={dropdownRef}
            handleEdit={handleEdit}
            handleDelete={handleDelete}
            isCreator={post.is_creator}
          />

          <div className="relative z-10 flex items-center mb-3 gap-4">
            <div className="relative w-24 h-24 rounded-full overflow-hidden border-2 border-primary-5">
              <Image
                src={getProfileImage()}
                alt=""
                fill
                sizes="96px"
                className="object-cover"
                unoptimized
              />
            </div>
            <div>
              <h3 className="lg:text-xl mobilescreen:text-lg font-bold text-secondary-100">
                {post.nickname || post.user?.full_name}
              </h3>
            </div>
          </div>
          <div className="relative z-10 line-clamp-2 md:line-clamp-3 text-secondary-100 lg:text-lg mobilescreen:text-base mobilescreen:leading-[30px]">
            <HashtagText
              /* Older posts carry one language only; show it rather than an empty card (F-CLA-1). */
              text={pickLocalized(post.idea_text_en, post.idea_text_ar, selectedLanguage)}
              onTagClick={handleTagClick}
            />
          </div>
        </div>
    </div>
  );
}

export default PostCard;
