"use client";

import { useEffect, useRef, useState, 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, MODULE_META, badgesFromDiscordRoleIds, type BadgeItem, type Profile } from "@/lib/constants";
import { badgesForProfile } from "@/lib/profile-badges";
import About from "./modules/About";
import DiscordCard from "./modules/DiscordCard";
import Clock from "./modules/Clock";
import ProfileBookmarkButton from "./ProfileLikeButton";
import ProfileTipButton from "./ProfileTipButton";
import { CardFrameOverlay, ProfileAvatarBlock, resolveCardFrameRadius } from "./ProfileCosmetics";

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 };
}

const MODULE_COMPONENTS: Record<string, (p: { profile: Profile }) => JSX.Element> = {
  about: About,
  discord: DiscordCard,
  clock: Clock,
};

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 isVideoBackground(url?: string) {
  return /\.(mp4|webm|mov)(\?|#|$)/i.test(url || "");
}

export default function ScrollProfile({ profile, entered = true, audioPlayer, lyricsBox, visualizer }: { profile: Profile; entered?: boolean; audioPlayer?: ReactNode; lyricsBox?: ReactNode; visualizer?: ReactNode }) {
  const accent = profile.accent || "#f5caca";
  const text = profile.text_color || "#000000";
  const badgeColor = profile.icon_color || "#000000";
  const linkColor = profile.monochrome_icons ? (profile.link_color || "#000000") : (profile.link_color || accent);
  const hasBgMedia = /^https?:\/\//.test(profile.background_url || "");
  const hasBgVideo = hasBgMedia && isVideoBackground(profile.background_url);
  const { badges: roleBadges, discordAvatarUrl, discordDecorationUrl } = useDiscordPresenceCosmetics(profile);
  const badges = 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 joined = profile.created_at ? new Date(profile.created_at).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }) : "";
  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 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 hasCardFrame = Boolean(profile.card_frame);
  const isOrnateRedFrame = profile.card_frame === "ornate-red";
  const isTypewriter = profile.username_effect === "typewriter";
  const modules = (profile.modules || []).filter((k) => {
    if (!MODULE_COMPONENTS[k]) return false;
    if (k === "discord") return profile.discord_enabled === true;
    return true;
  });
  const backgroundVideoRef = useRef<HTMLVideoElement>(null);

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

  return (
    <div style={{ position: "relative", minHeight: "100vh", color: text, fontFamily: profile.font === "JetBrains Mono" ? "monospace" : `${profile.font || "Inter"}, system-ui, sans-serif` }}>
      <div style={{ position: "fixed", inset: 0, zIndex: -1, background: hasBgMedia ? "#050507" : profile.background_color || BACKGROUNDS[profile.bg] || BACKGROUNDS.midnight }}>
        {hasBgMedia && (
          hasBgVideo ? (
            <video
              ref={backgroundVideoRef}
              src={profile.background_url}
              autoPlay={entered}
              muted
              loop
              playsInline
              preload={entered ? "auto" : "none"}
              style={{
                position: "absolute",
                inset: -10,
                width: "calc(100% + 20px)",
                height: "calc(100% + 20px)",
                objectFit: "cover",
                objectPosition: "center",
                filter: profile.background_effect === "blurred" ? "blur(4px)" : "none",
                transform: "scale(1.03)",
              }}
            />
          ) : (
            <div
              style={{
                position: "absolute",
                inset: -10,
                backgroundImage: `url(${profile.background_url})`,
                backgroundSize: "cover",
                backgroundPosition: "center",
                filter: profile.background_effect === "blurred" ? "blur(4px)" : "none",
                transform: "scale(1.03)",
              }}
            />
          )
        )}
        <div
          style={{
            position: "absolute",
            inset: -20,
            background: hasBgMedia
              ? profile.background_effect === "none"
                ? "transparent"
                : profile.background_effect === "darken"
                  ? "rgba(0,0,0,.66)"
                  : "linear-gradient(180deg, rgba(0,0,0,.24), rgba(0,0,0,.74))"
              : profile.profile_gradient
                ? `radial-gradient(circle at 50% 18%, ${accent}55, transparent 45%), linear-gradient(180deg, ${profile.background_color || "#050505"}, #000)`
                : "linear-gradient(180deg, rgba(5,5,7,0.25), rgba(5,5,7,0.75))",
          }}
        />
      </div>

      {visualizer}

      <section style={{ position: "relative", minHeight: "100vh", display: "grid", placeItems: "center", padding: 24 }}>
        <div
          className={(profile.is_promoter && !profile.hide_promoter_aura) ? "promoterCardAura" : undefined}
          style={{
            position: "relative",
            width: `min(${Math.max(badges.length > 4 ? 720 : 560, profile.profile_card_width || 0)}px,100%)`,
            textAlign: "center",
            margin: isOrnateRedFrame ? "16px 0" : undefined,
            padding: isOrnateRedFrame
              ? hasAvatar ? "50px 52px 60px" : "38px 52px 48px"
              : hasAvatar ? "34px 28px" : "26px 28px",
            borderRadius: cardRadius,
            background: opacity <= 0 ? "transparent" : `rgba(12,12,16,${opacity})`,
            border: opacity <= 0 || cardBorderWidth === 0 || hasCardFrame ? "1px solid transparent" : `${cardBorderWidth}px solid ${cardBorderColor}88`,
            backdropFilter: blur <= 0 ? "none" : `blur(${blur}px)`,
            WebkitBackdropFilter: blur <= 0 ? "none" : `blur(${blur}px)`,
            boxShadow: opacity <= 0 ? "none" : `0 0 0 1px #00000008, 0 24px 80px -34px ${accent}`,
          }}
        >
          <CardFrameOverlay cardFrame={profile.card_frame} cardRadius={cardRadius} />
          {hasAvatar && (
            <ProfileAvatarBlock
              profile={profile}
              size={118}
              margin="0 auto 16px"
              discordAvatarUrl={discordAvatarUrl}
              discordDecorationUrl={discordDecorationUrl}
            />
          )}

          <div style={{ display: "flex", alignItems: "center", gap: 8, justifyContent: "center", flexWrap: "wrap" }}>
            <span className="handleTipWrap">
              <h1
                className={[profile.animated_title && profile.username_effect !== "none" ? `nameEffect ${profile.username_effect}` : "", profile.is_promoter ? "promoterUsernameShimmer" : ""].filter(Boolean).join(" ") || undefined}
                style={{
                  fontSize: 42,
                  fontWeight: 900,
                  margin: 0,
                  padding: isTypewriter ? "2px 4px" : undefined,
                  letterSpacing: "-.04em",
                  color: text,
                  textShadow: profile.animated_title && profile.username_effect !== "none" ? (isTypewriter ? `0 0 10px ${accent}88` : `0 0 20px ${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>
              <span className="handleTipBox">{profile.public_uid ? `UUID #${profile.public_uid}` : profile.id ? `Account ${profile.id}` : "Account"}</span>
            </span>
            {badges.length > 0 && (
              <div
                style={{
                  display: "inline-flex",
                  flexDirection: "row",
                  gap: 7,
                  alignItems: "center",
                  flexWrap: "wrap",
                  justifyContent: "center",
                  flexBasis: badges.length > 4 ? "100%" : "auto",
                  width: badges.length > 4 ? "100%" : "auto",
                  marginTop: badges.length > 4 ? 6 : 0,
                }}
              >
                {badges.map((badge) => {
                  const isCustom = !!badge.custom || badge.id?.startsWith("custom-");
                  return (
                    <span
                      key={badge.id}
                      className="badgeTipWrap"
                      style={{
                        display: "inline-grid",
                        placeItems: "center",
                        fontSize: 16,
                        lineHeight: 1,
                        color: isCustom ? "inherit" : badgeColor,
                        textShadow: !isCustom && profile.badges_glow !== false ? `0 0 12px ${badgeColor}` : "none",
                        cursor: "help",
                      }}
                    >
                      <BadgeIcon
                        badge={badge}
                        monochrome={profile.monochrome_icons !== false}
                        color={badgeColor}
                        glow={!isCustom && profile.badges_glow !== false}
                        size={18}
                      />
                      <span className="badgeTipBox">{badge.name}</span>
                    </span>
                  );
                })}
              </div>
            )}
          </div>

          {(!profile.hide_username || !profile.display_name?.trim()) && (
            <p style={{ color: "#540606", fontSize: 14, margin: "5px 0 0" }}>@{profile.username}</p>
          )}
          {profile.alias && !profile.hide_alias && <p style={{ color: "#000", fontSize: 12, margin: "3px 0 0" }}>alias: @{profile.alias}</p>}
          {profile.bio && <p style={{ color: text, fontSize: 15, lineHeight: 1.55, margin: "14px auto 0", maxWidth: 460 }}>{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>
          )}


{profile.links?.length > 0 && (() => {
            const visibleLinks = profile.links.filter((l) => !l.hidden && (l.url || l.platform));
            if (visibleLinks.length === 0) return null;
            const isButtons = profile.link_style === "buttons";

            if (isButtons) {
              return (
                <div style={{ display: "grid", gap: 9, marginTop: 22, width: "100%", maxWidth: 420 }}>
                  {visibleLinks.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 {}
                        }}
                        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: linkColor,
                              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={linkColor} />
                            )}
                          </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: 16, marginTop: 22, flexWrap: "wrap", justifyContent: "center" }}>
                {visibleLinks.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 (
                    <a
                      key={l.id}
                      href={hrefFor(l.url)}
                      target="_blank"
                      rel="noreferrer"
                      aria-label={label}
                      title={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: linkColor, 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={linkColor} />
                      )}
                    </a>
                  );
                })}
              </div>
            );
          })()}

          <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>
        </div>

        {modules.length > 0 && (
          <div style={{ position: "absolute", bottom: 30, left: "50%", transform: "translateX(-50%)", display: "flex", flexDirection: "column", alignItems: "center", gap: 5, whiteSpace: "nowrap", fontFamily: 'Georgia, "Playfair Display", "Merriweather", serif', fontSize: 15, fontWeight: 700, color: "rgba(124, 7, 7, .88)", textShadow: "0 1px 10px rgba(0,0,0,.45)", animation: "scrollHintBounce 1.6s ease-in-out infinite" }}>
            Scroll for more
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M12 4v15m0 0 5.5-5.5M12 19l-5.5-5.5" />
            </svg>
          </div>
        )}
      </section>

      {lyricsBox && <section style={{ display: "grid", placeItems: "center", padding: "12px 24px 0" }}><div style={{ width: "min(560px,100%)" }}>{lyricsBox}</div></section>}
      {audioPlayer && <section style={{ display: "grid", placeItems: "center", padding: "12px 24px 36px" }}><div style={{ width: "min(560px,100%)" }}>{audioPlayer}</div></section>}

      {modules.map((key) => {
        const Comp = MODULE_COMPONENTS[key];
        if (key === "about") {
          const desc = (profile.website_description || "").trim();
          const subtitle = desc ? desc.split("\n")[0].trim().slice(0, 140) : "";
          return (
            <section key={key} style={{ minHeight: "66vh", display: "grid", placeItems: "center", padding: "42px 24px" }}>
              <div className="pfSection pfOnMedia" style={{ margin: 0 }}>
                <h2 className="pfSectionTitle">{MODULE_META[key].toLowerCase()}</h2>
                {subtitle && <p className="pfSectionSub">{subtitle}</p>}
                <div className="pfCard">
                  <Comp profile={profile} />
                </div>
              </div>
            </section>
          );
        }
        return (
          <section key={key} style={{ minHeight: "66vh", display: "grid", placeItems: "center", padding: "42px 24px" }}>
            <div style={{ width: "min(560px,100%)" }}>
              <h2 style={{ fontSize: 22, fontWeight: 900, margin: "0 0 14px", color: text }}>
                {MODULE_META[key]}
              </h2>
              <Comp profile={profile} />
            </div>
          </section>
        );
      })}

      <style>{`
        @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; }
      `}</style>
    </div>
  );
}
