"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  ArrowRight,
  Check,
  AlertCircle,
  Loader2,
  ExternalLink,
  ShieldAlert,
  Sparkles,
  Music,
  Video,
  X,
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import BrandIcon from "@/components/BrandIcon";
import type {
  TransferPreviewResponse,
  TransferSelection,
} from "@/lib/transfer/types";
import { FREE_TRANSFER_LIMIT_BYTES } from "@/lib/transfer/types";

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}

export default function TransferClient({ initialHandle = "" }: { initialHandle?: string }) {
  const router = useRouter();
  const supabase = useMemo(() => createClient(), []);

  const [handleInput, setHandleInput] = useState(initialHandle);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Authenticated state
  const [user, setUser] = useState<{ id: string } | null>(null);
  const [currentUsername, setCurrentUsername] = useState<string | null>(null);

  // Preview result state
  const [previewData, setPreviewData] = useState<TransferPreviewResponse | null>(null);
  const [selectedFields, setSelectedFields] = useState<TransferSelection>({
    displayName: true,
    bio: true,
    avatar: true,
    colors: true,
    socials: true,
    background: true,
    audio: true,
  });

  const [selectedSocialUrls, setSelectedSocialUrls] = useState<string[]>([]);

  // Destination handle
  const [chosenHandle, setChosenHandle] = useState("");
  const [customHandleInput, setCustomHandleInput] = useState("");
  const [showCustomHandle, setShowCustomHandle] = useState(false);

  // Existing user socials strategy
  const [socialsStrategy, setSocialsStrategy] = useState<"replace" | "merge" | "skip">("merge");

  // Over limit modal state
  const [showOverLimitModal, setShowOverLimitModal] = useState(false);

  // Apply in-progress state
  const [applying, setApplying] = useState(false);
  const [applyResult, setApplyResult] = useState<{
    ok: boolean;
    username?: string;
    warnings?: string[];
    error?: string;
  } | null>(null);

  // Check auth on mount
  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => {
      if (data?.user) {
        setUser(data.user);
        supabase
          .from("profiles")
          .select("username")
          .eq("id", data.user.id)
          .maybeSingle()
          .then(({ data: p }) => {
            if (p?.username) setCurrentUsername(p.username);
          });
      }
    });
  }, [supabase]);

  const fetchPreview = useCallback(async (handleToFetch: string) => {
    const trimmed = handleToFetch.trim();
    if (!trimmed) return;

    setLoading(true);
    setError(null);
    setPreviewData(null);
    setApplyResult(null);

    try {
      const res = await fetch("/api/transfer/guns/preview", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username: trimmed }),
      });

      const data: TransferPreviewResponse = await res.json();
      if (!res.ok || !data.ok) {
        setError(data.error || "Failed to preview guns.lol profile.");
      } else {
        setPreviewData(data);
        if (data.profile) {
          setSelectedSocialUrls(data.profile.socials.map((s) => s.url));
          setSelectedFields({
            displayName: true,
            bio: Boolean(data.profile.bio),
            avatar: !data.profile.avatarExceedsHardLimit && Boolean(data.profile.avatarUrl),
            colors: true,
            socials: true,
            background: !data.profile.backgroundExceedsHardLimit && Boolean(data.profile.backgroundUrl),
            audio: !data.profile.audioExceedsHardLimit && Boolean(data.profile.audioUrl),
          });
        }
        if (data.destination) {
          if (data.destination.exactAvailable) {
            setChosenHandle(data.destination.requestedUsername);
          } else if (data.destination.suggestions.length > 0) {
            setChosenHandle(data.destination.suggestions[0]);
          } else {
            setChosenHandle(data.destination.requestedUsername);
          }
        }
      }
    } catch {
      setError("Network error while connecting to transfer service. Please try again.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (initialHandle) {
      fetchPreview(initialHandle);
    }
  }, [initialHandle, fetchPreview]);

  const profile = previewData?.profile;
  const isPremium = Boolean(previewData?.isPremium);
  const allowanceBytes = previewData?.allowanceBytes || FREE_TRANSFER_LIMIT_BYTES;

  // Dynamic Size Calculation
  const currentSelectedBytes = useMemo(() => {
    if (!profile) return 0;
    let bytes = 0;

    const metaObj: Record<string, unknown> = {};
    if (selectedFields.displayName) metaObj.displayName = profile.displayName;
    if (selectedFields.bio) metaObj.bio = profile.bio;
    if (selectedFields.colors) metaObj.colors = profile.colors;
    bytes += new TextEncoder().encode(JSON.stringify(metaObj)).length;

    if (selectedFields.avatar && profile.avatarUrl) {
      bytes += profile.avatarEstimatedBytes || 450 * 1024;
    }

    if (selectedFields.background && profile.backgroundUrl) {
      bytes += profile.backgroundEstimatedBytes || 2500 * 1024;
    }

    if (selectedFields.audio && profile.audioUrl) {
      bytes += profile.audioEstimatedBytes || 1500 * 1024;
    }

    if (selectedFields.socials) {
      const selectedSocials = profile.socials.filter((s) => selectedSocialUrls.includes(s.url));
      bytes += selectedSocials.reduce((acc, s) => acc + s.estimatedBytes, 0);
    }

    return bytes;
  }, [profile, selectedFields, selectedSocialUrls]);

  const isOverLimit = currentSelectedBytes > allowanceBytes;
  const sizePercentage = Math.min(100, Math.round((currentSelectedBytes / allowanceBytes) * 100));

  const handleToggleField = (field: keyof TransferSelection) => {
    setSelectedFields((prev) => ({ ...prev, [field]: !prev[field] }));
  };

  const handleToggleSocial = (url: string) => {
    setSelectedSocialUrls((prev) =>
      prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url]
    );
  };

  const handleProceedToSignup = () => {
    if (!previewData || !previewData.transferToken) return;

    const sessionPayload = {
      token: previewData.transferToken,
      sourceUsername: profile?.sourceUsername,
      chosenHandle: chosenHandle || profile?.sourceUsername,
      selectedFields,
      selectedSocialUrls,
      estimatedBytes: currentSelectedBytes,
      savedAt: Date.now(),
    };

    window.sessionStorage.setItem("sinss_transfer_session", JSON.stringify(sessionPayload));
    const targetClaim = encodeURIComponent(chosenHandle || profile?.sourceUsername || "");
    router.push(`/signup?claim=${targetClaim}`);
  };

  const handleApplyToProfile = async () => {
    if (!previewData || !previewData.transferToken) return;

    setApplying(true);
    setApplyResult(null);

    try {
      const res = await fetch("/api/transfer/guns/apply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          transferToken: previewData.transferToken,
          selectedFields,
          selectedSocialUrls,
          socialsStrategy,
        }),
      });

      const data = await res.json();
      if (!res.ok || !data.ok) {
        setApplyResult({ ok: false, error: data.error || "Failed to apply profile changes." });
      } else {
        setApplyResult({
          ok: true,
          username: data.username || currentUsername || "you",
          warnings: data.warnings,
        });
      }
    } catch {
      setApplyResult({ ok: false, error: "Network error while applying profile changes." });
    } finally {
      setApplying(false);
    }
  };

  return (
    <div style={{ maxWidth: 840, width: "100%", margin: "0 auto" }}>
      {/* Hero Header */}
      <div style={{ textAlign: "center", marginBottom: 36 }}>
        <div
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            padding: "4px 12px",
            borderRadius: 999,
            background: "rgba(0, 0, 0, 0.05)",
            border: "1px solid rgba(0, 0, 0, 0.1)",
            fontSize: 11,
            letterSpacing: "1px",
            textTransform: "uppercase",
            color: "#1a0606",
            marginBottom: 16,
          }}
        >
          <Sparkles size={12} color="#ffffff" />
          One-Click Migration
        </div>
        <h1
          style={{
            fontSize: "clamp(28px, 5vw, 42px)",
            fontWeight: 600,
            letterSpacing: "-0.03em",
            margin: "0 0 12px",
            color: "#000",
            lineHeight: 1.2,
          }}
        >
          Switch from guns.lol to sinss.lol in seconds.
        </h1>
        <p
          style={{
            fontSize: 15,
            color: "#1c0707",
            maxWidth: 580,
            margin: "0 auto",
            lineHeight: 1.6,
          }}
        >
          Keep your links, bio, background video, and music. Unlock free video backgrounds, audio playlists with
          synced lyrics, and sub-30ms profile loading.
        </p>
      </div>

      {/* Input Box */}
      <div
        style={{
          background: "rgba(16, 18, 24, 0.75)",
          border: "1px solid rgba(0, 0, 0, 0.08)",
          borderRadius: 16,
          padding: 8,
          display: "flex",
          gap: 8,
          marginBottom: 32,
          boxShadow: "0 10px 40px rgba(0, 0, 0, 0.4)",
        }}
      >
        <div style={{ position: "relative", flex: 1, display: "flex", alignItems: "center" }}>
          <span
            style={{
              paddingLeft: 14,
              fontSize: 14,
              color: "#180a0a",
              userSelect: "none",
              fontFamily: "monospace",
            }}
          >
            guns.lol/
          </span>
          <input
            type="text"
            value={handleInput}
            onChange={(e) => setHandleInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") fetchPreview(handleInput);
            }}
            placeholder="username"
            disabled={loading}
            style={{
              flex: 1,
              background: "transparent",
              border: "none",
              outline: "none",
              color: "#000",
              fontSize: 14,
              padding: "12px 14px 12px 2px",
              fontFamily: "inherit",
            }}
          />
        </div>
        <button
          onClick={() => fetchPreview(handleInput)}
          disabled={loading || !handleInput.trim()}
          style={{
            background: "#ffffff",
            color: "#08090b",
            border: "none",
            borderRadius: 10,
            padding: "10px 20px",
            fontSize: 13,
            fontWeight: 600,
            cursor: loading ? "default" : "pointer",
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            transition: "opacity 0.15s",
            opacity: loading || !handleInput.trim() ? 0.6 : 1,
          }}
        >
          {loading ? (
            <>
              <Loader2 size={15} className="animate-spin" />
              Scanning...
            </>
          ) : (
            <>
              Preview Profile
              <ArrowRight size={14} />
            </>
          )}
        </button>
      </div>

      {/* Error Notice */}
      {error && (
        <div
          style={{
            background: "rgba(239, 191, 191, 0.08)",
            border: "1px solid rgba(239, 191, 191, 0.25)",
            color: "#fce1e1",
            borderRadius: 12,
            padding: "14px 18px",
            marginBottom: 24,
            fontSize: 13,
            display: "flex",
            alignItems: "center",
            gap: 10,
          }}
        >
          <AlertCircle size={18} style={{ flexShrink: 0 }} />
          <span>{error}</span>
        </div>
      )}

      {/* Completion Modal / View for Logged-In Users */}
      {applyResult && (
        <div
          style={{
            background: applyResult.ok ? "rgba(230, 198, 198, 0.08)" : "rgba(239, 191, 191, 0.08)",
            border: `1px solid ${applyResult.ok ? "rgba(230, 198, 198, 0.25)" : "rgba(239, 191, 191, 0.25)"}`,
            borderRadius: 16,
            padding: 24,
            marginBottom: 32,
            textAlign: "center",
          }}
        >
          {applyResult.ok ? (
            <>
              <div
                style={{
                  width: 44,
                  height: 44,
                  borderRadius: "50%",
                  background: "rgba(230, 198, 198, 0.15)",
                  display: "grid",
                  placeItems: "center",
                  margin: "0 auto 14px",
                  color: "#d37575",
                }}
              >
                <Check size={22} />
              </div>
              <h2 style={{ fontSize: 20, fontWeight: 600, margin: "0 0 8px", color: "#000" }}>
                Profile Successfully Transferred
              </h2>
              <p style={{ fontSize: 13, color: "#2d0909", margin: "0 0 20px", lineHeight: 1.5 }}>
                Your selected links, bio, background, music, and styling are now live on your sinss.lol profile.
              </p>
              {applyResult.warnings && applyResult.warnings.length > 0 && (
                <div style={{ fontSize: 12, color: "#fbf1f1", marginBottom: 16 }}>
                  {applyResult.warnings.map((w, i) => (
                    <div key={i}>{w}</div>
                  ))}
                </div>
              )}
              <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
                <Link
                  href={`/${applyResult.username}`}
                  target="_blank"
                  style={{
                    background: "#ffffff",
                    color: "#08090b",
                    padding: "9px 18px",
                    borderRadius: 8,
                    fontSize: 13,
                    fontWeight: 600,
                    textDecoration: "none",
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  View Live Profile <ExternalLink size={13} />
                </Link>
                <Link
                  href="/dashboard"
                  style={{
                    background: "rgba(0, 0, 0, 0.08)",
                    color: "#000",
                    padding: "9px 18px",
                    borderRadius: 8,
                    fontSize: 13,
                    textDecoration: "none",
                  }}
                >
                  Edit in Dashboard
                </Link>
              </div>
            </>
          ) : (
            <div style={{ color: "#fce1e1" }}>{applyResult.error}</div>
          )}
        </div>
      )}

      {/* Main Preview Container */}
      {profile && (
        <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
          {/* Transfer Size Allowance Bar */}
          <div
            style={{
              background: "rgba(16, 18, 24, 0.65)",
              border: `1px solid ${isOverLimit ? "rgba(239, 191, 191, 0.3)" : "rgba(0, 0, 0, 0.08)"}`,
              borderRadius: 14,
              padding: "16px 20px",
            }}
          >
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 500, color: "#000" }}>Estimated Transfer Size</span>
                <span
                  style={{
                    fontSize: 10,
                    padding: "2px 8px",
                    borderRadius: 4,
                    background: isPremium ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.08)",
                    color: isPremium ? "#ffffff" : "#1c0707",
                    fontWeight: 600,
                    letterSpacing: "0.5px",
                  }}
                >
                  {isPremium ? "PREMIUM (50 MB)" : "FREE TIER (35 MB)"}
                </span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: isOverLimit ? "#f8d6d6" : "#ffffff" }}>
                {formatBytes(currentSelectedBytes)} / {formatBytes(allowanceBytes)}
              </div>
            </div>

            {/* Progress bar */}
            <div
              style={{
                width: "100%",
                height: 6,
                background: "rgba(0, 0, 0, 0.08)",
                borderRadius: 999,
                overflow: "hidden",
                marginBottom: 8,
              }}
            >
              <div
                style={{
                  width: `${sizePercentage}%`,
                  height: "100%",
                  background: isOverLimit
                    ? "#efbfbf"
                    : "linear-gradient(90deg, #fae5e5, #ffffff)",
                  transition: "width 0.2s ease, background 0.2s ease",
                }}
              />
            </div>

            {/* Warning if over limit */}
            {isOverLimit ? (
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10 }}>
                <div style={{ fontSize: 12, color: "#f8d6d6", display: "flex", alignItems: "center", gap: 6 }}>
                  <AlertCircle size={14} />
                  Selected elements exceed your allowance by {formatBytes(currentSelectedBytes - allowanceBytes)}.
                </div>
                <button
                  onClick={() => setShowOverLimitModal(true)}
                  style={{
                    background: "transparent",
                    color: "#ffffff",
                    border: "none",
                    fontSize: 12,
                    textDecoration: "underline",
                    cursor: "pointer",
                    padding: 0,
                  }}
                >
                  Resolve size limit
                </button>
              </div>
            ) : (
              <div style={{ fontSize: 11, color: "#190a0a" }}>
                Within allowance. HEAD-based asset sizes are estimated previews; final byte counts are verified on upload.
              </div>
            )}

            {/* Hard Limit Warning for 50 MB Files */}
            {(profile.avatarExceedsHardLimit || profile.backgroundExceedsHardLimit || profile.audioExceedsHardLimit) && (
              <div
                style={{
                  marginTop: 12,
                  padding: "10px 14px",
                  borderRadius: 8,
                  background: "rgba(239, 191, 191, 0.08)",
                  border: "1px solid rgba(239, 191, 191, 0.2)",
                  fontSize: 12,
                  color: "#fce1e1",
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                }}
              >
                <ShieldAlert size={15} style={{ flexShrink: 0 }} />
                <span>
                  One or more media files exceed the <strong>50 MB single-file asset limit</strong> and must be excluded.
                  Files above 50 MB cannot be hosted.
                </span>
              </div>
            )}
          </div>

          {/* Profile Detected Card & Selection Panel */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))",
              gap: 20,
            }}
          >
            {/* Visual Card Preview */}
            <div
              style={{
                background: "rgba(16, 18, 24, 0.75)",
                border: "1px solid rgba(0, 0, 0, 0.08)",
                borderRadius: 16,
                padding: 24,
                display: "flex",
                flexDirection: "column",
                position: "relative",
              }}
            >
              <div style={{ fontSize: 11, letterSpacing: "1px", textTransform: "uppercase", color: "#170909", marginBottom: 16 }}>
                Detected Profile Card
              </div>

              {/* Avatar + Name row */}
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
                <div
                  style={{
                    width: 58,
                    height: 58,
                    borderRadius: "50%",
                    background: "rgba(0, 0, 0, 0.08)",
                    border: "1px solid rgba(0, 0, 0, 0.12)",
                    overflow: "hidden",
                    display: "grid",
                    placeItems: "center",
                    flexShrink: 0,
                  }}
                >
                  {selectedFields.avatar && profile.avatarUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={profile.avatarUrl}
                      alt={profile.displayName}
                      style={{ width: "100%", height: "100%", objectFit: "cover" }}
                    />
                  ) : (
                    <span style={{ fontSize: 22, color: "#000" }}>
                      {profile.displayName.charAt(0).toUpperCase()}
                    </span>
                  )}
                </div>
                <div>
                  <div style={{ fontSize: 17, fontWeight: 600, color: "#000" }}>
                    {selectedFields.displayName ? profile.displayName : `@${profile.sourceUsername}`}
                  </div>
                  <div style={{ fontSize: 12, color: "#180808" }}>guns.lol/{profile.sourceUsername}</div>
                </div>
              </div>

              {/* Bio */}
              {selectedFields.bio && profile.bio && (
                <p
                  style={{
                    fontSize: 13,
                    color: "#230707",
                    lineHeight: 1.5,
                    margin: "0 0 16px",
                    background: "rgba(0, 0, 0, 0.02)",
                    padding: 10,
                    borderRadius: 8,
                  }}
                >
                  {profile.bio}
                </p>
              )}

              {/* Detected Media Badges (Video & Audio) */}
              {(profile.backgroundUrl || profile.audioUrl) && (
                <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 16 }}>
                  {profile.backgroundUrl && (
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        padding: "8px 12px",
                        borderRadius: 8,
                        background: selectedFields.background ? "rgba(255, 255, 255, 0.06)" : "rgba(0, 0, 0, 0.02)",
                        border: `1px solid ${selectedFields.background ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.04)"}`,
                        fontSize: 12,
                        color: selectedFields.background ? "#ffffff" : "#000",
                      }}
                    >
                      <Video size={14} />
                      <span style={{ flex: 1 }}>Background Video / Asset</span>
                      <span style={{ fontSize: 11, color: "#000" }}>{formatBytes(profile.backgroundEstimatedBytes)}</span>
                    </div>
                  )}

                  {profile.audioUrl && (
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        padding: "8px 12px",
                        borderRadius: 8,
                        background: selectedFields.audio ? "rgba(255, 255, 255, 0.06)" : "rgba(0, 0, 0, 0.02)",
                        border: `1px solid ${selectedFields.audio ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.04)"}`,
                        fontSize: 12,
                        color: selectedFields.audio ? "#ffffff" : "#000",
                      }}
                    >
                      <Music size={14} />
                      <span style={{ flex: 1 }}>Audio Music Track</span>
                      <span style={{ fontSize: 11, color: "#000" }}>{formatBytes(profile.audioEstimatedBytes)}</span>
                    </div>
                  )}
                </div>
              )}

              {/* Theme Colors */}
              {selectedFields.colors && (
                <div style={{ marginBottom: 16 }}>
                  <div style={{ fontSize: 11, color: "#170808", marginBottom: 6 }}>Theme Colors</div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    {profile.colors.textColor && (
                      <div
                        title={`Text Color: ${profile.colors.textColor}`}
                        style={{
                          width: 18,
                          height: 18,
                          borderRadius: "50%",
                          background: profile.colors.textColor,
                          border: "1px solid #000",
                        }}
                      />
                    )}
                    {profile.colors.primaryColor && (
                      <div
                        title={`Accent Color: ${profile.colors.primaryColor}`}
                        style={{
                          width: 18,
                          height: 18,
                          borderRadius: "50%",
                          background: profile.colors.primaryColor,
                          border: "1px solid #000",
                        }}
                      />
                    )}
                    {profile.colors.backgroundColor && (
                      <div
                        title={`Background: ${profile.colors.backgroundColor}`}
                        style={{
                          width: 18,
                          height: 18,
                          borderRadius: "50%",
                          background: profile.colors.backgroundColor,
                          border: "1px solid #000",
                        }}
                      />
                    )}
                    <span style={{ fontSize: 11, color: "#000" }}>
                      {profile.colors.profileGradient ? "Gradient enabled" : "Solid"}
                    </span>
                  </div>
                </div>
              )}

              {/* Social Links List */}
              {selectedFields.socials && profile.socials.length > 0 && (
                <div>
                  <div style={{ fontSize: 11, color: "#170808", marginBottom: 8 }}>
                    Social Links ({profile.socials.length})
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                    {profile.socials.map((link) => {
                      const isChecked = selectedSocialUrls.includes(link.url);
                      return (
                        <div
                          key={link.url}
                          onClick={() => handleToggleSocial(link.url)}
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 10,
                            padding: "8px 10px",
                            borderRadius: 8,
                            background: isChecked ? "rgba(0, 0, 0, 0.04)" : "rgba(0, 0, 0, 0.01)",
                            border: `1px solid ${isChecked ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 0, 0, 0.03)"}`,
                            cursor: "pointer",
                            fontSize: 12,
                          }}
                        >
                          <input
                            type="checkbox"
                            checked={isChecked}
                            onChange={() => {}}
                            style={{ cursor: "pointer" }}
                          />
                          <BrandIcon platform={link.platform} size={15} />
                          <span style={{ color: isChecked ? "#000" : "#000", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                            {link.label || link.platform}
                          </span>
                          <span style={{ fontSize: 10, color: "#000" }}>{formatBytes(link.estimatedBytes)}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Unsupported Items Footnote */}
              {profile.unsupportedItems.length > 0 && (
                <div style={{ marginTop: "auto", paddingTop: 18, fontSize: 11, color: "#1c0c0c" }}>
                  <span>Excluded: {profile.unsupportedItems.join(", ")} (proprietary to guns.lol)</span>
                </div>
              )}
            </div>

            {/* Selection & Destination Configuration */}
            <div
              style={{
                background: "rgba(16, 18, 24, 0.75)",
                border: "1px solid rgba(0, 0, 0, 0.08)",
                borderRadius: 16,
                padding: 24,
                display: "flex",
                flexDirection: "column",
              }}
            >
              <div style={{ fontSize: 11, letterSpacing: "1px", textTransform: "uppercase", color: "#170909", marginBottom: 16 }}>
                Transfer Options
              </div>

              {/* Checkboxes for Elements */}
              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 24 }}>
                <label style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, cursor: "pointer" }}>
                  <input
                    type="checkbox"
                    checked={selectedFields.displayName}
                    onChange={() => handleToggleField("displayName")}
                  />
                  <span>Display Name: <strong>{profile.displayName}</strong></span>
                </label>

                <label style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, cursor: "pointer" }}>
                  <input
                    type="checkbox"
                    checked={selectedFields.bio}
                    onChange={() => handleToggleField("bio")}
                    disabled={!profile.bio}
                  />
                  <span>Bio Description {!profile.bio && <small style={{ color: "#000" }}>(None detected)</small>}</span>
                </label>

                <label
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                    fontSize: 13,
                    cursor: profile.avatarExceedsHardLimit ? "not-allowed" : "pointer",
                    opacity: profile.avatarExceedsHardLimit ? 0.5 : 1,
                  }}
                >
                  <input
                    type="checkbox"
                    checked={selectedFields.avatar}
                    onChange={() => handleToggleField("avatar")}
                    disabled={profile.avatarExceedsHardLimit || !profile.avatarUrl}
                  />
                  <span>
                    Avatar Image ({formatBytes(profile.avatarEstimatedBytes)})
                    {profile.avatarExceedsHardLimit && " — Exceeds 50 MB Limit"}
                  </span>
                </label>

                {/* Background Video Toggle */}
                {profile.backgroundUrl && (
                  <label
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 10,
                      fontSize: 13,
                      cursor: profile.backgroundExceedsHardLimit ? "not-allowed" : "pointer",
                      opacity: profile.backgroundExceedsHardLimit ? 0.5 : 1,
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={selectedFields.background}
                      onChange={() => handleToggleField("background")}
                      disabled={profile.backgroundExceedsHardLimit}
                    />
                    <span>
                      Background Video ({formatBytes(profile.backgroundEstimatedBytes)})
                      {profile.backgroundExceedsHardLimit && " — Exceeds 50 MB Limit"}
                    </span>
                  </label>
                )}

                {/* Audio Music Track Toggle */}
                {profile.audioUrl && (
                  <label
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 10,
                      fontSize: 13,
                      cursor: profile.audioExceedsHardLimit ? "not-allowed" : "pointer",
                      opacity: profile.audioExceedsHardLimit ? 0.5 : 1,
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={selectedFields.audio}
                      onChange={() => handleToggleField("audio")}
                      disabled={profile.audioExceedsHardLimit}
                    />
                    <span>
                      Audio Music Track ({formatBytes(profile.audioEstimatedBytes)})
                      {profile.audioExceedsHardLimit && " — Exceeds 50 MB Limit"}
                    </span>
                  </label>
                )}

                <label style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, cursor: "pointer" }}>
                  <input
                    type="checkbox"
                    checked={selectedFields.colors}
                    onChange={() => handleToggleField("colors")}
                  />
                  <span>Theme & Background Colors</span>
                </label>

                <label style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, cursor: "pointer" }}>
                  <input
                    type="checkbox"
                    checked={selectedFields.socials}
                    onChange={() => handleToggleField("socials")}
                    disabled={profile.socials.length === 0}
                  />
                  <span>Social Links ({profile.socials.length} links)</span>
                </label>
              </div>

              {/* Destination Handle for New Users OR Link Strategy for Existing */}
              {!user ? (
                <div style={{ marginBottom: 24, paddingTop: 18, borderTop: "1px solid rgba(0, 0, 0, 0.08)" }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: "#000", marginBottom: 8 }}>
                    Destination Username on sinss.lol
                  </div>

                  {previewData.destination?.exactAvailable ? (
                    <div
                      style={{
                        padding: "8px 12px",
                        borderRadius: 8,
                        background: "rgba(230, 198, 198, 0.1)",
                        border: "1px solid rgba(230, 198, 198, 0.25)",
                        fontSize: 12,
                        color: "#d37575",
                        display: "flex",
                        alignItems: "center",
                        gap: 6,
                        marginBottom: 12,
                      }}
                    >
                      <Check size={14} />
                      <strong>@{previewData.destination.requestedUsername}</strong> is available on sinss.lol!
                    </div>
                  ) : (
                    <div style={{ marginBottom: 12 }}>
                      <div style={{ fontSize: 12, color: "#fce1e1", marginBottom: 8, display: "flex", alignItems: "center", gap: 6 }}>
                        <AlertCircle size={13} />
                        @{profile.sourceUsername} is taken on sinss.lol. Choose an alternative:
                      </div>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 10 }}>
                        {previewData.destination?.suggestions.map((sug) => (
                          <button
                            key={sug}
                            type="button"
                            onClick={() => {
                              setChosenHandle(sug);
                              setShowCustomHandle(false);
                            }}
                            style={{
                              background: chosenHandle === sug ? "#ffffff" : "rgba(0, 0, 0, 0.06)",
                              color: chosenHandle === sug ? "#08090b" : "#000",
                              border: "1px solid rgba(0, 0, 0, 0.1)",
                              padding: "6px 12px",
                              borderRadius: 6,
                              fontSize: 12,
                              fontWeight: 500,
                              cursor: "pointer",
                            }}
                          >
                            @{sug}
                          </button>
                        ))}
                        <button
                          type="button"
                          onClick={() => setShowCustomHandle(true)}
                          style={{
                            background: showCustomHandle ? "#ffffff" : "rgba(0, 0, 0, 0.06)",
                            color: showCustomHandle ? "#08090b" : "#000",
                            border: "1px dashed rgba(0, 0, 0, 0.2)",
                            padding: "6px 12px",
                            borderRadius: 6,
                            fontSize: 12,
                            cursor: "pointer",
                          }}
                        >
                          Custom...
                        </button>
                      </div>

                      {showCustomHandle && (
                        <input
                          type="text"
                          value={customHandleInput}
                          onChange={(e) => {
                            const val = e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, "").slice(0, 20);
                            setCustomHandleInput(val);
                            setChosenHandle(val);
                          }}
                          placeholder="enter custom username"
                          style={{
                            width: "100%",
                            background: "rgba(0, 0, 0, 0.3)",
                            border: "1px solid rgba(0, 0, 0, 0.15)",
                            borderRadius: 6,
                            padding: "8px 10px",
                            color: "#000",
                            fontSize: 12,
                          }}
                        />
                      )}
                    </div>
                  )}
                </div>
              ) : (
                /* Existing User Social Links Strategy */
                <div style={{ marginBottom: 24, paddingTop: 18, borderTop: "1px solid rgba(0, 0, 0, 0.08)" }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: "#000", marginBottom: 8 }}>
                    Social Links Import Strategy
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 12 }}>
                    <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                      <input
                        type="radio"
                        name="socialsStrategy"
                        value="merge"
                        checked={socialsStrategy === "merge"}
                        onChange={() => setSocialsStrategy("merge")}
                      />
                      <span><strong>Merge</strong> (Keep existing links & add new ones)</span>
                    </label>
                    <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                      <input
                        type="radio"
                        name="socialsStrategy"
                        value="replace"
                        checked={socialsStrategy === "replace"}
                        onChange={() => setSocialsStrategy("replace")}
                      />
                      <span><strong>Replace</strong> (Overwrite existing links)</span>
                    </label>
                    <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                      <input
                        type="radio"
                        name="socialsStrategy"
                        value="skip"
                        checked={socialsStrategy === "skip"}
                        onChange={() => setSocialsStrategy("skip")}
                      />
                      <span><strong>Skip</strong> (Leave existing links untouched)</span>
                    </label>
                  </div>
                </div>
              )}

              {/* Action Button */}
              <div style={{ marginTop: "auto" }}>
                {!user ? (
                  <button
                    onClick={handleProceedToSignup}
                    disabled={isOverLimit || !chosenHandle}
                    style={{
                      width: "100%",
                      background: isOverLimit ? "#3e2424" : "#ffffff",
                      color: isOverLimit ? "#2d0909" : "#08090b",
                      border: "none",
                      borderRadius: 10,
                      padding: "13px 20px",
                      fontSize: 14,
                      fontWeight: 600,
                      cursor: isOverLimit || !chosenHandle ? "not-allowed" : "pointer",
                      display: "inline-flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: 8,
                    }}
                  >
                    {isOverLimit ? "Exceeds Transfer Allowance" : `Claim @${chosenHandle} & Transfer`}
                    {!isOverLimit && <ArrowRight size={15} />}
                  </button>
                ) : (
                  <button
                    onClick={handleApplyToProfile}
                    disabled={isOverLimit || applying}
                    style={{
                      width: "100%",
                      background: isOverLimit ? "#3e2424" : "#ffffff",
                      color: isOverLimit ? "#2d0909" : "#08090b",
                      border: "none",
                      borderRadius: 10,
                      padding: "13px 20px",
                      fontSize: 14,
                      fontWeight: 600,
                      cursor: isOverLimit || applying ? "not-allowed" : "pointer",
                      display: "inline-flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: 8,
                    }}
                  >
                    {applying ? (
                      <>
                        <Loader2 size={16} className="animate-spin" />
                        Applying Transfer to Profile...
                      </>
                    ) : isOverLimit ? (
                      "Exceeds Transfer Allowance"
                    ) : (
                      <>
                        Apply to My Profile
                        <ArrowRight size={15} />
                      </>
                    )}
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Over-Limit Resolution Modal */}
      {showOverLimitModal && profile && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            background: "rgba(0, 0, 0, 0.75)",
            backdropFilter: "blur(6px)",
            display: "grid",
            placeItems: "center",
            zIndex: 1000,
            padding: 20,
          }}
        >
          <div
            style={{
              background: "#0d0f14",
              border: "1px solid rgba(0, 0, 0, 0.12)",
              borderRadius: 18,
              maxWidth: 520,
              width: "100%",
              padding: 26,
              boxShadow: "0 24px 70px rgba(0, 0, 0, 0.8)",
            }}
          >
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, color: "#f8d6d6" }}>
                <AlertCircle size={18} />
                <h3 style={{ fontSize: 17, fontWeight: 600, margin: 0, color: "#000" }}>
                  Transfer Allowance Exceeded
                </h3>
              </div>
              <button
                onClick={() => setShowOverLimitModal(false)}
                style={{ background: "transparent", border: "none", color: "#000", cursor: "pointer", padding: 4 }}
              >
                <X size={18} />
              </button>
            </div>

            <p style={{ fontSize: 13, color: "#2d0909", margin: "0 0 16px", lineHeight: 1.5 }}>
              Your selected transfer is <strong>{formatBytes(currentSelectedBytes)}</strong>, which exceeds the{" "}
              {isPremium ? "Premium (50 MB)" : "Free (35 MB)"} limit. Uncheck heavy items below to bring it under the
              limit:
            </p>

            {/* Quick Deselection Controls */}
            <div
              style={{
                background: "rgba(0, 0, 0, 0.03)",
                border: "1px solid rgba(0, 0, 0, 0.08)",
                borderRadius: 10,
                padding: "12px 14px",
                marginBottom: 20,
                display: "flex",
                flexDirection: "column",
                gap: 10,
              }}
            >
              {profile.backgroundUrl && (
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }}>
                  <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                    <input
                      type="checkbox"
                      checked={selectedFields.background}
                      onChange={() => handleToggleField("background")}
                    />
                    <span>Background Video / Asset</span>
                  </label>
                  <span style={{ fontSize: 12, color: "#2d0909" }}>{formatBytes(profile.backgroundEstimatedBytes)}</span>
                </div>
              )}

              {profile.audioUrl && (
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }}>
                  <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                    <input
                      type="checkbox"
                      checked={selectedFields.audio}
                      onChange={() => handleToggleField("audio")}
                    />
                    <span>Audio Music Track</span>
                  </label>
                  <span style={{ fontSize: 12, color: "#2d0909" }}>{formatBytes(profile.audioEstimatedBytes)}</span>
                </div>
              )}

              {profile.avatarUrl && (
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }}>
                  <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                    <input
                      type="checkbox"
                      checked={selectedFields.avatar}
                      onChange={() => handleToggleField("avatar")}
                    />
                    <span>Avatar Image</span>
                  </label>
                  <span style={{ fontSize: 12, color: "#2d0909" }}>{formatBytes(profile.avatarEstimatedBytes)}</span>
                </div>
              )}

              {profile.socials.length > 0 && (
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }}>
                  <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                    <input
                      type="checkbox"
                      checked={selectedFields.socials}
                      onChange={() => handleToggleField("socials")}
                    />
                    <span>Social Links</span>
                  </label>
                  <span style={{ fontSize: 12, color: "#2d0909" }}>
                    {formatBytes(profile.socials.reduce((a, b) => a + b.estimatedBytes, 0))}
                  </span>
                </div>
              )}
            </div>

            {/* Upgrade CTA if on Free Tier */}
            {!isPremium && (
              <div
                style={{
                  background: "rgba(255, 255, 255, 0.05)",
                  border: "1px solid rgba(255, 255, 255, 0.15)",
                  borderRadius: 12,
                  padding: 14,
                  marginBottom: 20,
                  fontSize: 12,
                  color: "#7e0b0b",
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                }}
              >
                <div>
                  <div style={{ fontWeight: 600, color: "#ffffff", marginBottom: 2 }}>Need more room?</div>
                  <div>Lifetime Premium expands your allowance to 50 MB.</div>
                </div>
                <Link
                  href="/premium"
                  target="_blank"
                  style={{
                    background: "#ffffff",
                    color: "#08090b",
                    padding: "6px 12px",
                    borderRadius: 6,
                    fontWeight: 600,
                    textDecoration: "none",
                    whiteSpace: "nowrap",
                  }}
                >
                  Upgrade
                </Link>
              </div>
            )}

            <button
              onClick={() => setShowOverLimitModal(false)}
              style={{
                width: "100%",
                background: "rgba(0, 0, 0, 0.1)",
                color: "#000",
                border: "none",
                borderRadius: 8,
                padding: "10px 14px",
                fontSize: 13,
                fontWeight: 600,
                cursor: "pointer",
              }}
            >
              Done Reviewing
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
