"use client";

import Image from "next/image";
import { useTranslation } from "react-i18next";
import { getDefaultProfileImage } from "@/lib/helpers";
import { relativeTime } from "../relativeTime";
import { type PostData } from "./InnerPost";

const asset = (path: string) => `/assets/${path}`;

/** The author row above a post: avatar, name and relative timestamp. */
export default function CommunityPostAuthor({
  postUser,
  postData,
  selectedLanguage,
  profileUrl,
  router,
}: {
  postUser: NonNullable<PostData["data"]>["user"] | undefined;
  postData: NonNullable<PostData["data"]>;
  selectedLanguage: string;
  /* Built by the page; falls back to "/" rather than being nullable. */
  profileUrl: string;
  router: { push: (href: string) => void };
}) {
  const { t } = useTranslation();

  /*
   * BE-169 (backend `0572fb7`): for a volunteer, `user.full_name` is the name
   * other people may see — the real name when «إظهار اسمي» is on, otherwise the
   * nickname — so it goes first. Organizations keep the post's nickname first.
   */
  const authorName =
    postUser?.user_type === "volunteer" || postUser?.user_type === "individual"
      ? postUser.full_name || postData.nickname || ""
      : postData.nickname || postUser?.full_name || "";

  return (
  <div className="flex items-center gap-3 mb-4">
    {postUser && (
      <Image
        className="aspect-square shrink-0 rounded-full w-[84px] h-[84px] object-cover mobilescreen:w-[50px] mobilescreen:h-[50px] border-2 border-primary-5 cursor-pointer"
        src={
          postUser.profile_pic ||
          getDefaultProfileImage(
            postUser.gender_display?.value_en,
            asset("profile/male_profile.svg"),
            asset("profile/female_profile.svg"),
            asset("profile/org_profile.svg")
          )
        }
        alt={authorName}
        width={84}
        height={84}
        unoptimized
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          router.push(profileUrl);
        }}
      />
    )}
    <div className="gap-3 items-center">
      <h3 className="font-bold text-xl xs:text-base">
        {authorName}
      </h3>
      <p className="text-[#535151] text-lg xs:text-xs flex gap-1">
        • {relativeTime(postData.created_at, selectedLanguage, t)}
      </p>
    </div>
  </div>
  );
}
