"use client";

import type { CSSProperties } from "react";
import type { Profile } from "@/lib/constants";
import { CREDIT_SHOP_ITEMS } from "@/lib/credits-catalog";

export function resolveAvatarDecorationUrl(decoration?: string | null): string | null {
  if (!decoration || typeof decoration !== "string") return null;
  const trimmed = decoration.trim();
  if (!trimmed) return null;
  if (/^https?:\/\//i.test(trimmed) || trimmed.startsWith("/")) {
    return trimmed;
  }
  const matchedCatalog = CREDIT_SHOP_ITEMS.find(
    (item) => item.type === "avatar_decoration" && (item.id === trimmed || item.assetId === trimmed)
  );
  const assetId = matchedCatalog?.assetId || trimmed;
  return `https://cdn.discordapp.com/avatar-decoration-presets/${assetId}.png?size=240&passthrough=true`;
}

export function resolveAvatarShape(
  shape?: string,
  frame?: string | null,
  hasDecoration?: boolean
): { containerStyle: CSSProperties; borderRadiusCss: string } {
  const cleanFrame = frame || "";

  // Demon Wings is a rounded-square armor frame; force matching rounded-square inner cutout
  if (cleanFrame === "demon-wings") {
    return {
      containerStyle: { borderRadius: "15%", clipPath: "none" },
      borderRadiusCss: "15%",
    };
  }

  // Discord avatar decorations are strictly circular (240px circle inside 288px canvas = 120%)
  if (hasDecoration) {
    return {
      containerStyle: { borderRadius: "50%", clipPath: "none" },
      borderRadiusCss: "50%",
    };
  }

  // When an avatar border frame (gold-laurel, cyber-neon, pixel-glow) is equipped,
  // polygon clip-paths (hexagon/star) cannot have a clean perimeter border, so normalize to circle
  if (cleanFrame && (shape === "hexagon" || shape === "star")) {
    return {
      containerStyle: { borderRadius: "50%", clipPath: "none" },
      borderRadiusCss: "50%",
    };
  }

  if (shape === "square") {
    return {
      containerStyle: { borderRadius: "10%" },
      borderRadiusCss: "10%",
    };
  }
  if (shape === "rounded") {
    return {
      containerStyle: { borderRadius: "24%" },
      borderRadiusCss: "24%",
    };
  }
  if (shape === "hexagon") {
    return {
      containerStyle: {
        borderRadius: 0,
        clipPath: "polygon(25% 5%,75% 5%,100% 50%,75% 95%,25% 95%,0 50%)",
      },
      borderRadiusCss: "0px",
    };
  }
  if (shape === "star") {
    return {
      containerStyle: {
        borderRadius: 0,
        clipPath: "polygon(50% 0%,61% 35%,98% 35%,68% 57%,79% 91%,50% 70%,21% 91%,32% 57%,2% 35%,39% 35%)",
      },
      borderRadiusCss: "0px",
    };
  }

  return {
    containerStyle: { borderRadius: "50%" },
    borderRadiusCss: "50%",
  };
}

export function resolveCardFrameRadius(cardFrame?: string | null, baseRadius = 20): number {
  if (cardFrame === "ornate-red") {
    return Math.max(15, Math.min(20, baseRadius));
  }
  return baseRadius;
}

