"use client";

import React from "react";
import { cn } from "@/lib/utils";

export const STORY_RING_PX = 2.5;
export const STORY_AVATAR_SIZE = 56;
export const STORY_RING_OUTER_SIZE = STORY_AVATAR_SIZE + STORY_RING_PX * 2;

export const TIER_RING_COLORS = {
  blue: "#2196EB",
  green: "#22C55E",
  gold: "#EAB308",
} as const;

export type StoryRingTierColor = "blue" | "green" | "gold" | null;

export function verifyBadgeToTierColor(verifyBadge?: string | null): StoryRingTierColor {
  if (verifyBadge === "blue" || verifyBadge === "green" || verifyBadge === "gold") {
    return verifyBadge;
  }
  return null;
}

interface StoryRingProps {
  hasStory?: boolean;
  hasUnviewed?: boolean;
  forceGradient?: boolean;
  /** When set (blue/green/gold), overrides the default gradient/gray ring with a flat tier color. Gray/none tiers should pass null/undefined to keep default behavior. */
  tierColor?: StoryRingTierColor;
  rounded?: "full" | "xl";
  avatarSize?: number;
  avatarRadius?: number;
  animated?: boolean;
  /** Applied to the outer wrapper (e.g. margin/shrink utilities) — never to the clipped inner avatar box. */
  className?: string;
  children: React.ReactNode;
}

export default function StoryRing({
  hasStory = false,
  hasUnviewed = false,
  forceGradient = false,
  tierColor = null,
  rounded = "full",
  avatarSize,
  avatarRadius,
  animated = true,
  className,
  children,
}: StoryRingProps) {
  const isXl = rounded === "xl";
  const resolvedAvatarSize =
    avatarSize ?? (isXl ? undefined : STORY_AVATAR_SIZE);
  const cornerRadius =
    avatarRadius ??
    (isXl ? 12 : resolvedAvatarSize ? resolvedAvatarSize / 2 : undefined);
  const innerRadius =
    cornerRadius != null
      ? Math.max(0, cornerRadius - (hasStory ? STORY_RING_PX : 0))
      : undefined;

  const outerRounded = isXl ? "rounded-xl" : "rounded-full";
  const innerRounded =
    innerRadius != null
      ? undefined
      : isXl
        ? "rounded-[calc(0.75rem-2.5px)]"
        : "rounded-full";

  // When there's no story, the ring layer isn't drawn — keep the total footprint
  // exactly equal to resolvedAvatarSize (matching the old "render bare children"
  // behavior) instead of the ring-inclusive size, so call sites whose surrounding
  // layout was built around "no story = original size" don't grow unexpectedly.
  const ringInset = hasStory ? STORY_RING_PX : 0;
  const outerSize =
    resolvedAvatarSize != null
      ? resolvedAvatarSize + (hasStory ? STORY_RING_PX * 2 : 0)
      : undefined;

  const gradient =
    "conic-gradient(from 210deg, #feda75, #fa7e1e, #d62976, #962fbf, #4f5bd5, #feda75)";

  const live = hasUnviewed || forceGradient;
  const ringBg = tierColor
    ? TIER_RING_COLORS[tierColor]
    : live
      ? gradient
      : "#a3a3a3";

  // Always render the same wrapper structure (same total size, same rounding)
  // regardless of hasStory — only the ring-color layer is conditional. This keeps
  // the box model identical between "has story" and "no story" avatars in the same
  // row/list, avoiding any vertical misalignment when only some rows show a ring.
  return (
    <div
      className={cn("relative inline-flex shrink-0 items-center justify-center", className)}
      style={
        outerSize != null
          ? { width: outerSize, height: outerSize }
          : undefined
      }
    >
      {hasStory && (
        <div
          className={cn(
            "absolute inset-0",
            outerRounded,
            !tierColor && live && animated && "story-ring-live"
          )}
          style={{ background: ringBg }}
          aria-hidden
        />
      )}
      <div
        className={cn(
          "relative z-[1] flex items-center justify-center overflow-hidden bg-white leading-none dark:bg-neutral-950",
          innerRounded
        )}
        style={{
          margin: ringInset,
          ...(innerRadius != null ? { borderRadius: innerRadius } : {}),
          ...(resolvedAvatarSize != null
            ? {
                width: resolvedAvatarSize,
                height: resolvedAvatarSize,
              }
            : { width: "100%", height: "100%" }),
        }}
      >
        <div className="h-full w-full [&_img]:h-full [&_img]:w-full [&_img]:object-cover [&>*]:h-full [&>*]:w-full">
          {children}
        </div>
      </div>
    </div>
  );
}
