"use client";

import { useTranslation } from "react-i18next";
import SocialLinks from "./ProfileSocialLinks";
import ProfileStatsRow from "./ProfileStatsRow";
import { buildProfileStatCards } from "./profileStatCards";
import Title from "@/components/shared/Title";
import { occupationOptions } from "@/data/Constants";
import { type PublicProfileResponse } from "./commonProfileTypes";
import { useLanguageStore } from "@/store/languageStore";
import { type ProfileData } from "./commonProfileTypes";
import { hasPositiveCount } from "@/lib/helpers";

/** Background details and the achievement cards beneath them. */
export default function BackgroundAndAchievements({
  profile,
  userType,
  isVolunteerTeam,
}: {
  profile: ProfileData;
  userType: PublicProfileResponse["user_type"];
  isVolunteerTeam: boolean;
}) {
  const { t } = useTranslation();
  const language = useLanguageStore((state) => state.language);
  /*
   * `occupation` and `current_status` are the same answer under two names, and
   * both hold the raw slug (`university_student`). They used to render as two
   * separate rows under labels that are identical in both languages
   * ("Current status" / "الوضع الحالي"), one of them showing the untranslated
   * slug. Resolved once here, from whichever field the API populated, and
   * falling back to the raw string only when it is genuinely free text that no
   * option matches.
   */
  const rawCurrentStatus = profile.occupation || profile.current_status || "";
  const occupation = occupationOptions.find(
    (option) => option.value === rawCurrentStatus
  );
  const currentStatusLabel = occupation
    ? occupation[language === "ar" ? "name_ar" : "name_en"]
    : rawCurrentStatus;
  const interests = profile.interest_display || [];
  /*
   * Volunteer counters on `/public-profile/{id}`:
   * 1. Volunteer hour — attended hours.
   * 2. Volunteer Opportunity — volunteer_opportunity participations.
   * 3. Development Opportunity — learn-serve activities as Participant OR
   *    Provider (one per opportunity, NOT certificates). Uses the exact card
   *    style of the entity's development counter (n_learnServeicn.svg +
   *    OPPORTUNITIESORGANIZED-- + primary-503).
   *
   * The backend's `total_opportunities` combines attended volunteer and
   * development activities. The volunteer-only figure is therefore derived by
   * subtracting the participant portion of the development counter; the latter
   * is combined Participant + Provider, and `opportunities_organized` supplies
   * the Provider portion. Explicit split fields still win during rollout.
   */
  const { cards } = buildProfileStatCards(
    profile,
    t,
    userType,
    isVolunteerTeam
  );

  return (
    <section className="px-3 pt-10 2xl:px-5 2xl:pt-[70px]">
      <div className="mb-12 gap-8 lg:flex">
        <div className="lg:w-1/2">
          <Title text={t("COMMON.ABOUT.ME")} hasMargin={false} className="mb-6 text-start" />
          <div className="space-y-5 text-lg text-primary-5 lg:w-[80%]">
            {/*
              Organizations still show their name; volunteers do not. This
              endpoint returns `full_name: null` for volunteers on purpose, so
              their identity here is the nickname/badge/status/interests set
              rendered above and below instead.
            */}
            {userType === "organization" && (
              <p>
                <strong>{t("COMMON.COMPANYNAME")} : </strong>
                {profile.company_name || profile.full_name || "—"}
              </p>
            )}
            {/*
              Sector was dropped from the UI at the client's request. The field
              still exists on the API (used by 8 resources) and will be removed
              there separately, so nothing reads `sector_display` here any more.
            */}
            {userType === "volunteer" && currentStatusLabel && (
              <p>
                <strong>{t("COMMON.CURRENT_STATUS")} : </strong>
                {currentStatusLabel}
              </p>
            )}
            {interests.length > 0 && (
              <div>
                <h3 className="mb-2 font-bold">{t("COMMON.INTEREST")}</h3>
                <div className="flex flex-wrap gap-2 rounded-[20px] border border-primary-5 px-[17px] py-3">
                  {interests.map((interest, index) => (
                    <span
                      key={interest.id ?? index}
                      className="rounded-full bg-[#eaeaf1] px-4 py-1 text-[15px]"
                    >
                      {interest[language === "ar" ? "value_ar" : "value_en"]}
                    </span>
                  ))}
                </div>
              </div>
            )}
            <SocialLinks profile={profile} />
          </div>
        </div>
        {/* No heading over an empty row: every counter still at zero is
            hidden, so with none to show the whole block goes. */}
        {cards.some((card) => hasPositiveCount(card.value)) && (
          <div className="mt-10 w-full lg:mt-0 lg:w-1/2">
            <Title text={t("COMMON.ACHIEVEMENT")} hasMargin={false} className="mb-6 text-start" />
            {/* Mobile keeps the counters on one row — the client asked for the
                four to sit side by side rather than stack — scrolling sideways
                when they don't fit. */}
            <ProfileStatsRow cards={cards} />
          </div>
        )}
      </div>
    </section>
  );
}
