"use client";

import CommunityPostMenu from "./CommunityPostMenu";
import HashtagText from "@/components/shared/HashtagText";
import { pickLocalized } from "@/features/shared/types/cms";
import React from "react";
import Image from "next/image";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import InnerPostFooter from "./InnerPostFooter";
import InnerPostAuthor from "./InnerPostAuthor";
import { useInnerPost } from "./useInnerPost";
import type { PostData } from "./InnerPost";

/**
 * A community post card.
 *
 * The whole card is a link to the post, so every control inside it stops
 * propagation — a tag, a like or the owner menu must not navigate.
 */
export default function InnerPostCard({
  screen,
  data,
}: {
  screen: ReturnType<typeof useInnerPost>;
  data: PostData["data"];
}) {
  const { t } = useTranslation();
  const {
    state,
    router,
    selectedLanguage,
    showDropdown,
    setShowDropdown,
    dropdownRef,
    handleEdit,
    handleDelete,
    handleTagClick,
  } = screen;

  /*
   * Full height, so cards in one grid row line up; the text block grows and
   * the like / reply row sits at the bottom of every card.
   */
  const title =
    (selectedLanguage === "ar" ? data?.title_ar : data?.title_en) ?? "";

  /*
   * The card's link is a **stretched overlay**, not a wrapper.
   *
   * It used to wrap the whole card, which put the creator's options menu —
   * Edit and *Delete* — inside the `<a>`. A `<button>` is not valid content
   * for a link: the two share one Tab stop's worth of space, assistive
   * technology announces the nesting inconsistently, and the only thing
   * keeping the delete from also navigating was a `preventDefault()` in every
   * handler. Here the link is a sibling that covers the card's box, so the
   * whole card is still clickable while the buttons are real siblings with
   * nothing to cancel.
   *
   * Why the z-indexes: the overlay is positioned, so it paints above the
   * card's static content and absorbs clicks on the text — which is what
   * makes the card clickable. Anything that must stay interactive therefore
   * has to be lifted above it, which is what `relative z-10` on the menu, the
   * body and the footer below is doing. The link carries the post's title as
   * its accessible name; without it the link's name would be the card's whole
   * text content.
   */
  return (
  <div className="block h-full">
    <div
      onClick={(event) => {
        const target = event.target as HTMLElement;
        if (target.closest("a, button, input, textarea, select, summary, [role=button], [role=menuitem]")) return;
        router.push(`/community-detail/${data.id}`);
      }}
      className={`cursor-pointer flex h-full flex-col border rounded-[20px] p-6 xsmall:p-3 smallscreen:p-[10px] relative shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] ${
        state === 1
          ? "bg-primary-5/5 border-primary-5"
          : "bg-[#FC95550D]/5 border-[#FC9555]"
      }`}
    >
      <Link
        href={`/community-detail/${data?.id}`}
        className="absolute inset-0 z-0 rounded-[20px]"
      >
        <span className="sr-only">{title}</span>
      </Link>
      {/* The shared menu — this was a second, drifted copy of it. */}
      <CommunityPostMenu
        selectedLanguage={selectedLanguage}
        showDropdown={showDropdown}
        setShowDropdown={setShowDropdown}
        dropdownRef={dropdownRef}
        handleEdit={handleEdit}
        handleDelete={handleDelete}
        isCreator={data?.is_creator}
        triggerClassName={
          state === 1 ? "hover:bg-gray-100" : "hover:bg-[#f4c5a7]"
        }
        iconClassName={`text-lg ${
          state === 1 ? "text-primary-5" : "text-[#FC9555]"
        }`}
      />

      <div className="relative z-10">
        <InnerPostAuthor screen={screen} data={data} />
      </div>

      <div className="relative z-10 mb-4 flex-1">
        <h2 className="text-xl font-bold mb-2 flex gap-3 items-center">
          {/* Idea badge only — the funding ("Needs Support") badge was removed. */}
          {data?.proposing_idea ? (
            <div
              className="flex items-center justify-center gap-1.5 border border-[#FC9555] bg-[#FAEADD] rounded-[20px]"
              style={{ width: 60, height: 36 }}
            >
              <div className="relative w-[12px] h-[19px]">
                <Image
                  src="/assets/community/idia.svg"
                  alt={t("COMMON.PROPOSING_IDEA")}
                  fill
                  className="object-contain"
                  unoptimized
                />
              </div>
            </div>
          ) : null}
        </h2>

        <div className="line-clamp-6 text-[#535151] text-lg">
          <HashtagText
            text={pickLocalized(data?.idea_text_en, data?.idea_text_ar, selectedLanguage)}
            onTagClick={handleTagClick}
            tagClassName="text-blue-500 cursor-pointer hover:underline font-medium"
          />
        </div>
      </div>

      {/*
        The list payload already carries `post_images`; they used to appear
        only on the detail page. Up to three here, the third showing "+N"
        for the rest — the whole card still opens the detail page, where
        they can be viewed full size.
      */}
      {(() => {
        /* A type guard, not just a truthiness filter: `post_images[].image`
           is `getimg(...)`, which is null for an empty column, and
           `next/image` throws on a missing `src`. Narrowing here is what lets
           `img.image` below be a plain string. */
        const images = (data?.post_images ?? []).filter(
          (img): img is { id: number; image: string } =>
            typeof img?.image === "string" && img.image !== ""
        );
        if (images.length === 0) return null;
        const shown = images.slice(0, 3);
        const hidden = images.length - shown.length;
        return (
          <div
            className={`relative z-10 mb-4 grid gap-2 ${
              shown.length === 1 ? "grid-cols-1" : shown.length === 2 ? "grid-cols-2" : "grid-cols-3"
            }`}
          >
            {shown.map((img, index) => (
              <div
                key={img.id ?? index}
                className={`relative overflow-hidden rounded-[14px] bg-[#29246D0A] ${
                  shown.length === 1 ? "h-[260px] mobilescreen:h-[180px]" : "h-[160px] mobilescreen:h-[110px]"
                }`}
              >
                <Image
                  src={img.image}
                  alt={`${t("COMMON.POST")} ${index + 1}`}
                  fill
                  unoptimized
                  className="object-cover"
                />
                {hidden > 0 && index === shown.length - 1 && (
                  <span className="absolute inset-0 flex items-center justify-center bg-black/45 text-2xl font-bold text-white">
                    +{hidden}
                  </span>
                )}
              </div>
            ))}
          </div>
        );
      })()}

      <div className="relative z-10">
        <InnerPostFooter screen={screen} data={data} />
      </div>
    </div>
  </div>
  );
}
