"use client";

import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
import { Eye, MapPin, ExternalLink } from "lucide-react";
import ProfileShareButton from "./ProfileShareButton";
import { PLATFORMS } from "./platforms";
import BrandIcon from "./BrandIcon";
import BadgeIcon from "./BadgeIcon";
import { BACKGROUNDS, badgesFromDiscordRoleIds, isCustomBadgeNameReserved, type BadgeItem, type Profile } from "@/lib/constants";
import { badgesForProfile } from "@/lib/profile-badges";
import DiscordCard from "./modules/DiscordCard";
import Clock from "./modules/Clock";
import ProfileBookmarkButton from "./ProfileLikeButton";
import ProfileTipButton from "./ProfileTipButton";
import FalseCardSections from "./FalseCardSections";
import CusDeveloperSection from "./CusDeveloperSection";
import { CardFrameOverlay, ProfileAvatarBlock, resolveCardFrameRadius } from "./ProfileCosmetics";

function fontFamily(font?: string) {
  if (font === "JetBrains Mono") return "monospace";
  if (font === "Fira Code") return "'Fira Code', monospace";
  if (font) return `${font}, Inter, system-ui, sans-serif`;
  return "Inter, system-ui, sans-serif";
}


function hrefFor(raw?: string) {
  const value = raw || "";
  if (!value) return "#";
  if (value.startsWith("mailto:")) return value;
  return value.startsWith("http") ? value : `https://${value.replace(/^https?:\/\//, "")}`;
}

function LinkIcons({ profile }: { profile: Profile }) {
  const accent = profile.accent || "#f5caca";
  const iconColor = profile.monochrome_icons ? (profile.link_color || "#000000") : (profile.link_color || accent);
  const links = (profile.links || []).filter((l) => !l.hidden && (l.url || l.platform));

  if (links.length === 0) return null;

  const isButtons = profile.link_style === "buttons";

  if (isButtons) {
    return (
      <div style={{ display: "grid", gap: 9, marginTop: 20, width: "100%" }}>
        {links.map((l) => {
          const P = PLATFORMS[l.platform] || PLATFORMS.website;
          const customImg = l.platform === "website" && /^https?:\/\//.test(l.image_url || "");
          const label = l.label || P.label;
          let hostname = "";
          try {
            const parsed = new URL(hrefFor(l.url));
            hostname = parsed.hostname.replace(/^www\./, "");
          } catch {
            hostname = l.url;
          }

          return (
            <a
              key={l.id}
              href={hrefFor(l.url)}
              target="_blank"
              rel="noreferrer"
              onClick={() => {
                try {
                  navigator.sendBeacon?.(`/api/sys/click`, new Blob([JSON.stringify({ username: profile.username, url: l.url })], { type: "text/plain" }));
                } catch {}
              }}
              className="profileLinkButton"
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                gap: 12,
                padding: "10px 14px",
                borderRadius: 12,
                background: "rgba(0, 0, 0, 0.04)",
                border: "1px solid rgba(0, 0, 0, 0.08)",
                textDecoration: "none",
                color: "#000000",
                transition: "all 0.16s ease",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: 8,
                    overflow: "hidden",
                    display: "grid",
                    placeItems: "center",
                    background: "rgba(0, 0, 0, 0.05)",
                    border: "1px solid rgba(0, 0, 0, 0.08)",
                    color: iconColor,
                    flexShrink: 0,
                  }}
                >
                  {customImg ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={l.image_url} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                  ) : (
                    <BrandIcon platform={l.platform} size={18} monochrome={!!profile.monochrome_icons} color={iconColor} />
                  )}
                </div>
                <div style={{ minWidth: 0, textAlign: "left" }}>
                  <span style={{ display: "block", fontSize: 13.5, fontWeight: 700, color: profile.text_color || "#000000", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {label}
                  </span>
                  <span style={{ display: "block", fontSize: 11, color: "#3c0f0f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {hostname}
                  </span>
                </div>
              </div>
              <ExternalLink size={14} style={{ color: "#341212", flexShrink: 0 }} />
            </a>
          );
        })}
      </div>
    );
  }

  return (
    <div style={{ display: "flex", gap: 14, marginTop: 18, flexWrap: "wrap", justifyContent: "center" }}>
      {links.map((l) => {
        const P = PLATFORMS[l.platform] || PLATFORMS.website;
        const customImg = l.platform === "website" && /^https?:\/\//.test(l.image_url || "");
        const label = l.label || P.label;
        return (
          <div key={l.id} className="badgeTipWrap">
            <a
              href={hrefFor(l.url)}
              target="_blank"
              rel="noreferrer"
              aria-label={label}
              onClick={() => {
                try {
                  navigator.sendBeacon?.(`/api/sys/click`, new Blob([JSON.stringify({ username: profile.username, url: l.url })], { type: "text/plain" }));
                } catch {}
              }}
              style={{
                width: 28,
                height: 28,
                display: "grid",
                placeItems: "center",
                color: iconColor,
                opacity: 0.95,
                transition: "all .15s",
                borderRadius: 8,
                overflow: "hidden",
              }}
            >
              {customImg ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={l.image_url} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", aspectRatio: "1 / 1" }} />
              ) : (
                <BrandIcon platform={l.platform} size={24} monochrome={!!profile.monochrome_icons} color={iconColor} />
              )}
            </a>
            <span className="badgeTipBox">{label}</span>
          </div>
        );
      })}
    </div>
  );
}