export function ProfileAvatarBlock({
  profile,
  size = 92,
  discordDecorationUrl,
  discordAvatarUrl,
  margin = "0 auto 15px",
  fallbackPlaceholder = false,
}: {
  profile: Partial<Profile>;
  size?: number;
  discordDecorationUrl?: string | null;
  discordAvatarUrl?: string | null;
  margin?: string | number;
  fallbackPlaceholder?: boolean;
}) {
  const effectiveAvatarUrl =
    profile.use_discord_avatar && discordAvatarUrl ? discordAvatarUrl : profile.avatar_url || "";
  const isImg = /^https?:\/\//i.test(effectiveAvatarUrl) || effectiveAvatarUrl.startsWith("/");

  if (!isImg && !fallbackPlaceholder) {
    return null;
  }
  const accent = profile.accent || "#f5caca";
  const frame = profile.avatar_frame || "";

  const explicitDecorUrl = resolveAvatarDecorationUrl(profile.avatar_decoration);
  const activeDecorationUrl =
    explicitDecorUrl || (profile.discord_avatar_decoration && discordDecorationUrl ? discordDecorationUrl : null);

  const hasFrameOrDecor = Boolean(frame || activeDecorationUrl);
  const { containerStyle, borderRadiusCss } = resolveAvatarShape(
    profile.avatar_shape,
    frame,
    Boolean(activeDecorationUrl)
  );

  const effectiveMargin =
    hasFrameOrDecor && (margin === "0 auto 15px" || margin === "0 auto 16px")
      ? "6px auto 22px"
      : margin;

  return (
    <div
      style={{
        position: "relative",
        width: size,
        height: size,
        margin: effectiveMargin,
        display: "inline-block",
        flexShrink: 0,
      }}
    >
      <div
        style={{
          width: size,
          height: size,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          fontSize: Math.round(size * 0.45),
          background: "#0d0d13",
          border: hasFrameOrDecor ? "none" : `2px solid ${accent}`,
          boxShadow: hasFrameOrDecor ? "none" : `0 0 24px ${accent}88`,
          overflow: "hidden",
          ...containerStyle,
        }}
      >
        {isImg ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={effectiveAvatarUrl}
            alt=""
            style={{
              width: "100%",
              height: "100%",
              objectFit: "cover",
              display: "block",
            }}
          />
        ) : (
          effectiveAvatarUrl || "👤"
        )}
      </div>

      {/* Demon Wings Frame: calibrated to avatarFrame.png's exact opaque rail coordinates */}
      {frame === "demon-wings" && (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src="/addons/avatarFrame.png"
          alt=""
          style={{
            position: "absolute",
            top: "-13%",
            left: "-10%",
            width: "120%",
            height: "122%",
            maxWidth: "none",
            maxHeight: "none",
            objectFit: "fill",
            pointerEvents: "none",
            filter: "drop-shadow(0 0 10px rgba(227, 130, 130, 0.45))",
            zIndex: 4,
          }}
        />
      )}

      {/* Golden Laurel Frame: snug 24k gold rim + sculpted SVG laurel wreath */}
      {frame === "gold-laurel" && (
        <>
          <div
            style={{
              position: "absolute",
              inset: -2,
              borderRadius: borderRadiusCss,
              border: "2.5px solid #e57272",
              boxShadow:
                "0 0 14px rgba(229, 114, 114, 0.55), inset 0 0 8px rgba(229, 114, 114, 0.35)",
              pointerEvents: "none",
              zIndex: 4,
            }}
          />
          <svg
            viewBox="0 0 120 120"
            fill="none"
            aria-hidden="true"
            style={{
              position: "absolute",
              top: "50%",
              left: "50%",
              transform: "translate(-50%, -50%)",
              width: "122%",
              height: "122%",
              maxWidth: "none",
              maxHeight: "none",
              pointerEvents: "none",
              filter: "drop-shadow(0 2px 6px rgba(229, 114, 114, 0.45))",
              zIndex: 5,
            }}
          >
            <defs>
              <linearGradient id="goldLaurelGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" stopColor="#ffffff" />
                <stop offset="50%" stopColor="#e57272" />
                <stop offset="100%" stopColor="#edd7d7" />
              </linearGradient>
            </defs>
            {/* Outer delicate filigree ring */}
            <circle
              cx="60"
              cy="60"
              r="52"
              stroke="url(#goldLaurelGrad)"
              strokeWidth="1.2"
              strokeDasharray="3 3"
              opacity="0.75"
            />
            {/* Top diamond crest */}
            <polygon points="60,3 64,8 60,13 56,8" fill="url(#goldLaurelGrad)" />
            {/* Bottom ribbon clasp */}
            <polygon points="60,107 65,112 60,117 55,112" fill="url(#goldLaurelGrad)" />
            {/* Left & Right Laurel Leaf Clusters */}
            <g fill="url(#goldLaurelGrad)">
              <ellipse cx="14" cy="84" rx="5.5" ry="2.4" transform="rotate(-35 14 84)" />
              <ellipse cx="9" cy="68" rx="5.8" ry="2.4" transform="rotate(-15 9 68)" />
              <ellipse cx="9" cy="52" rx="5.8" ry="2.4" transform="rotate(15 9 52)" />
              <ellipse cx="14" cy="36" rx="5.5" ry="2.4" transform="rotate(35 14 36)" />
              <ellipse cx="24" cy="22" rx="5.2" ry="2.2" transform="rotate(55 24 22)" />
              <ellipse cx="106" cy="84" rx="5.5" ry="2.4" transform="rotate(35 106 84)" />
              <ellipse cx="111" cy="68" rx="5.8" ry="2.4" transform="rotate(15 111 68)" />
              <ellipse cx="111" cy="52" rx="5.8" ry="2.4" transform="rotate(-15 111 52)" />
              <ellipse cx="106" cy="36" rx="5.5" ry="2.4" transform="rotate(-35 106 36)" />
              <ellipse cx="96" cy="22" rx="5.2" ry="2.2" transform="rotate(-55 96 22)" />
            </g>
          </svg>
        </>
      )}

      {/* Cyber Neon Frame: snug dual-layer cyan & ultraviolet border matching avatar shape */}
      {frame === "cyber-neon" && (
        <>
          <div
            style={{
              position: "absolute",
              inset: -2,
              borderRadius: borderRadiusCss,
              border: "2.5px solid #f5caca",
              boxShadow:
                "0 0 14px rgba(245, 202, 202, 0.8), inset 0 0 10px rgba(247, 217, 217, 0.65)",
              pointerEvents: "none",
              zIndex: 4,
              animation: "titlePulse 2.5s ease-in-out infinite",
            }}
          />
          <div
            style={{
              position: "absolute",
              inset: -5,
              borderRadius: borderRadiusCss,
              border: "1px solid rgba(247, 217, 217, 0.65)",
              boxShadow: "0 0 18px rgba(247, 217, 217, 0.4)",
              pointerEvents: "none",
              zIndex: 4,
            }}
          />
        </>
      )}

      {/* Pixel Glow Frame: flush inner border + snug segmented pixel ring matching avatar shape */}
      {frame === "pixel-glow" && (
        <>
          <div
            style={{
              position: "absolute",
              inset: -1,
              borderRadius: borderRadiusCss,
              border: "2px solid rgba(255, 255, 255, 0.9)",
              boxShadow: "inset 0 0 8px rgba(255, 255, 255, 0.35)",
              pointerEvents: "none",
              zIndex: 4,
            }}
          />
          <div
            style={{
              position: "absolute",
              inset: -4,
              borderRadius: borderRadiusCss,
              border: "2px dashed #ffffff",
              boxShadow: "0 0 14px rgba(255, 255, 255, 0.65)",
              pointerEvents: "none",
              zIndex: 4,
            }}
          />
        </>
      )}

      {/* Discord Avatar Decoration: 288x288 preset canvas = exact 120% of 240x240 circular avatar */}
      {activeDecorationUrl && (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={activeDecorationUrl}
          alt=""
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: "120%",
            height: "120%",
            maxWidth: "none",
            maxHeight: "none",
            objectFit: "contain",
            pointerEvents: "none",
            zIndex: 6,
          }}
        />
      )}
    </div>
  );
}

