"use client";

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

/**
 * A post card's author row.
 *
 * The avatar placeholder depends on the author's gender, and a volunteer who
 * has not made their profile public is linked through the private route.
 */
export default function InnerPostAuthor({
  screen,
  data,
}: {
  screen: ReturnType<typeof useInnerPost>;
  data: PostData["data"];
}) {
  const { t } = useTranslation();
  const { selectedLanguage, router, state } = screen;

  /*
   * 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 =
    data?.user?.user_type === "volunteer" || data?.user?.user_type === "individual"
      ? data.user.full_name || data?.nickname || ""
      : data?.nickname || data?.user?.full_name || "";

  return (
  <div className="flex items-center gap-3 mb-4">
    {(() => {
      const userObj = data?.user;
      if (!userObj) return null;
      const userId = userObj.id;
      const profileUrl = `/public-profile/${userId}`;

      const defaultImgMale = "/assets/profile/male_profile.svg";
      const defaultImgFemale = "/assets/profile/female_profile.svg";
      const defaultImgOrg = "/assets/profile/org_profile.svg";

      return (
        <button
          type="button"
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            router.push(profileUrl);
          }}
          className="relative w-[72px] h-[72px] mobilescreen:w-[50px] mobilescreen:h-[50px] flex-shrink-0 focus:outline-none"
          aria-label={authorName}
        >
          <Image
            className={`rounded-full object-cover border-2 ${
              state === 1 ? "border-primary-5" : "border-primary-10"
            }`}
            src={
              userObj?.profile_pic ||
              getDefaultProfileImage(
                userObj?.gender_display?.value_en,
                defaultImgMale,
                defaultImgFemale,
                defaultImgOrg
              )
            }
            alt=""
            fill
            unoptimized
          />
        </button>
      );
    })()}
    <div className="gap-3 items-center">
      <h3 className="font-bold text-xl">
        {authorName}
      </h3>
      <p className="text-[#535151] lg:text-base md:text-base mobilescreen:text-sm">
        •{" "}
        {relativeTime(data?.created_at, selectedLanguage, t)}
      </p>
    </div>
  </div>
  );
}