function useDiscordPresenceCosmetics(profile: Profile) {
  const [badges, setBadges] = useState<BadgeItem[]>([]);
  const [discordAvatarUrl, setDiscordAvatarUrl] = useState<string | null>(null);
  const [discordDecorationUrl, setDiscordDecorationUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!profile.discord_id) {
      setBadges([]);
      setDiscordAvatarUrl(null);
      setDiscordDecorationUrl(null);
      return;
    }
    let alive = true;
    async function loadBadges() {
      try {
        const res = await fetch(`/api/discord/presence/${profile.discord_id}`);
        const data = await res.json();
        if (!alive) return;
        const roleIds = Array.isArray(data?.member?.roles) ? data.member.roles : Array.isArray(data?.roles) ? data.roles : [];
        setBadges(badgesFromDiscordRoleIds(roleIds.map(String)));
        setDiscordAvatarUrl(typeof data?.user?.avatar_url === "string" ? data.user.avatar_url : null);
        setDiscordDecorationUrl(typeof data?.user?.avatar_decoration_url === "string" ? data.user.avatar_decoration_url : null);
      } catch {
        if (alive) {
          setBadges([]);
          setDiscordAvatarUrl(null);
          setDiscordDecorationUrl(null);
        }
      }
    }
    loadBadges();
    return () => { alive = false; };
  }, [profile.discord_id]);

  return { badges, discordAvatarUrl, discordDecorationUrl };
}

function BadgeStrip({ profile, badges }: { profile: Profile; badges: BadgeItem[] }) {
  if (badges.length === 0) return null;
  const badgeColor = profile.icon_color || "#000000";

  return (
    <div
      style={{
        display: "inline-flex",
        flexDirection: "row",
        gap: 7,
        alignItems: "center",
        flexWrap: "wrap",
        justifyContent: "center",
      }}
    >
      {badges.map((badge) => {
        const isCustom = !!badge.custom || badge.id?.startsWith("custom-");
        if (isCustom && isCustomBadgeNameReserved(badge.name)) return null;
        const isPremiumBadge = badge.id === "premium" || badge.name.toLowerCase() === "premium";
        const isVerifiedBadge = badge.id === "verified" || badge.name.toLowerCase() === "verified";
        const href = isPremiumBadge ? "/premium" : isVerifiedBadge ? "/addons" : undefined;

        const badgeInner = (
          <span
            key={badge.id}
            aria-label={badge.name}
            className="badgeTipWrap badgeIconOnly"
            style={{
              display: "inline-grid",
              placeItems: "center",
              width: badge.image_url ? 18 : "auto",
              height: badge.image_url ? 18 : "auto",
              fontSize: 16,
              lineHeight: 1,
              color: isCustom ? "inherit" : badgeColor,
              textShadow: !isCustom && profile.badges_glow !== false ? `0 0 12px ${badgeColor}` : "none",
              cursor: href ? "pointer" : "help",
            }}
          >
            <BadgeIcon
              badge={badge}
              monochrome={profile.monochrome_icons !== false}
              color={badgeColor}
              glow={!isCustom && profile.badges_glow !== false}
              size={18}
            />
            <span className="badgeTipBox">
              {badge.name}{isPremiumBadge ? " · Get Premium" : isVerifiedBadge ? " · Get Verified" : ""}
            </span>
          </span>
        );

        if (href) {
          return (
            <a
              key={badge.id}
              href={href}
              target="_blank"
              rel="noopener noreferrer"
              style={{ textDecoration: "none", color: "inherit", display: "inline-grid" }}
              title={isPremiumBadge ? "Upgrade to Lifetime Premium" : "Get Verified on sinss.lol"}
            >
              {badgeInner}
            </a>
          );
        }

        return badgeInner;
      })}
    </div>
  );
}

