"use client";

import Image from "next/image";
import { cn } from "@/lib/utils";
import { buildStorageUrl } from "./BaseUrl";
import StoryRing, { verifyBadgeToTierColor, STORY_RING_PX } from "@/components/stories/StoryRing";
import { useStoryMetaForUser } from "@/hooks/useStoryMetaForUser";

const sizeMap = {
  xxs: "h-5 w-5",
  xs: "h-8 w-8",
  sm: "h-10 w-10",
  chat: "h-14 w-14",
  md: "h-[72px] w-[72px]",
  lg: "h-[120px] w-[120px]",
  xl: "h-[280px] w-[280px]",
};

const sizePxMap: Record<keyof typeof sizeMap, number> = {
  xxs: 20,
  xs: 32,
  sm: 40,
  chat: 56,
  md: 72,
  lg: 120,
  xl: 280,
};

type ProfileAvatarProps = {
  src?: string | null;
  alt?: string;
  size?: keyof typeof sizeMap;
  rounded?: "2xl" | "xl" | "full";
  className?: string;
  fallback?: string;
  /** When provided, wraps the avatar in a story ring reflecting this user's story/verify-tier status. */
  userId?: string | null;
  verifyBadge?: string | null;
};

function ProfileAvatar({
  src,
  alt = "",
  size = "md",
  rounded = "2xl",
  className,
  fallback = "/images/fake-avatar.png",
  userId,
  verifyBadge,
}: ProfileAvatarProps) {
  const roundedClass =
    rounded === "full"
      ? "rounded-full"
      : rounded === "xl"
        ? "rounded-xl"
        : "rounded-2xl";

  const imageSrc = src ? buildStorageUrl(src) : fallback;

  const { hasStory, hasUnviewed } = useStoryMetaForUser(userId);

  // When wrapped in a StoryRing, `className` (margins, shrink, size overrides) must land
  // on the ring's outer box, not this inner <Image> — the ring's middle layer is a fixed-size
  // overflow-hidden box, so any margin applied here gets silently clipped instead of creating
  // visible spacing (see the search-list "avatar stuck to text" regression).
  const image = (
    <Image
      src={imageSrc}
      alt={alt}
      width={280}
      height={280}
      unoptimized
      className={cn(
        "profile-avatar aspect-square object-cover shrink-0",
        sizeMap[size],
        roundedClass,
        !userId && className
      )}
    />
  );

  if (!userId) {
    return image;
  }

  // Keep the total rendered footprint equal to sizePxMap[size] in both states.
  // StoryRing only adds ring padding when hasStory is true, so when it *is* true we
  // pre-shrink the photo by the ring's width; when it's false we pass the full size
  // (StoryRing then renders it 1:1, matching a plain avatar exactly). Either way the
  // outer box never grows/shrinks relative to a plain avatar, so wrapping a row's
  // avatar with a ring never shifts that row's height or the next element's position.
  const avatarSizeForRing = hasStory
    ? Math.max(0, sizePxMap[size] - STORY_RING_PX * 2)
    : sizePxMap[size];
  const cornerRadius = rounded === "full" ? avatarSizeForRing / 2 : rounded === "xl" ? 12 : 16;

  return (
    <StoryRing
      hasStory={hasStory}
      hasUnviewed={hasUnviewed}
      tierColor={verifyBadgeToTierColor(verifyBadge)}
      rounded={rounded === "full" ? "full" : "xl"}
      avatarSize={avatarSizeForRing}
      avatarRadius={cornerRadius}
      className={className}
    >
      {image}
    </StoryRing>
  );
}

export default ProfileAvatar;