export function CardFrameOverlay({
  cardFrame,
  cardRadius = 20,
}: {
  cardFrame?: string | null;
  cardRadius?: number;
}) {
  if (!cardFrame) return null;

  if (cardFrame === "ornate-red") {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src="/addons/cardFrame.png"
        alt=""
        style={{
          position: "absolute",
          left: "-2.6%",
          top: "-4%",
          width: "105.2%",
          height: "109%",
          maxWidth: "none",
          maxHeight: "none",
          objectFit: "fill",
          zIndex: 10,
          pointerEvents: "none",
          filter: "drop-shadow(0 6px 16px rgba(0,0,0,0.75))",
        }}
      />
    );
  }

  if (cardFrame === "cyber-grid") {
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          borderRadius: cardRadius,
          border: "2px solid rgba(250, 229, 229, 0.85)",
          boxShadow:
            "0 0 22px rgba(250, 229, 229, 0.35), inset 0 0 14px rgba(250, 229, 229, 0.18), inset 0 0 0 3px rgba(250, 229, 229, 0.12)",
          pointerEvents: "none",
          zIndex: 10,
        }}
      />
    );
  }

  if (cardFrame === "royal-gold") {
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          borderRadius: cardRadius,
          border: "2px solid rgba(246, 230, 230, 0.85)",
          outline: "1px dashed rgba(246, 230, 230, 0.45)",
          outlineOffset: "3px",
          boxShadow:
            "0 0 24px rgba(246, 230, 230, 0.28), inset 0 0 0 3px rgba(246, 230, 230, 0.15)",
          pointerEvents: "none",
          zIndex: 10,
        }}
      />
    );
  }

  if (cardFrame === "abyss-smoke") {
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          borderRadius: cardRadius,
          border: "2px solid rgba(247, 217, 217, 0.78)",
          boxShadow:
            "0 0 28px rgba(247, 217, 217, 0.4), inset 0 0 18px rgba(247, 217, 217, 0.22)",
          pointerEvents: "none",
          zIndex: 10,
        }}
      />
    );
  }

  return null;
}