function HandleTooltip({ profile, children }: { profile: Profile; children: ReactNode }) {
  const idLabel = profile.public_uid ? `UUID #${profile.public_uid}` : profile.id ? `Account ${profile.id}` : "Account";
  return (
    <span className="handleTipWrap">
      <span className="handleTipText">{children}</span>
      <span className="handleTipBox">{idLabel}</span>
    </span>
  );
}

function ModuleCards({ profile }: { profile: Profile }) {
  const modules = profile.modules || [];
  const showDiscord = modules.includes("discord") && profile.discord_enabled === true;
  const showClock = modules.includes("clock");
  if (!showDiscord && !showClock) return null;

  return (
    <div style={{ display: "grid", gap: 10 }}>
      {showDiscord && <DiscordCard profile={profile} />}
      {showClock && <Clock profile={profile} />}
    </div>
  );
}

function StatsRow({ profile }: { profile: Profile }) {
  const joined = profile.created_at ? new Date(profile.created_at).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }) : "";
  return (
    <div style={{ marginTop: 20, display: "flex", justifyContent: "center", gap: 16, color: "#340808", fontSize: 12, flexWrap: "wrap" }}>
      {!profile.hide_views && <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Eye size={14} /> {(profile.views || 0).toLocaleString()}</span>}
      {!(profile.hide_bookmarks || profile.hide_likes) && <ProfileBookmarkButton username={profile.username} initialBookmarks={Number(profile.bookmark_count ?? profile.like_count ?? 0)} accent={profile.accent || "#f5caca"} />}
      <ProfileTipButton username={profile.username} accent={profile.accent || "#f5caca"} />
      <ProfileShareButton username={profile.username} displayName={profile.display_name} accent={profile.accent || "#f5caca"} />
      {!profile.hide_join_date && joined && <span>Joined {joined}</span>}
    </div>
  );
}

