"use client";

import React from "react";
import Link from "next/link";
import {
  type LeaderboardItem,
  type LeaderboardPodiumProps,
} from "./achievementsTypes";
import {
  podiumName,
  podiumProfileHref,
  podiumProfileImage,
} from "./podiumItem";
import { PODIUM_SLOTS } from "./podiumSlots";
import RemoteImage from "@/components/ui/RemoteImage";
import CrownIcon from "./CrownIcon";
import { leaderboardRank, leaderboardValue, hourUnitForDisplay } from "../leaderboardValue";


type PodiumSlot = (typeof PODIUM_SLOTS)[keyof typeof PODIUM_SLOTS];


const LeaderboardPodium: React.FC<LeaderboardPodiumProps> = ({
  data,
  type,
  t,
}) => {
  const topThree: (LeaderboardItem | null)[] = [
    ...(data || []).slice(0, 3),
    null,
    null,
    null,
  ].slice(0, 3);

  // Rendered left-to-right as 2 – 1 – 3; the grid mirrors itself under `dir=rtl`.
  const podiumOrder = [
    { item: topThree[1], slot: PODIUM_SLOTS[2] },
    { item: topThree[0], slot: PODIUM_SLOTS[1] },
    { item: topThree[2], slot: PODIUM_SLOTS[3] },
  ];

  const getDisplayLabel = (item: LeaderboardItem | null) => {
    switch (type) {
      case "individuals":
        return hourUnitForDisplay(leaderboardValue(item ?? {}, type), t);
      case "teams":
        return t("COMMON.OPPORTUNITY");
      case "companies":
        return t("COMMON.SPONSORED_OPPORTUNITIES");
      default:
        return "";
    }
  };

  const renderAvatar = (item: LeaderboardItem, slot: PodiumSlot) => {
    const profilePic = podiumProfileImage(item, type);
    const name = podiumName(item, t);
    const shared = `${slot.avatar} rounded-full object-cover bg-white ring-2 ${slot.ring} ring-offset-2 ring-offset-white shadow-[0_10px_25px_-12px_rgba(41,36,109,0.45)] transition-transform duration-200 group-hover:-translate-y-1`;

    if (profilePic) {
      /* Square at every breakpoint, so `slot.avatarPx` states the aspect box
         and the classes keep deciding the painted size — see `RemoteImage`. */
      return (
        <RemoteImage
          src={profilePic}
          alt={name}
          width={slot.avatarPx}
          height={slot.avatarPx}
          className={shared}
        />
      );
    }

    return (
      <div
        className={`${shared} ${slot.initials} flex items-center justify-center text-xl md:text-2xl font-bold`}
      >
        {name.charAt(0).toUpperCase()}
      </div>
    );
  };

  if (!data || data.length === 0) {
    return (
      <div className="rounded-[24px] border border-dashed border-[#D5D2E8] bg-[#FAFAFD] py-8 text-center">
        <p className="text-[#8B87A6] text-sm md:text-base">
          {t("COMMON.NO_DATA_AVAILABLE")}
        </p>
      </div>
    );
  }

  return (
    <div className="mt-6 md:mt-8 mb-4 grid grid-cols-3 items-end gap-2 xsl:gap-4 md:gap-5">
      {podiumOrder.map(({ item, slot }) => {
        const name = podiumName(item, t);
        const isEmpty = !item || name === t("COMMON.NO_DATA");
        // Ties share the backend's rank, so two rows can both read «1».
        const rank = isEmpty ? Number(slot.rank) : leaderboardRank(item, Number(slot.rank));

        const head = isEmpty ? (
          <div className="flex flex-col items-center gap-3 pb-8 md:gap-4 md:pb-10 lg:pb-12">
            <div
              className={`${slot.avatar} rounded-full border border-dashed border-[#D5D2E8] bg-[#FAFAFD]`}
            />
            <span className="text-[11px] xsl:text-sm md:text-base font-semibold text-[#A8A4C0]">
              {t("COMMON.NO_DATA")}
            </span>
          </div>
        ) : (
          <Link
            href={podiumProfileHref(item)}
            className="group flex flex-col items-center gap-3 pb-8 md:gap-4 md:pb-10 lg:pb-12 outline-none focus-visible:ring-2 focus-visible:ring-[#29246D]/40 rounded-2xl px-1"
          >
            {rank === 1 && <CrownIcon />}
            {renderAvatar(item, slot)}
            <span className="max-w-full text-center text-[11px] xsl:text-sm md:text-sm lg:text-base font-bold text-primary-5 leading-snug line-clamp-2 break-words group-hover:underline decoration-2 underline-offset-4">
              {name}
            </span>
          </Link>
        );

        return (
          <div key={slot.rank} className="flex flex-col items-center justify-end">
            {head}

            <div
              className={`relative w-full ${slot.height} rounded-t-[18px] xsl:rounded-t-[20px] md:rounded-t-[24px] flex items-center justify-center px-1 ${
                isEmpty
                  ? "bg-[#F4F3F9] border border-b-0 border-dashed border-[#D5D2E8]"
                  : `${slot.bar} ${slot.shadow}`
              }`}
            >
              {/* Rank pill straddles the pedestal edge — a fixed translate, so it
                  never drifts the way the old percentage offsets did. */}
              <span
                className={`absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 flex items-center justify-center rounded-full bg-white ring-1 ${slot.ring} ${slot.pillText} shadow-[0_6px_16px_-6px_rgba(41,36,109,0.35)] w-7 h-7 xsl:w-9 xsl:h-9 md:w-10 md:h-10 lg:w-12 lg:h-12 text-xs xsl:text-base md:text-lg lg:text-xl font-bold`}
              >
                {rank}
              </span>

              {!isEmpty && (
                <div className="flex flex-col items-center justify-center gap-0.5 md:gap-1 pt-3 md:pt-5 text-center">
                  <span
                    className={`${slot.valueColor} font-bold leading-none text-lg xsl:text-2xl md:text-3xl lg:text-4xl 2xl:text-[42px] tabular-nums`}
                  >
                    {leaderboardValue(item, type)}
                  </span>
                  <span
                    className={`${slot.labelColor} font-medium leading-snug text-[10px] xsl:text-xs md:text-sm`}
                  >
                    {getDisplayLabel(item)}
                  </span>
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default LeaderboardPodium;