function isVideoBackground(url?: string) {
  return /\.(mp4|webm|mov)(\?|#|$)/i.test(url || "");
}

function Background({ profile, entered }: { profile: Profile; entered: boolean }) {
  const accent = profile.accent || "#f5caca";
  const hasBgMedia = /^https?:\/\//.test(profile.background_url || "");
  const hasBgVideo = hasBgMedia && isVideoBackground(profile.background_url);
  const fallbackBg = profile.background_color || (BACKGROUNDS[profile.bg] || BACKGROUNDS.midnight);
  const mediaStyle = {
    position: "absolute" as const,
    inset: -10,
    width: "calc(100% + 20px)",
    height: "calc(100% + 20px)",
    objectFit: "cover" as const,
    objectPosition: "center",
    filter: profile.background_effect === "blurred" ? "blur(4px)" : "none",
    transform: "scale(1.03)",
  };
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    if (entered) video.play().catch(() => {});
    else video.pause();
  }, [entered]);

  return (
    <>
      {hasBgMedia && (
        hasBgVideo ? (
          <video
            ref={videoRef}
            src={profile.background_url}
            autoPlay={entered}
            muted
            loop
            playsInline
            preload={entered ? "auto" : "none"}
            style={mediaStyle}
          />
        ) : (
          <div
            style={{
              ...mediaStyle,
              backgroundImage: `url(${profile.background_url})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
            }}
          />
        )
      )}
      <div
        style={{
          position: "absolute",
          inset: -20,
          pointerEvents: "none",
          background: hasBgMedia
            ? profile.background_effect === "none"
              ? "transparent"
              : profile.background_effect === "darken"
                ? "rgba(0,0,0,.62)"
                : "linear-gradient(180deg, rgba(0,0,0,.18), rgba(0,0,0,.58))"
            : profile.profile_gradient
              ? `radial-gradient(circle at 50% 20%, ${accent}55, transparent 48%), linear-gradient(180deg, ${profile.background_color || "#050505"}, #000)`
              : fallbackBg,
          animation: profile.effect === "glow" ? "glow 4s ease-in-out infinite" : "none",
        }}
      />
    </>
  );
}

function NameBlock({ profile, badges, align = "center" }: { profile: Profile; badges: BadgeItem[]; align?: "center" | "left" }) {
  const text = profile.text_color || "#000000";
  const accent = profile.accent || "#f5caca";
  const animated = profile.animated_title && profile.username_effect !== "none";
  const isTypewriter = profile.username_effect === "typewriter";
  return (
    <div style={{ textAlign: align }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: align === "center" ? "center" : "flex-start", gap: 8, flexWrap: "wrap" }}>
        <HandleTooltip profile={profile}>
          <h1
            className={[animated ? `nameEffect ${profile.username_effect}` : "", profile.is_promoter ? "promoterUsernameShimmer" : ""].filter(Boolean).join(" ") || undefined}
            style={{
              fontSize: 28,
              fontWeight: 900,
              margin: 0,
              padding: isTypewriter ? "2px 4px" : undefined,
              color: text,
              letterSpacing: "-.03em",
              textShadow: animated ? (isTypewriter ? `0 0 10px ${accent}88` : `0 0 18px ${accent}`) : "none",
              whiteSpace: isTypewriter ? "nowrap" : "normal",
              overflow: isTypewriter ? "hidden" : "visible",
              display: isTypewriter ? "inline-block" : "block",
              borderRight: isTypewriter ? `2px solid ${accent}` : "none",
              animation: profile.animated_title && profile.username_effect === "sparkle" ? "titlePulse 2.4s ease-in-out infinite" : profile.animated_title && isTypewriter ? "typewriterName 4.8s steps(24,end) infinite, caretBlink .8s step-end infinite" : "none",
            }}
          >
            {profile.display_name || profile.username}

          </h1>
        </HandleTooltip>
        <BadgeStrip profile={profile} badges={badges} />
      </div>
      {(!profile.hide_username || !profile.display_name?.trim()) && (
        <p style={{ margin: "4px 0 0", fontSize: 13, color: "#600707" }}>@{profile.username}</p>
      )}
      {profile.alias && !profile.hide_alias && <p style={{ margin: "3px 0 0", fontSize: 12, color: "#230707" }}>alias: @{profile.alias}</p>}
      {profile.pronouns && <p style={{ margin: "4px 0 0", fontSize: 12, color: "#230707" }}>{profile.pronouns}</p>}
    </div>
  );
}

export default function ProfileCard({ profile, entered = true, audioPlayer, lyricsBox, visualizer, previewMode = false }: { profile: Profile; entered?: boolean; audioPlayer?: ReactNode; lyricsBox?: ReactNode; visualizer?: ReactNode; previewMode?: boolean }) {
  const accent = profile.accent || "#f5caca";
  const text = profile.text_color || "#000000";
  const opacity = Math.max(0, Math.min(100, profile.profile_opacity ?? 70)) / 100;
  const blur = Math.max(0, Math.min(100, profile.profile_blur ?? 22));
  const followsCursor = profile.profile_animation === "follow-cursor";
  const cursorIntensity = Math.max(0, Math.min(100, profile.cursor_follow_intensity ?? 55)) / 100;
  const rawCardRadius = Math.max(0, Math.min(48, profile.profile_card_radius ?? 20));
  const cardRadius = resolveCardFrameRadius(profile.card_frame, rawCardRadius);
  const cardBorderWidth = Math.max(0, Math.min(4, profile.profile_card_border_width ?? 1));
  const cardBorderColor = profile.profile_card_border_color || accent;
  const { badges: roleBadges, discordAvatarUrl, discordDecorationUrl } = useDiscordPresenceCosmetics(profile);
  const visibleBadges = badgesForProfile(profile, roleBadges);
  const effectiveAvatarUrl =
    profile.use_discord_avatar && discordAvatarUrl ? discordAvatarUrl : profile.avatar_url || "";
  const hasAvatar = Boolean(
    effectiveAvatarUrl &&
    (/^https?:\/\//i.test(effectiveAvatarUrl) || effectiveAvatarUrl.startsWith("/"))
  );
  const followStageRef = useRef<HTMLDivElement | null>(null);
  const followCardRef = useRef<HTMLElement | null>(null);
  const followMotionRef = useRef({
    tiltX: 0,
    tiltY: 0,
    translateX: 0,
    translateY: 0,
    scale: 1,
    glareX: 50,
    glareY: 35,
    targetTiltX: 0,
    targetTiltY: 0,
    targetTranslateX: 0,
    targetTranslateY: 0,
    targetScale: 1,
    targetGlareX: 50,
    targetGlareY: 35,
    frame: null as number | null,
    lastFrameTime: 0,
  });
  const panelBackground = opacity <= 0 ? "transparent" : `rgba(12,12,16,${opacity})`;
  const hasCardFrame = Boolean(profile.card_frame);
  const isOrnateRedFrame = profile.card_frame === "ornate-red";
  const showPromoterAura = Boolean(profile.is_promoter && !profile.hide_promoter_aura);
  const panel = {
    background: panelBackground,
    backdropFilter: blur <= 0 ? "none" : `blur(${blur}px)`,
    WebkitBackdropFilter: blur <= 0 ? "none" : `blur(${blur}px)`,
    border: opacity <= 0 || cardBorderWidth === 0 || hasCardFrame ? "1px solid transparent" : `${cardBorderWidth}px solid ${cardBorderColor}88`,
    boxShadow: opacity <= 0 ? "none" : `0 0 0 1px #00000008, 0 22px 70px -28px ${accent}`,
  } as const;

  const isPortfolio = profile.layout === "portfolio";
  const isCompact = profile.layout === "compact";
  const isMinimal = profile.layout === "minimal";
  const isBanner = profile.layout === "banner";
  const isFalseProfile = profile.username?.toLowerCase() === "false";
  const isCusProfile = profile.username?.toLowerCase() === "cus";
  const layoutWidth = isPortfolio || isBanner ? 760 : isFalseProfile ? 540 : isCusProfile ? 480 : isCompact ? 360 : isMinimal ? 520 : 430;
  const configuredWidth = Math.max(320, Math.min(900, profile.profile_card_width ?? layoutWidth));
  const cardWidth = configuredWidth;

  const animateFollowCard = () => {
    const motion = followMotionRef.current;
    if (motion.frame !== null) return;

    const animate = (time: number) => {
      const card = followCardRef.current;
      if (!card) {
        motion.frame = null;
        return;
      }

      const delta = motion.lastFrameTime ? Math.min(time - motion.lastFrameTime, 48) : 16;
      const damping = 1 - Math.exp(-delta / 75);
      motion.lastFrameTime = time;
      motion.tiltX += (motion.targetTiltX - motion.tiltX) * damping;
      motion.tiltY += (motion.targetTiltY - motion.tiltY) * damping;
      motion.translateX += (motion.targetTranslateX - motion.translateX) * damping;
      motion.translateY += (motion.targetTranslateY - motion.translateY) * damping;
      motion.scale += (motion.targetScale - motion.scale) * damping;
      motion.glareX += (motion.targetGlareX - motion.glareX) * damping;
      motion.glareY += (motion.targetGlareY - motion.glareY) * damping;

      card.style.setProperty("--profile-tilt-x", `${motion.tiltX}deg`);
      card.style.setProperty("--profile-tilt-y", `${motion.tiltY}deg`);
      card.style.setProperty("--profile-translate-x", `${motion.translateX}px`);
      card.style.setProperty("--profile-translate-y", `${motion.translateY}px`);
      card.style.setProperty("--profile-card-scale", String(motion.scale));
      card.style.setProperty("--profile-glare-x", `${motion.glareX}%`);
      card.style.setProperty("--profile-glare-y", `${motion.glareY}%`);

      const remaining = Math.max(
        Math.abs(motion.targetTiltX - motion.tiltX),
        Math.abs(motion.targetTiltY - motion.tiltY),
        Math.abs(motion.targetTranslateX - motion.translateX),
        Math.abs(motion.targetTranslateY - motion.translateY),
        Math.abs(motion.targetScale - motion.scale) * 100,
        Math.abs(motion.targetGlareX - motion.glareX) / 10,
        Math.abs(motion.targetGlareY - motion.glareY) / 10,
      );

      if (remaining > 0.015) {
        motion.frame = requestAnimationFrame(animate);
      } else {
        motion.tiltX = motion.targetTiltX;
        motion.tiltY = motion.targetTiltY;
        motion.translateX = motion.targetTranslateX;
        motion.translateY = motion.targetTranslateY;
        motion.scale = motion.targetScale;
        motion.glareX = motion.targetGlareX;
        motion.glareY = motion.targetGlareY;
        card.style.setProperty("--profile-tilt-x", `${motion.tiltX}deg`);
        card.style.setProperty("--profile-tilt-y", `${motion.tiltY}deg`);
        card.style.setProperty("--profile-translate-x", `${motion.translateX}px`);
        card.style.setProperty("--profile-translate-y", `${motion.translateY}px`);
        card.style.setProperty("--profile-card-scale", String(motion.scale));
        card.style.setProperty("--profile-glare-x", `${motion.glareX}%`);
        card.style.setProperty("--profile-glare-y", `${motion.glareY}%`);
        motion.frame = null;
        motion.lastFrameTime = 0;
      }
    };

    motion.frame = requestAnimationFrame(animate);
  };

  const handleCardPointerMove = (event: ReactPointerEvent<HTMLElement>) => {
    if (!followsCursor || event.pointerType === "touch") return;
    const stage = followStageRef.current;
    const card = followCardRef.current;
    if (!stage || !card) return;
    const rect = stage.getBoundingClientRect();
    const horizontal = Math.max(-1, Math.min(1, ((event.clientX - rect.left - card.offsetLeft) / card.offsetWidth - 0.5) * 2));
    const vertical = Math.max(-1, Math.min(1, ((event.clientY - rect.top - card.offsetTop) / card.offsetHeight - 0.5) * 2));
    const maxTilt = 9 * cursorIntensity;
    const motion = followMotionRef.current;
    motion.targetTiltX = -vertical * maxTilt;
    motion.targetTiltY = horizontal * maxTilt;
    motion.targetTranslateX = horizontal * cursorIntensity * 4;
    motion.targetTranslateY = vertical * cursorIntensity * 4;
    motion.targetScale = 1 + cursorIntensity * 0.012;
    motion.targetGlareX = (horizontal + 1) * 50;
    motion.targetGlareY = (vertical + 1) * 50;
    animateFollowCard();
  };

  const resetCardTilt = () => {
    const motion = followMotionRef.current;
    motion.targetTiltX = 0;
    motion.targetTiltY = 0;
    motion.targetTranslateX = 0;
    motion.targetTranslateY = 0;
    motion.targetScale = 1;
    motion.targetGlareX = 50;
    motion.targetGlareY = 35;
    animateFollowCard();
  };

  return (
    <div
      suppressHydrationWarning
      style={{
        position: "relative",
        width: "100%",
        minHeight: previewMode ? "100%" : "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: previewMode ? "16px 12px" : 28,
        borderRadius: "inherit",
        overflow: "hidden",
        background: profile.background_color || "#050507",
        fontFamily: fontFamily(profile.font),
      }}
    >
      <Background profile={profile} entered={entered} />
      {visualizer}

      <div ref={followStageRef} suppressHydrationWarning style={{ position: "relative", zIndex: 3, width: "100%", maxWidth: cardWidth, display: "grid", gap: 12 }}>
        <section
          ref={followCardRef}
          suppressHydrationWarning
          className={[followsCursor ? "cursorFollowCard" : "", isOrnateRedFrame ? "hasOrnateRedFrame" : "", showPromoterAura ? "promoterCardAura" : ""].filter(Boolean).join(" ") || undefined}
          onPointerMove={followsCursor ? handleCardPointerMove : undefined}
          onPointerLeave={followsCursor ? resetCardTilt : undefined}
          onPointerCancel={followsCursor ? resetCardTilt : undefined}
          style={{
            width: "100%",
            marginTop: isOrnateRedFrame ? 14 : 0,
            marginBottom: isOrnateRedFrame ? 18 : 0,
            padding: isOrnateRedFrame
              ? isPortfolio || isBanner
                ? hasAvatar ? "46px 52px 54px" : "38px 46px 42px"
                : isCompact
                  ? hasAvatar ? "44px 36px 52px" : "36px 32px 40px"
                  : isMinimal
                    ? "44px 44px 52px"
                    : hasAvatar ? "48px 52px 58px" : "38px 46px 44px"
              : isPortfolio || isBanner
                ? hasAvatar ? "26px" : "22px 24px"
                : isCompact
                  ? hasAvatar ? "22px 20px 18px" : "18px 20px 18px"
                  : isMinimal
                    ? "24px"
                    : hasAvatar ? "30px 26px 22px" : "24px 26px 22px",
            borderRadius: cardRadius,
            textAlign: isPortfolio || isBanner ? "left" : "center",
            animation: profile.profile_animation === "float"
              ? (showPromoterAura ? "float 7s ease-in-out infinite, promoterPulseAura 4s ease-in-out infinite" : "float 7s ease-in-out infinite")
              : (showPromoterAura ? "promoterPulseAura 4s ease-in-out infinite" : "none"),
            position: "relative",
            transform: followsCursor ? "perspective(1000px) translate3d(var(--profile-translate-x,0px),var(--profile-translate-y,0px),0) rotateX(var(--profile-tilt-x,0deg)) rotateY(var(--profile-tilt-y,0deg)) scale3d(var(--profile-card-scale,1),var(--profile-card-scale,1),var(--profile-card-scale,1))" : undefined,
            transformOrigin: "center",
            transformStyle: "preserve-3d",
            transition: followsCursor ? "box-shadow 180ms ease" : undefined,
            willChange: followsCursor ? "transform" : undefined,
            ...panel,
          }}
        >
          <CardFrameOverlay cardFrame={profile.card_frame} cardRadius={cardRadius} />
          {isPortfolio || isBanner ? (
            <div
              style={{
                display: "grid",
                gridTemplateColumns: !hasAvatar
                  ? "minmax(0,1fr)"
                  : isBanner
                    ? "minmax(0,1fr) 120px"
                    : "120px minmax(0,1fr)",
                gap: hasAvatar ? 22 : 0,
                alignItems: "center",
              }}
            >
              {!isBanner && hasAvatar && (
                <div>
                  <ProfileAvatarBlock
                    profile={profile}
                    size={112}
                    discordAvatarUrl={discordAvatarUrl}
                    discordDecorationUrl={discordDecorationUrl}
                  />
                </div>
              )}
              <div>
                <NameBlock profile={profile} badges={visibleBadges} align="left" />
                {profile.bio && <p style={{ margin: "12px 0 0", fontSize: 15, lineHeight: 1.5, color: text }}>{profile.bio}</p>}
                {profile.location && (
                  <p style={{ margin: "10px 0 0", fontSize: 13, color: "#530808", display: "inline-flex", gap: 5, alignItems: "center" }}>
                    <MapPin size={14} /> {profile.location}
                  </p>
                )}
                <LinkIcons profile={profile} />
                <StatsRow profile={profile} />
                {isFalseProfile && <FalseCardSections accent={accent} />}
                {isCusProfile && <CusDeveloperSection accent={accent} />}
              </div>
              {isBanner && hasAvatar && (
                <div>
                  <ProfileAvatarBlock
                    profile={profile}
                    size={112}
                    discordAvatarUrl={discordAvatarUrl}
                    discordDecorationUrl={discordDecorationUrl}
                  />
                </div>
              )}
            </div>
          ) : (
            <>
              {!isMinimal && hasAvatar && (
                <ProfileAvatarBlock
                  profile={profile}
                  size={isCompact ? 76 : 92}
                  discordAvatarUrl={discordAvatarUrl}
                  discordDecorationUrl={discordDecorationUrl}
                />
              )}
              <NameBlock profile={profile} badges={visibleBadges} />
              {profile.bio && <p style={{ margin: "12px 0 0", fontSize: isCompact ? 14 : 15, lineHeight: 1.45, color: text }}>{profile.bio}</p>}
              {profile.location && (
                <p style={{ margin: "10px 0 0", fontSize: 13, color: "#530808", display: "inline-flex", gap: 5, alignItems: "center" }}>
                  <MapPin size={14} /> {profile.location}
                </p>
              )}
              <LinkIcons profile={profile} />
              <StatsRow profile={profile} />
              {isFalseProfile && <FalseCardSections accent={accent} />}
              {isCusProfile && <CusDeveloperSection accent={accent} />}
            </>
          )}
        </section>

        {audioPlayer}
        {lyricsBox}
        <ModuleCards profile={profile} />
      </div>

      <style dangerouslySetInnerHTML={{ __html: `
        .cursorFollowCard::before { content: ""; position: absolute; inset: 0; z-index: 0; pointer-events: none; border-radius: inherit; background: radial-gradient(circle at var(--profile-glare-x,50%) var(--profile-glare-y,35%), rgba(0, 0, 0, .16), transparent 48%); opacity: .72; }
        .cursorFollowCard > * { position: relative; z-index: 1; }
        .profileLinkButton:hover { border-color: rgba(0, 0, 0, 0.22) !important; background: rgba(0, 0, 0, 0.08) !important; transform: translateY(-1px); }
        @keyframes titlePulse {
          0%,100% { filter: brightness(1); transform: translateY(0); }
          50% { filter: brightness(1.25); transform: translateY(-1px); }
        }
        .handleTipWrap { position: relative; display: inline-flex; align-items: center; justify-content: center; cursor: default; }
        .handleTipBox { position: absolute; left: 50%; bottom: calc(100% + 8px); transform: translateX(-50%) translateY(4px); opacity: 0; pointer-events: none; white-space: nowrap; padding: 7px 10px; border-radius: 999px; background: rgba(12,12,16,.86); border: 1px solid rgba(0, 0, 0, .12); box-shadow: 0 16px 40px rgba(0,0,0,.35); color: #000; font-size: 12px; transition: .16s ease; backdrop-filter: blur(10px); }
        .handleTipWrap:hover .handleTipBox { opacity: 1; transform: translateX(-50%) translateY(0); }
        .badgeTipWrap { position: relative; }
        .badgeTipBox { position: absolute; left: 50%; bottom: calc(100% + 8px); transform: translateX(-50%) translateY(4px); opacity: 0; pointer-events: none; white-space: nowrap; padding: 6px 9px; border-radius: 999px; background: rgba(12,12,16,.9); border: 1px solid rgba(0, 0, 0, .12); color: #000; font-size: 11px; transition: .16s ease; box-shadow: 0 12px 32px rgba(0,0,0,.35); }
        .badgeTipWrap:hover .badgeTipBox { opacity: 1; transform: translateX(-50%) translateY(0); }
        @keyframes typewriterName {
          0%, 10% { width: 0; }
          42%, 68% { width: 100%; }
          95%, 100% { width: 0; }
        }
        @keyframes caretBlink { 0%,100% { border-color: transparent; } 50% { border-color: currentColor; } }
        .nameEffect.typewriter { max-width: 100%; vertical-align: bottom; }
        .nameEffect.glow { filter: drop-shadow(0 0 12px currentColor); }
        .nameEffect.sparkle::after { content: "✦"; margin-left: 6px; font-size: .45em; vertical-align: top; }
        @media (max-width: 620px) {
          section > div[style*="grid-template-columns"] { grid-template-columns: 1fr !important; text-align: center; }
          .hasOrnateRedFrame { padding: 44px 32px 54px !important; }
        }
      ` }} />
    </div>
  );
}
