"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import {
  Coins,
  Sparkles,
  Check,
  ExternalLink,
  History,
  Gift,
  Zap,
  Package,
  Send,
  X,
  AlertCircle,
  ArrowRight,
} from "lucide-react";
import {
  CREDIT_SHOP_ITEMS,
  CREDIT_PACKS,
  type CreditShopItem,
  type CreditItemType,
} from "@/lib/credits-catalog";
import {
  getUserCreditsState,
  purchaseItemWithCredits,
  equipCosmetic,
  tipCreditsAction,
  type UserCreditsState,
} from "@/lib/credits-actions";
import { ProfileAvatarBlock } from "./ProfileCosmetics";
import { STOCK_BADGES, type Profile } from "@/lib/constants";
import type { LinkedAccountsState } from "@/lib/linked-accounts";
import DailyRewardsCard from "@/components/DailyRewardsCard";
import CratesView from "@/components/CratesView";
import EarnCreditsSection from "@/components/EarnCreditsSection";
import Link from "next/link";

interface CreditsShopProps {
  profile: Profile;
  update: (patch: Partial<Profile>) => void;
  linkedAccounts?: LinkedAccountsState;
  initialTransferHandle?: string | null;
}

type ShopCategory = "all" | CreditItemType | "crates" | "packs" | "earn" | "transfer";

export default function CreditsShop({
  profile,
  update,
  linkedAccounts,
  initialTransferHandle,
}: CreditsShopProps) {
  const [state, setState] = useState<UserCreditsState | null>(null);
  const [loading, setLoading] = useState(true);
  const [category, setCategory] = useState<ShopCategory>("all");
  const [busyItem, setBusyItem] = useState<string | null>(null);
  const [message, setMessage] = useState<{ text: string; error?: boolean } | null>(null);

  // Transfer modal state
  const [transferModalOpen, setTransferModalOpen] = useState(false);
  const [transferUsername, setTransferUsername] = useState("");
  const [transferAmount, setTransferAmount] = useState("");
  const [transferNote, setTransferNote] = useState("");
  const [transferBusy, setTransferBusy] = useState(false);
  const [transferError, setTransferError] = useState<string | null>(null);

  const loadState = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getUserCreditsState(profile.id);
      setState(res);
    } catch (e) {
      console.error("Failed to load credits state", e);
    } finally {
      setLoading(false);
    }
  }, [profile.id]);

  useEffect(() => {
    loadState();
  }, [loadState]);

  const credits = typeof state?.credits === "number" && (state.credits > 0 || !profile.credits)
    ? state.credits
    : (profile.credits ?? state?.credits ?? 0);
  const unlocks = state?.unlocks ?? [];
  const transactions = state?.transactions ?? [];

  useEffect(() => {
    if (initialTransferHandle) {
      setCategory("transfer");
      setTransferUsername(initialTransferHandle.replace(/^@/, ""));
      setTransferError(null);
    }
  }, [initialTransferHandle]);

  const otherLinkedAccounts = useMemo(() => {
    return (linkedAccounts?.accounts || []).filter(
      (a) => a.id !== profile.id && a.username.toLowerCase() !== profile.username.toLowerCase()
    );
  }, [linkedAccounts, profile.id, profile.username]);

  const rawTransactions = state?.transactions;
  const transferTransactions = useMemo(() => {
    return (rawTransactions || []).filter(
      (tx) =>
        tx.action === "transfer_sent" ||
        tx.action === "transfer_received" ||
        tx.action === "tip_sent" ||
        tx.action === "tip_received" ||
        tx.description?.toLowerCase().includes("transfer") ||
        tx.description?.toLowerCase().includes("tip")
    );
  }, [rawTransactions]);

  const isUnlocked = (item: CreditShopItem) => {
    return unlocks.some((u) => u.itemId === item.id);
  };

  const isEquipped = (item: CreditShopItem) => {
    if (item.type === "avatar_frame") {
      return (profile.avatar_frame || state?.avatarFrame) === item.id;
    }
    if (item.type === "avatar_decoration") {
      const current = profile.avatar_decoration || state?.avatarDecoration;
      return current === (item.assetId || item.id);
    }
    if (item.type === "card_frame") {
      return (profile.card_frame || state?.cardFrame) === item.id;
    }
    if (item.type === "cursor_trail") {
      return profile.cursor_effect === item.id;
    }
    if (item.type === "badge") {
      const currentBadges = Array.isArray(profile.badges) ? profile.badges : [];
      return currentBadges.some((b) => b.id === item.id && b.enabled !== false);
    }
    return false;
  };

  const handlePurchase = async (item: CreditShopItem) => {
    if (credits < item.price) {
      setMessage({ text: `You need ${item.price - credits} more credits for ${item.name}.`, error: true });
      return;
    }

    setBusyItem(item.id);
    setMessage(null);

    const res = await purchaseItemWithCredits(item.id);
    setBusyItem(null);

    if (!res.success) {
      setMessage({ text: res.error || "Purchase failed.", error: true });
      return;
    }

    setMessage({ text: `Unlocked ${item.name} for ${item.price} credits.` });
    
    // Update local state
    setState((prev) => {
      if (!prev) return null;
      return {
        ...prev,
        credits: res.newBalance ?? (prev.credits - item.price),
        unlocks: [...prev.unlocks, { itemType: item.type, itemId: item.id }],
      };
    });
    update({ credits: res.newBalance });
  };

  const handleEquip = async (item: CreditShopItem) => {
    setBusyItem(item.id);
    setMessage(null);

    if (item.type === "avatar_frame" || item.type === "avatar_decoration" || item.type === "card_frame") {
      const isAlreadyEquipped = isEquipped(item);
      const targetId = isAlreadyEquipped ? null : item.id;
      const res = await equipCosmetic(item.type, targetId);

      setBusyItem(null);
      if (!res.success) {
        setMessage({ text: res.error || "Failed to equip item.", error: true });
        return;
      }

      if (item.type === "avatar_frame") {
        setState((prev) => prev ? { ...prev, avatarFrame: targetId } : null);
        update({ avatar_frame: targetId ?? "" });
      } else if (item.type === "avatar_decoration") {
        const storedVal = targetId ? (item.assetId || item.id) : null;
        setState((prev) => prev ? { ...prev, avatarDecoration: storedVal } : null);
        update({ avatar_decoration: storedVal ?? "" });
      } else {
        setState((prev) => prev ? { ...prev, cardFrame: targetId } : null);
        update({ card_frame: targetId ?? "" });
      }
      setMessage({ text: targetId ? `Equipped ${item.name}.` : `Unequipped ${item.name}.` });
    } else if (item.type === "cursor_trail") {
      const isAlreadyEquipped = isEquipped(item);
      const nextCursor = isAlreadyEquipped ? "none" : item.id;
      update({ cursor_effect: nextCursor });
      setBusyItem(null);
      setMessage({ text: isAlreadyEquipped ? `Unequipped ${item.name}.` : `Equipped ${item.name} cursor trail.` });
    } else if (item.type === "badge") {
      // Toggle badge in badges list
      const currentBadges = Array.isArray(profile.badges) ? [...profile.badges] : [];
      const existingBadge = currentBadges.find((b) => b.id === item.id);
      let updatedBadges;
      if (existingBadge && existingBadge.enabled !== false) {
        updatedBadges = currentBadges.filter((b) => b.id !== item.id);
        setMessage({ text: `Unequipped ${item.name} badge from your profile.` });
      } else {
        const stock = STOCK_BADGES.find((b) => b.id === item.id);
        updatedBadges = [
          ...currentBadges.filter((b) => b.id !== item.id),
          {
            id: item.id,
            name: stock?.name || item.name,
            icon: stock?.icon || item.badgeIcon || "⭐",
            monoIcon: stock?.monoIcon || item.badgeIcon || "⭐",
            enabled: true,
          },
        ];
        setMessage({ text: `Equipped ${item.name} badge on your profile.` });
      }
      update({ badges: updatedBadges });
      setBusyItem(null);
    }
  };

  const handleTransfer = async () => {
    const amt = parseInt(transferAmount, 10);
    if (!transferUsername.trim()) {
      setTransferError("Please enter a recipient username.");
      return;
    }
    if (isNaN(amt) || amt <= 0) {
      setTransferError("Please enter a valid credit amount.");
      return;
    }
    if (amt > credits) {
      setTransferError(`Insufficient balance. You currently have ${credits.toLocaleString()} credits.`);
      return;
    }

    setTransferBusy(true);
    setTransferError(null);

    try {
      const res = await tipCreditsAction(transferUsername.trim(), amt, transferNote.trim());
      setTransferBusy(false);

      if (!res.success) {
        setTransferError(res.error || "Transfer failed.");
      } else {
        const cleanHandle = transferUsername.trim().replace(/^@/, "");
        const successNotice = res.isLinkedTransfer
          ? `Successfully transferred ${amt.toLocaleString()} credits to your linked account @${cleanHandle}.`
          : `Successfully sent ${amt.toLocaleString()} credits to @${cleanHandle}.`;

        setMessage({ text: successNotice });
        setTransferModalOpen(false);
        setTransferUsername("");
        setTransferAmount("");
        setTransferNote("");

        if (res.newBalance !== undefined) {
          setState((prev) => (prev ? { ...prev, credits: res.newBalance! } : null));
          update({ credits: res.newBalance });
        }
      }
    } catch {
      setTransferBusy(false);
      setTransferError("Network error completing transfer.");
    }
  };

  const filteredItems = CREDIT_SHOP_ITEMS.filter((item) => {
    if (category === "all") return true;
    return item.type === category;
  });

  if (loading && !state) {
    return (
      <div className="creditsLoadingState">
        <Coins className="creditsLoadingCoin spin" size={32} />
        <p>Loading Sinss Credits shop…</p>
        <style jsx>{`
          .creditsLoadingState {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 60px 20px;
            color: #2d0909;
            gap: 12px;
          }
          :global(.creditsLoadingCoin) {
            color: #f6e6e6;
          }
        `}</style>
      </div>
    );
  }

  return (
    <div className="creditsShopContainer">
      {/* Balance & Overview Card */}
      <section className="creditsHero">
        <div className="creditsHeroMain">
          <div className="creditsHeroBadge">
            <Coins className="creditsHeroCoin" size={28} />
            <div>
              <span className="creditsHeroLabel">Sinss Credits Balance</span>
              <div className="creditsHeroAmount">
                {credits.toLocaleString()}{" "}
                <span className="creditsHeroUnit">Credits</span>
              </div>
            </div>
          </div>
          <p className="creditsHeroDesc">
            Earn credits through profile views and community milestones, or redeem packs to unlock
            exclusive avatar frames, card borders, cursor trails, and utility boosts.
          </p>
        </div>

        <div className="creditsHeroActions">
          <Link href="/crates" className="creditsQuickBtn creditsQuickBtnCrates">
            <Package size={16} />
            <span>Mystery Crates</span>
          </Link>
          <button
            type="button"
            className="creditsQuickBtn creditsQuickBtnEarn"
            onClick={() => setCategory("earn")}
          >
            <Gift size={16} />
            <span>Earn Credits</span>
          </button>
          <button
            type="button"
            className={`creditsQuickBtn creditsQuickBtnTransfer ${category === "transfer" ? "active" : ""}`}
            onClick={() => {
              setCategory("transfer");
            }}
          >
            <Send size={15} />
            <span>Transfer</span>
          </button>
          <button
            type="button"
            className="creditsQuickBtn creditsQuickBtnBuy"
            onClick={() => setCategory("packs")}
          >
            <Zap size={16} />
            <span>Top-up Packs</span>
          </button>
        </div>
      </section>

      {/* Transfer Modal */}
      {transferModalOpen && (
        <div className="transferOverlay" onClick={() => !transferBusy && setTransferModalOpen(false)}>
          <div className="transferModalCard" onClick={(e) => e.stopPropagation()}>
            <div className="transferModalHead">
              <div className="transferModalTitleWrap">
                <Coins size={22} className="transferCoinIcon" />
                <div>
                  <h3>Transfer Sinss Credits</h3>
                  <p>Send credits to your other linked accounts or any username.</p>
                </div>
              </div>
              <button
                type="button"
                className="transferCloseBtn"
                onClick={() => setTransferModalOpen(false)}
                disabled={transferBusy}
              >
                <X size={16} />
              </button>
            </div>

            <div className="transferRuleNotice">
              <Coins size={13} className="transferNoticeCoin" />
              <span>
                Daily rewards and free quest credits can only be claimed on one account across your linked profiles. You can transfer credits between your linked accounts at any time.
              </span>
            </div>

            {transferError && (
              <div className="transferErrorBox">
                <AlertCircle size={14} />
                <span>{transferError}</span>
              </div>
            )}

            <div className="transferFormGroup">
              <label htmlFor="transfer-user">Recipient Username</label>
              <div className="transferInputWrap">
                <span className="transferPrefix">@</span>
                <input
                  id="transfer-user"
                  type="text"
                  placeholder="username"
                  value={transferUsername}
                  onChange={(e) => setTransferUsername(e.target.value.replace(/^@/, ''))}
                  disabled={transferBusy}
                />
              </div>
            </div>

            <div className="transferFormGroup">
              <div className="transferAmountHead">
                <label htmlFor="transfer-amount">Amount</label>
                <span className="transferBalanceHint">
                  Available: <strong>{credits.toLocaleString()}</strong>
                </span>
              </div>
              <div className="transferInputWrap">
                <Coins size={14} className="transferInputCoin" />
                <input
                  id="transfer-amount"
                  type="number"
                  min="1"
                  max={credits}
                  placeholder="0"
                  value={transferAmount}
                  onChange={(e) => setTransferAmount(e.target.value)}
                  disabled={transferBusy}
                />
                <button
                  type="button"
                  className="transferMaxBtn"
                  onClick={() => setTransferAmount(String(credits))}
                  disabled={transferBusy || credits <= 0}
                >
                  Max
                </button>
              </div>

              <div className="transferPresets">
                {[50, 100, 250, 500].map((val) => (
                  <button
                    key={val}
                    type="button"
                    className={`transferPresetChip ${transferAmount === String(val) ? "active" : ""}`}
                    onClick={() => setTransferAmount(String(val))}
                    disabled={transferBusy || credits < val}
                  >
                    +{val}
                  </button>
                ))}
              </div>
            </div>

            <div className="transferFormGroup">
              <label htmlFor="transfer-note">Message (Optional)</label>
              <input
                id="transfer-note"
                type="text"
                maxLength={140}
                placeholder="E.g. Moving credits to main account"
                value={transferNote}
                onChange={(e) => setTransferNote(e.target.value)}
                disabled={transferBusy}
                className="transferNoteInput"
              />
            </div>

            <div className="transferModalActions">
              <button
                type="button"
                className="transferCancelBtn"
                onClick={() => setTransferModalOpen(false)}
                disabled={transferBusy}
              >
                Cancel
              </button>
              <button
                type="button"
                className="transferSubmitBtn"
                onClick={handleTransfer}
                disabled={transferBusy || !transferUsername.trim() || !transferAmount || parseInt(transferAmount, 10) <= 0}
              >
                <Send size={14} />
                <span>{transferBusy ? "Transferring…" : "Send Transfer"}</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Notification Banner */}
      {message && (
        <div className={`creditsAlert ${message.error ? "creditsAlertError" : "creditsAlertSuccess"}`}>
          <span>{message.text}</span>
          <button type="button" onClick={() => setMessage(null)} className="creditsAlertClose">
            ✕
          </button>
        </div>
      )}

      {/* Navigation Filter Tabs */}
      <nav className="creditsFilterBar" aria-label="Credits Shop Categories">
        <button
          type="button"
          className={`creditsFilterChip ${category === "all" ? "active" : ""}`}
          onClick={() => setCategory("all")}
        >
          All Items
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "avatar_frame" ? "active" : ""}`}
          onClick={() => setCategory("avatar_frame")}
        >
          Avatar Frames
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "avatar_decoration" ? "active" : ""}`}
          onClick={() => setCategory("avatar_decoration")}
        >
          Decorations
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "card_frame" ? "active" : ""}`}
          onClick={() => setCategory("card_frame")}
        >
          Card Borders
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "cursor_trail" ? "active" : ""}`}
          onClick={() => setCategory("cursor_trail")}
        >
          Cursor Trails
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "badge" ? "active" : ""}`}
          onClick={() => setCategory("badge")}
        >
          Badges
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "utility" ? "active" : ""}`}
          onClick={() => setCategory("utility")}
        >
          Utilities
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "crates" ? "active" : ""}`}
          onClick={() => setCategory("crates")}
        >
          Crates
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "packs" ? "active" : ""}`}
          onClick={() => setCategory("packs")}
        >
          Credit Packs
        </button>
        <button
          type="button"
          className={`creditsFilterChip ${category === "earn" ? "active" : ""}`}
          onClick={() => setCategory("earn")}
        >
          Earn Free
        </button>
        <button
          type="button"
          className={`creditsFilterChip creditsFilterChipTransfer ${category === "transfer" ? "active" : ""}`}
          onClick={() => setCategory("transfer")}
        >
          <Send size={12} style={{ marginRight: 6 }} />
          Transfer
        </button>
      </nav>

      {/* Transfer Hub Section */}
      {category === "transfer" && (
        <section className="creditsSection transferHubSection">
          <div className="cardHead2">
            <div className="transferHeadRow">
              <div className="transferHeadIcon">
                <Send size={24} />
              </div>
              <div>
                <h2>Transfer Sinss Credits</h2>
                <p>Transfer credits instantly between your linked accounts or tip any user on sinss.lol.</p>
              </div>
            </div>
          </div>

          <div className="transferHubRuleNotice">
            <Coins size={14} className="transferNoticeCoin" />
            <span>
              <strong>Account Policy:</strong> Daily rewards and milestone quest credits can only be claimed once across linked accounts. You can transfer credits between your linked accounts at any time without fees or limits.
            </span>
          </div>

          <div className="transferHubGrid">
            {/* Left Column: Transfer Form */}
            <div className="transferHubCard">
              <h3 className="transferCardTitle">Send Credits</h3>

              {/* Linked Accounts Quick Pick */}
              {otherLinkedAccounts.length > 0 && (
                <div className="transferLinkedGroup">
                  <span className="transferLinkedLabel">Quick Transfer to Linked Account:</span>
                  <div className="transferLinkedChips">
                    {otherLinkedAccounts.map((acc) => (
                      <button
                        key={acc.id}
                        type="button"
                        className={`transferLinkedChip ${transferUsername.toLowerCase() === acc.username.toLowerCase() ? "active" : ""}`}
                        onClick={() => {
                          setTransferUsername(acc.username);
                          setTransferError(null);
                        }}
                      >
                        {acc.avatar_url ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img src={acc.avatar_url} alt="" className="transferLinkedAvatar" />
                        ) : (
                          <div className="transferLinkedAvatarPlaceholder">
                            {acc.username.slice(0, 1).toUpperCase()}
                          </div>
                        )}
                        <span className="transferLinkedName">@{acc.username}</span>
                        {transferUsername.toLowerCase() === acc.username.toLowerCase() && (
                          <Check size={13} className="transferCheck" />
                        )}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {transferError && (
                <div className="transferErrorBox">
                  <AlertCircle size={14} />
                  <span>{transferError}</span>
                </div>
              )}

              <div className="transferFormGroup">
                <label htmlFor="hub-transfer-user">Recipient Username</label>
                <div className="transferInputWrap">
                  <span className="transferPrefix">@</span>
                  <input
                    id="hub-transfer-user"
                    type="text"
                    placeholder="username"
                    value={transferUsername}
                    onChange={(e) => {
                      setTransferUsername(e.target.value.replace(/^@/, ""));
                      setTransferError(null);
                    }}
                    disabled={transferBusy}
                  />
                </div>
              </div>

              <div className="transferFormGroup">
                <div className="transferAmountHead">
                  <label htmlFor="hub-transfer-amount">Amount</label>
                  <span className="transferBalanceHint">
                    Available: <strong>{credits.toLocaleString()}</strong>
                  </span>
                </div>
                <div className="transferInputWrap">
                  <Coins size={14} className="transferInputCoin" />
                  <input
                    id="hub-transfer-amount"
                    type="number"
                    min="1"
                    max={credits}
                    placeholder="0"
                    value={transferAmount}
                    onChange={(e) => {
                      setTransferAmount(e.target.value);
                      setTransferError(null);
                    }}
                    disabled={transferBusy}
                  />
                  <button
                    type="button"
                    className="transferMaxBtn"
                    onClick={() => {
                      setTransferAmount(String(credits));
                      setTransferError(null);
                    }}
                    disabled={transferBusy || credits <= 0}
                  >
                    Max
                  </button>
                </div>

                <div className="transferPresets">
                  {[50, 100, 250, 500, 1000].map((val) => (
                    <button
                      key={val}
                      type="button"
                      className={`transferPresetChip ${transferAmount === String(val) ? "active" : ""}`}
                      onClick={() => {
                        setTransferAmount(String(val));
                        setTransferError(null);
                      }}
                      disabled={transferBusy || credits < val}
                    >
                      +{val >= 1000 ? `${val / 1000}k` : val}
                    </button>
                  ))}
                </div>
              </div>

              <div className="transferFormGroup">
                <label htmlFor="hub-transfer-note">Message / Memo (Optional)</label>
                <input
                  id="hub-transfer-note"
                  type="text"
                  maxLength={140}
                  placeholder="E.g. Moving credits to main account"
                  value={transferNote}
                  onChange={(e) => setTransferNote(e.target.value)}
                  disabled={transferBusy}
                  className="transferNoteInput"
                />
              </div>

              <button
                type="button"
                className="transferHubSubmitBtn"
                onClick={handleTransfer}
                disabled={transferBusy || !transferUsername.trim() || !transferAmount || parseInt(transferAmount, 10) <= 0}
              >
                <Send size={15} />
                <span>{transferBusy ? "Transferring…" : "Send Transfer"}</span>
              </button>
            </div>

            {/* Right Column: Recent Transfers History */}
            <div className="transferHubCard">
              <h3 className="transferCardTitle">Transfer History</h3>
              {transferTransactions.length === 0 ? (
                <div className="transferEmptyHistory">
                  <Send size={24} className="transferEmptyIcon" />
                  <p>No credit transfers yet.</p>
                  <small>Transfers sent or received from your accounts will appear here.</small>
                </div>
              ) : (
                <div className="transferTxList">
                  {transferTransactions.slice(0, 10).map((tx) => {
                    const isSent = tx.action === "transfer_sent" || tx.action === "tip_sent" || tx.amount < 0;
                    return (
                      <div key={tx.id} className="transferTxItem">
                        <div className={`transferTxIcon ${isSent ? "sent" : "received"}`}>
                          <Send size={13} style={{ transform: isSent ? "none" : "rotate(180deg)" }} />
                        </div>
                        <div className="transferTxDetails">
                          <span className="transferTxTitle">
                            {isSent ? "Transfer Sent" : "Transfer Received"}
                          </span>
                          <span className="transferTxMeta">
                            {tx.description || (isSent ? "Sent to account" : "Received from account")}
                            {tx.createdAt ? ` · ${new Date(tx.createdAt).toLocaleDateString()}` : ""}
                          </span>
                        </div>
                        <div className={`transferTxAmount ${isSent ? "sent" : "received"}`}>
                          {isSent ? `-${Math.abs(tx.amount).toLocaleString()}` : `+${tx.amount.toLocaleString()}`}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </section>
      )}

      {/* Earn Section */}
      {category === "earn" && (
        <section className="creditsSection">
          <div style={{ marginBottom: 20 }}>
            <DailyRewardsCard
              profile={profile}
              onClaimSuccess={(data) => {
                update({
                  credits: data.newBalance,
                  daily_streak: data.day,
                });
                loadState();
              }}
            />
          </div>

          <EarnCreditsSection
            profile={profile}
            claimedMilestones={state?.claimedMilestones || []}
            onClaimSuccess={(milestoneId, earned, newBalance) => {
              update({ credits: newBalance });
              setState((prev) => {
                if (!prev) return null;
                return {
                  ...prev,
                  credits: newBalance,
                  claimedMilestones: [...(prev.claimedMilestones || []), milestoneId],
                };
              });
              setMessage({ text: `Claimed +${earned} credits.` });
            }}
          />
        </section>
      )}

      {/* Credit Packs Section */}
      {category === "packs" && (
        <section className="creditsSection">
          <div className="cardHead2">
            <h2>Credit Packs</h2>
            <p>Purchase credits to unlock exclusive cosmetics and utility perks instantly.</p>
          </div>

          <div className="packsGrid">
            {CREDIT_PACKS.map((pack) => (
              <div
                key={pack.id}
                className={`packCard ${pack.popular ? "packCardPopular" : ""}`}
              >
                {pack.popular && <span className="packBadge">Most Popular</span>}
                <div className="packCoins">
                  <Coins size={32} />
                </div>
                <h3 className="packTitle">{pack.name}</h3>
                <div className="packAmount">{pack.credits.toLocaleString()} Credits</div>
                <div className="packPrice">${pack.priceUsd.toFixed(2)}</div>
                <Link href="/premium" className="packBtn">
                  Purchase Pack
                </Link>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Mystery Crates Section */}
      {category === "crates" && (
        <section className="creditsSection">
          <div className="cratesHubBanner">
            <div className="cratesHubBannerText">
              <span className="cratesHubTag">Full Experience</span>
              <strong>Dedicated Mystery Crates Hub Available</strong>
              <p>Explore CS2-style case inspections, item probabilities, daily rewards, and free credit quests on the dedicated page.</p>
            </div>
            <Link href="/crates" className="cratesHubLink">
              <span>Open Dedicated Page</span>
              <ExternalLink size={14} />
            </Link>
          </div>
          <CratesView
            credits={credits}
            onBalanceUpdate={(newBalance) => {
              if (state) setState({ ...state, credits: newBalance });
              update({ credits: newBalance });
            }}
            onEquipCosmetic={(type, id) => {
              const matched = CREDIT_SHOP_ITEMS.find((i) => i.id === id);
              if (matched) handleEquip(matched);
            }}
          />
        </section>
      )}

      {/* Catalog Items Grid */}
      {category !== "packs" && category !== "earn" && category !== "crates" && category !== "transfer" && (
        <section className="creditsSection">
          {category === "all" && (
            <div className="transferBannerPromo" onClick={() => setCategory("transfer")}>
              <div className="transferBannerLeft">
                <div className="transferBannerIcon">
                  <Send size={18} />
                </div>
                <div className="transferBannerText">
                  <strong>Transfer Credits Between Accounts</strong>
                  <p>Send credits to your linked profiles or tip any username on sinss.lol.</p>
                </div>
              </div>
              <button type="button" className="transferBannerBtn">
                <span>Transfer</span>
                <ArrowRight size={14} />
              </button>
            </div>
          )}

          <div className="cardHead2">
            <h2>
              {category === "all"
                ? "Cosmetic & Utility Catalog"
                : category === "avatar_frame"
                ? "Avatar Frames"
                : category === "avatar_decoration"
                ? "Discord Avatar Decorations"
                : category === "card_frame"
                ? "Card Borders"
                : category === "cursor_trail"
                ? "Cursor Trails"
                : category === "badge"
                ? "Exclusive Badges"
                : "Profile Utilities"}
            </h2>
            <p>Items unlocked with Sinss Credits are permanently saved to your account.</p>
          </div>

          <div className="catalogGrid">
            {filteredItems.map((item) => {
              const owned = isUnlocked(item);
              const equipped = isEquipped(item);
              const canAfford = credits >= item.price;
              const isBusy = busyItem === item.id;

              return (
                <div
                  key={item.id}
                  className={`catalogCard ${owned ? "catalogCardOwned" : ""} ${
                    equipped ? "catalogCardEquipped" : ""
                  }`}
                >
                  <div className="catalogPreviewWrap">
                    {item.type === "avatar_decoration" || item.type === "avatar_frame" ? (
                      <ProfileAvatarBlock
                        profile={{
                          ...profile,
                          avatar_frame: item.type === "avatar_frame" ? item.id : null,
                          avatar_decoration: item.type === "avatar_decoration" ? (item.assetId || item.previewUrl || item.id) : null,
                        }}
                        size={58}
                        margin={0}
                        fallbackPlaceholder={true}
                      />
                    ) : item.previewUrl ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={item.previewUrl}
                        alt=""
                        className="catalogPreviewImg"
                        style={{
                          maxHeight: 100,
                          objectFit: "contain",
                        }}
                      />
                    ) : item.badgeIcon ? (
                      <span className="catalogPreviewEmoji">{item.badgeIcon}</span>
                    ) : (
                      <div
                        className="catalogPreviewGraphic"
                        style={{
                          borderColor: item.color || "#f5caca",
                          boxShadow: item.color ? `0 0 16px ${item.color}44` : undefined,
                        }}
                      >
                        <Sparkles size={24} style={{ color: item.color || "#f5caca" }} />
                      </div>
                    )}
                    {equipped && <span className="equippedPill">Equipped</span>}
                  </div>

                  <div className="catalogInfo">
                    <div className="catalogTitleRow">
                      <strong className="catalogItemName">{item.name}</strong>
                      <span className="catalogItemPrice">
                        <Coins size={13} /> {item.price}
                      </span>
                    </div>
                    <p className="catalogItemDesc">{item.description}</p>
                  </div>

                  <div className="catalogFooter">
                    {owned ? (
                      <button
                        type="button"
                        className={`catalogBtn ${equipped ? "catalogBtnEquipped" : "catalogBtnEquip"}`}
                        disabled={isBusy}
                        onClick={() => handleEquip(item)}
                      >
                        {isBusy ? (
                          "Updating…"
                        ) : equipped ? (
                          <>
                            <Check size={14} /> Equipped (Click to Unequip)
                          </>
                        ) : (
                          "Equip"
                        )}
                      </button>
                    ) : (
                      <button
                        type="button"
                        className={`catalogBtn ${canAfford ? "catalogBtnBuy" : "catalogBtnTopUp"}`}
                        disabled={isBusy}
                        onClick={() => {
                          if (!canAfford) {
                            setCategory("packs");
                            setMessage({
                              text: `You need ${(item.price - credits).toLocaleString()} more credits for ${item.name}. Choose a credit pack below to top up.`,
                            });
                            return;
                          }
                          handlePurchase(item);
                        }}
                      >
                        {isBusy ? (
                          "Unlocking…"
                        ) : canAfford ? (
                          <>
                            <Coins size={14} /> Unlock for {item.price}
                          </>
                        ) : (
                          <>
                            <Coins size={14} /> Need {item.price - credits} more · Top Up
                          </>
                        )}
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </section>
      )}

      {/* Transaction History Section */}
      <section className="creditsSection">
        <div className="cardHead2">
          <h2>
            <History size={18} style={{ display: "inline-block", verticalAlign: "text-bottom", marginRight: 8 }} />
            Transaction History
          </h2>
          <p>Recent credit earnings, purchases, and reward claims.</p>
        </div>

        {transactions.length === 0 ? (
          <div className="empty2">No credit transactions yet. Unlock cosmetics or claim milestones above!</div>
        ) : (
          <div className="txList">
            {transactions.map((tx) => {
              const isPositive = tx.amount > 0;
              return (
                <div key={tx.id} className="txRow">
                  <div className="txInfo">
                    <strong>{tx.description}</strong>
                    <small>
                      {new Date(tx.createdAt).toLocaleDateString(undefined, {
                        month: "short",
                        day: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </small>
                  </div>
                  <div className="txAmountWrap">
                    <span className={`txAmount ${isPositive ? "txPositive" : "txNegative"}`}>
                      {isPositive ? `+${tx.amount}` : tx.amount} Credits
                    </span>
                    <small className="txBalance">Bal: {tx.balanceAfter}</small>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </section>

      <style jsx>{`
        .creditsShopContainer {
          display: flex;
          flex-direction: column;
          gap: 24px;
        }

        .creditsHero {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 20px;
          padding: 26px 30px;
          border-radius: 18px;
          background: linear-gradient(135deg, rgba(246, 230, 230, 0.08), rgba(12, 12, 18, 0.95) 60%);
          border: 1px solid rgba(246, 230, 230, 0.25);
          box-shadow: 0 12px 40px -10px rgba(0, 0, 0, 0.6), inset 0 0 20px rgba(246, 230, 230, 0.04);
        }

        @media (max-width: 800px) {
          .creditsHero {
            flex-direction: column;
            align-items: flex-start;
          }
        }

        .creditsHeroBadge {
          display: flex;
          align-items: center;
          gap: 16px;
          margin-bottom: 8px;
        }

        :global(.creditsHeroCoin) {
          color: #f6e6e6;
          filter: drop-shadow(0 0 10px rgba(246, 230, 230, 0.6));
        }

        .creditsHeroLabel {
          font-size: 12px;
          text-transform: uppercase;
          letter-spacing: 0.1em;
          color: #f6e6e6;
          font-weight: 750;
        }

        .creditsHeroAmount {
          font-size: 32px;
          font-weight: 900;
          color: #000;
          letter-spacing: -0.02em;
        }

        .creditsHeroUnit {
          font-size: 16px;
          font-weight: 600;
          color: #390505;
        }

        .creditsHeroDesc {
          margin: 6px 0 0;
          font-size: 14px;
          color: #2d0909;
          max-width: 580px;
          line-height: 1.5;
        }

        .creditsHeroActions {
          display: flex;
          gap: 12px;
          flex-shrink: 0;
        }

        .creditsQuickBtn {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          padding: 10px 18px;
          border-radius: 12px;
          font-size: 14px;
          font-weight: 700;
          cursor: pointer;
          transition: all 0.16s ease;
        }

        .creditsQuickBtnCrates {
          background: linear-gradient(135deg, rgba(247, 217, 217, 0.2), rgba(247, 217, 217, 0.35));
          border: 1px solid rgba(247, 217, 217, 0.5);
          color: #ffffff;
          text-decoration: none;
        }

        .creditsQuickBtnCrates:hover {
          background: linear-gradient(135deg, rgba(247, 217, 217, 0.35), rgba(247, 217, 217, 0.5));
          transform: translateY(-1px);
          color: #000;
        }

        .creditsQuickBtnEarn {
          background: rgba(0, 0, 0, 0.06);
          border: 1px solid rgba(0, 0, 0, 0.14);
          color: #000;
        }

        .creditsQuickBtnEarn:hover {
          background: rgba(0, 0, 0, 0.12);
        }

        .creditsQuickBtnBuy {
          background: #f6e6e6;
          border: 1px solid #fdf6f6;
          color: #111;
        }

        .creditsQuickBtnTransfer {
          background: rgba(245, 202, 202, 0.16);
          border: 1px solid rgba(245, 202, 202, 0.45);
          color: #f5caca;
          box-shadow: 0 0 14px rgba(245, 202, 202, 0.12);
        }

        .creditsQuickBtnTransfer:hover,
        .creditsQuickBtnTransfer.active {
          background: rgba(245, 202, 202, 0.28);
          border-color: #f5caca;
          color: #000;
          transform: translateY(-1px);
        }

        /* Transfer Modal Styles */
        .transferOverlay {
          position: fixed;
          inset: 0;
          background: rgba(0, 0, 0, 0.75);
          backdrop-filter: blur(10px);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 10000;
          padding: 20px;
        }

        .transferModalCard {
          width: min(100%, 480px);
          background: #0f1117;
          border: 1px solid rgba(0, 0, 0, 0.12);
          border-radius: 18px;
          padding: 28px;
          box-shadow: 0 24px 60px rgba(0, 0, 0, 0.8);
          animation: transferModalPop 0.2s cubic-bezier(0.16, 1, 0.3, 1);
        }

        @keyframes transferModalPop {
          from {
            opacity: 0;
            transform: scale(0.96) translateY(8px);
          }
          to {
            opacity: 1;
            transform: scale(1) translateY(0);
          }
        }

        .transferModalHead {
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          margin-bottom: 16px;
        }

        .transferModalTitleWrap {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        :global(.transferCoinIcon) {
          color: #f5e1e1;
        }

        .transferModalTitleWrap h3 {
          font-size: 18px;
          font-weight: 700;
          color: #000;
          margin: 0;
        }

        .transferModalTitleWrap p {
          font-size: 12px;
          color: #551212;
          margin: 2px 0 0;
        }

        .transferCloseBtn {
          background: transparent;
          border: none;
          color: #3d1616;
          cursor: pointer;
          padding: 4px;
          border-radius: 6px;
          transition: color 0.15s ease;
        }

        .transferCloseBtn:hover {
          color: #000;
        }

        .transferRuleNotice {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 10px 14px;
          border-radius: 10px;
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid rgba(255, 255, 255, 0.15);
          font-size: 11.5px;
          color: #7e0b0b;
          line-height: 1.5;
          margin-bottom: 18px;
        }

        :global(.transferNoticeCoin) {
          color: #f5e1e1;
          flex-shrink: 0;
        }

        .transferErrorBox {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px 12px;
          border-radius: 8px;
          background: rgba(239, 191, 191, 0.15);
          border: 1px solid rgba(239, 191, 191, 0.3);
          color: #fce1e1;
          font-size: 12px;
          margin-bottom: 16px;
        }

        .transferFormGroup {
          margin-bottom: 16px;
        }

        .transferFormGroup label {
          display: block;
          font-size: 12px;
          font-weight: 600;
          color: #7e0b0b;
          margin-bottom: 6px;
        }

        .transferAmountHead {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 6px;
        }

        .transferBalanceHint {
          font-size: 11.5px;
          color: #551212;
        }

        .transferBalanceHint strong {
          color: #000;
        }

        .transferInputWrap {
          display: flex;
          align-items: center;
          background: #161922;
          border: 1px solid rgba(0, 0, 0, 0.1);
          border-radius: 10px;
          padding: 4px 12px;
          gap: 8px;
          transition: border-color 0.15s ease;
        }

        .transferInputWrap:focus-within {
          border-color: #f5caca;
        }

        .transferPrefix {
          color: #3d1616;
          font-weight: 700;
          font-size: 15px;
        }

        :global(.transferInputCoin) {
          color: #f5e1e1;
        }

        .transferInputWrap input {
          flex: 1;
          background: transparent;
          border: none;
          outline: none;
          color: #000;
          font-size: 14px;
          padding: 8px 0;
        }

        .transferMaxBtn {
          background: rgba(0, 0, 0, 0.08);
          border: 1px solid rgba(0, 0, 0, 0.15);
          color: #9b0707;
          font-size: 11px;
          font-weight: 700;
          padding: 4px 10px;
          border-radius: 6px;
          cursor: pointer;
          transition: background 0.15s ease;
        }

        .transferMaxBtn:hover:not(:disabled) {
          background: rgba(0, 0, 0, 0.16);
          color: #000;
        }

        .transferPresets {
          display: flex;
          gap: 6px;
          margin-top: 8px;
        }

        .transferPresetChip {
          padding: 4px 10px;
          border-radius: 6px;
          font-size: 11px;
          font-weight: 600;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.08);
          color: #551212;
          cursor: pointer;
          transition: all 0.15s ease;
        }

        .transferPresetChip:hover:not(:disabled) {
          background: rgba(0, 0, 0, 0.09);
          color: #000;
        }

        .transferPresetChip.active {
          border-color: #f5caca;
          color: #f5caca;
          background: rgba(245, 202, 202, 0.1);
        }

        .transferNoteInput {
          width: 100%;
          background: #161922;
          border: 1px solid rgba(0, 0, 0, 0.1);
          border-radius: 10px;
          padding: 10px 14px;
          color: #000;
          font-size: 13px;
          outline: none;
          transition: border-color 0.15s ease;
        }

        .transferNoteInput:focus {
          border-color: #f5caca;
        }

        .transferModalActions {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 10px;
          margin-top: 24px;
          padding-top: 18px;
          border-top: 1px solid rgba(0, 0, 0, 0.08);
        }

        .transferCancelBtn {
          padding: 9px 18px;
          border-radius: 10px;
          font-size: 13px;
          font-weight: 600;
          background: transparent;
          border: 1px solid rgba(0, 0, 0, 0.12);
          color: #551212;
          cursor: pointer;
          transition: color 0.15s ease;
        }

        .transferCancelBtn:hover:not(:disabled) {
          color: #000;
        }

        .transferSubmitBtn {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          padding: 10px 22px;
          border-radius: 10px;
          font-size: 13px;
          font-weight: 700;
          background: #f6dbdb;
          border: none;
          color: #000;
          cursor: pointer;
          transition: all 0.15s ease;
        }

        .transferSubmitBtn:hover:not(:disabled) {
          background: #ebbdbd;
          transform: translateY(-1px);
        }

        .transferSubmitBtn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        /* Filter Chip Transfer */
        .creditsFilterChipTransfer {
          display: inline-flex;
          align-items: center;
        }

        .creditsFilterChipTransfer.active {
          background: rgba(245, 202, 202, 0.18) !important;
          border-color: #f5caca !important;
          color: #f5caca !important;
        }

        /* Transfer Banner Promo on Catalog */
        .transferBannerPromo {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 16px;
          padding: 16px 22px;
          border-radius: 14px;
          background: linear-gradient(135deg, rgba(245, 202, 202, 0.08), rgba(13, 18, 31, 0.95) 75%);
          border: 1px solid rgba(245, 202, 202, 0.25);
          cursor: pointer;
          margin-bottom: 24px;
          transition: all 0.18s ease;
          box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
        }

        .transferBannerPromo:hover {
          border-color: #f5caca;
          background: linear-gradient(135deg, rgba(245, 202, 202, 0.14), rgba(13, 18, 31, 0.98) 75%);
          transform: translateY(-1px);
        }

        .transferBannerLeft {
          display: flex;
          align-items: center;
          gap: 14px;
        }

        .transferBannerIcon {
          width: 40px;
          height: 40px;
          border-radius: 10px;
          background: rgba(245, 202, 202, 0.12);
          border: 1px solid rgba(245, 202, 202, 0.3);
          color: #f5caca;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .transferBannerText strong {
          display: block;
          font-size: 14.5px;
          color: #000;
          margin-bottom: 2px;
        }

        .transferBannerText p {
          margin: 0;
          font-size: 12.5px;
          color: #551212;
        }

        .transferBannerBtn {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          border-radius: 8px;
          background: #f5caca;
          border: none;
          color: #061014;
          font-size: 13px;
          font-weight: 750;
          cursor: pointer;
          flex-shrink: 0;
          transition: opacity 0.15s ease;
        }

        .transferBannerPromo:hover .transferBannerBtn {
          opacity: 0.9;
        }

        /* Transfer Hub Page Section */
        .transferHubSection {
          margin-bottom: 28px;
        }

        .transferHeadRow {
          display: flex;
          align-items: center;
          gap: 14px;
        }

        .transferHeadIcon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          background: rgba(245, 202, 202, 0.12);
          border: 1px solid rgba(245, 202, 202, 0.3);
          color: #f5caca;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .transferHubRuleNotice {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 12px 16px;
          border-radius: 12px;
          background: rgba(245, 202, 202, 0.05);
          border: 1px solid rgba(245, 202, 202, 0.2);
          font-size: 12px;
          color: #7e0b0b;
          line-height: 1.5;
          margin-bottom: 20px;
        }

        .transferHubRuleNotice strong {
          color: #f5caca;
        }

        .transferHubGrid {
          display: grid;
          grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr);
          gap: 20px;
        }

        @media (max-width: 900px) {
          .transferHubGrid {
            grid-template-columns: 1fr;
          }
        }

        .transferHubCard {
          background: #0f1117;
          border: 1px solid rgba(0, 0, 0, 0.1);
          border-radius: 16px;
          padding: 24px;
          box-shadow: 0 12px 36px rgba(0, 0, 0, 0.5);
        }

        .transferCardTitle {
          font-size: 16px;
          font-weight: 700;
          color: #000;
          margin: 0 0 18px;
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .transferLinkedGroup {
          margin-bottom: 18px;
          padding: 12px 14px;
          border-radius: 12px;
          background: rgba(0, 0, 0, 0.02);
          border: 1px dashed rgba(0, 0, 0, 0.1);
        }

        .transferLinkedLabel {
          display: block;
          font-size: 11px;
          font-weight: 700;
          text-transform: uppercase;
          letter-spacing: 0.05em;
          color: #3d1616;
          margin-bottom: 8px;
        }

        .transferLinkedChips {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .transferLinkedChip {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          padding: 6px 12px;
          border-radius: 10px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.1);
          color: #9b0707;
          font-size: 12px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.15s ease;
        }

        .transferLinkedChip:hover {
          background: rgba(245, 202, 202, 0.1);
          border-color: rgba(245, 202, 202, 0.35);
          color: #000;
        }

        .transferLinkedChip.active {
          background: rgba(245, 202, 202, 0.18);
          border-color: #f5caca;
          color: #f5caca;
        }

        .transferLinkedAvatar {
          width: 22px;
          height: 22px;
          border-radius: 50%;
          object-fit: cover;
        }

        .transferLinkedAvatarPlaceholder {
          width: 22px;
          height: 22px;
          border-radius: 50%;
          background: #512f2f;
          color: #000;
          font-size: 11px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
        }

        .transferCheck {
          color: #f5caca;
          margin-left: 2px;
        }

        .transferHubSubmitBtn {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          width: 100%;
          height: 44px;
          border-radius: 10px;
          background: #f5caca;
          border: none;
          color: #061014;
          font-size: 13.5px;
          font-weight: 800;
          cursor: pointer;
          transition: all 0.15s ease;
          margin-top: 10px;
        }

        .transferHubSubmitBtn:hover:not(:disabled) {
          background: #fadede;
          transform: translateY(-1px);
        }

        .transferHubSubmitBtn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .transferEmptyHistory {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 40px 20px;
          text-align: center;
          color: #3d1616;
        }

        :global(.transferEmptyIcon) {
          color: #512f2f;
          margin-bottom: 12px;
        }

        .transferEmptyHistory p {
          margin: 0 0 4px;
          font-size: 13.5px;
          color: #551212;
          font-weight: 600;
        }

        .transferEmptyHistory small {
          font-size: 12px;
          color: #3d1616;
          max-width: 260px;
        }

        .transferTxList {
          display: flex;
          flex-direction: column;
          gap: 10px;
          max-height: 420px;
          overflow-y: auto;
          padding-right: 4px;
        }

        .transferTxItem {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 10px 12px;
          border-radius: 10px;
          background: rgba(0, 0, 0, 0.02);
          border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .transferTxIcon {
          width: 30px;
          height: 30px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .transferTxIcon.sent {
          background: rgba(239, 191, 191, 0.12);
          color: #f8d6d6;
        }

        .transferTxIcon.received {
          background: rgba(214, 146, 146, 0.12);
          color: #de8383;
        }

        .transferTxDetails {
          flex: 1;
          min-width: 0;
        }

        .transferTxTitle {
          display: block;
          font-size: 12.5px;
          font-weight: 600;
          color: #9b0707;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .transferTxMeta {
          display: block;
          font-size: 11px;
          color: #3d1616;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .transferTxAmount {
          font-size: 13px;
          font-weight: 750;
          flex-shrink: 0;
        }

        .transferTxAmount.sent {
          color: #f8d6d6;
        }

        .transferTxAmount.received {
          color: #de8383;
        }

        .cratesHubBanner {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 20px;
          padding: 18px 24px;
          border-radius: 14px;
          background: linear-gradient(135deg, rgba(247, 217, 217, 0.12), rgba(15, 17, 23, 0.95) 70%);
          border: 1px solid rgba(247, 217, 217, 0.3);
          margin-bottom: 24px;
          flex-wrap: wrap;
        }

        .cratesHubBannerText strong {
          display: block;
          font-size: 15px;
          font-weight: 700;
          color: #000;
          margin-bottom: 4px;
        }

        .cratesHubBannerText p {
          font-size: 13px;
          color: #551212;
          margin: 0;
          line-height: 1.4;
        }

        .cratesHubTag {
          display: inline-block;
          font-size: 10px;
          font-weight: 800;
          text-transform: uppercase;
          letter-spacing: 0.5px;
          color: #fceaea;
          background: rgba(247, 217, 217, 0.2);
          border: 1px solid rgba(247, 217, 217, 0.4);
          padding: 2px 8px;
          border-radius: 999px;
          margin-bottom: 6px;
        }

        .cratesHubLink {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          background: #f7d9d9;
          color: #000;
          text-decoration: none;
          font-size: 13px;
          font-weight: 700;
          padding: 8px 16px;
          border-radius: 8px;
          transition: background 0.15s ease;
          white-space: nowrap;
        }

        .cratesHubLink:hover {
          background: #eab5b5;
        }

        .creditsAlert {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 18px;
          border-radius: 12px;
          font-size: 14px;
          font-weight: 600;
        }

        .creditsAlertSuccess {
          background: rgba(214, 146, 146, 0.12);
          border: 1px solid rgba(214, 146, 146, 0.3);
          color: #de8383;
        }

        .creditsAlertError {
          background: rgba(239, 191, 191, 0.12);
          border: 1px solid rgba(239, 191, 191, 0.3);
          color: #f8d6d6;
        }

        .creditsAlertClose {
          background: transparent;
          border: none;
          color: inherit;
          cursor: pointer;
          font-size: 16px;
          padding: 0 4px;
        }

        .creditsFilterBar {
          display: flex;
          gap: 8px;
          overflow-x: auto;
          padding-bottom: 4px;
        }

        .creditsFilterChip {
          padding: 8px 16px;
          border-radius: 999px;
          background: rgba(0, 0, 0, 0.05);
          border: 1px solid rgba(0, 0, 0, 0.08);
          color: #2d0909;
          font-size: 13px;
          font-weight: 600;
          white-space: nowrap;
          cursor: pointer;
          transition: all 0.15s ease;
        }

        .creditsFilterChip:hover {
          color: #000;
          background: rgba(0, 0, 0, 0.08);
        }

        .creditsFilterChip.active {
          color: #000;
          background: rgba(246, 230, 230, 0.18);
          border-color: rgba(246, 230, 230, 0.45);
        }

        .creditsSection {
          display: flex;
          flex-direction: column;
          gap: 18px;
        }

        .catalogGrid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
          gap: 16px;
        }

        .catalogCard {
          display: flex;
          flex-direction: column;
          border-radius: 16px;
          background: rgba(18, 18, 24, 0.7);
          border: 1px solid rgba(0, 0, 0, 0.07);
          overflow: hidden;
          transition: transform 0.18s ease, border-color 0.18s ease;
        }

        .catalogCard:hover {
          transform: translateY(-2px);
          border-color: rgba(0, 0, 0, 0.14);
        }

        .catalogCardEquipped {
          border-color: rgba(246, 230, 230, 0.4);
          box-shadow: 0 0 20px -8px rgba(246, 230, 230, 0.3);
        }

        .catalogPreviewWrap {
          position: relative;
          height: 120px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: radial-gradient(circle at center, rgba(0, 0, 0, 0.04), transparent 70%);
          border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .catalogPreviewEmoji {
          font-size: 42px;
        }

        .catalogPreviewGraphic {
          width: 56px;
          height: 56px;
          border-radius: 14px;
          border: 2px solid;
          display: grid;
          place-items: center;
        }

        .equippedPill {
          position: absolute;
          top: 10px;
          right: 10px;
          padding: 4px 10px;
          border-radius: 999px;
          font-size: 11px;
          font-weight: 750;
          text-transform: uppercase;
          letter-spacing: 0.06em;
          background: rgba(246, 230, 230, 0.2);
          border: 1px solid rgba(246, 230, 230, 0.45);
          color: #fdf6f6;
        }

        .catalogInfo {
          padding: 16px 18px 12px;
          flex: 1;
        }

        .catalogTitleRow {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 10px;
          margin-bottom: 6px;
        }

        .catalogItemName {
          font-size: 15px;
          color: #000;
        }

        .catalogItemPrice {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          font-weight: 700;
          color: #f6e6e6;
        }

        .catalogItemDesc {
          font-size: 12.5px;
          line-height: 1.45;
          color: #2d0909;
          margin: 0;
        }

        .catalogFooter {
          padding: 12px 18px 16px;
        }

        .catalogBtn {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 7px;
          padding: 9px 14px;
          border-radius: 10px;
          font-size: 13.5px;
          font-weight: 700;
          cursor: pointer;
          transition: all 0.15s ease;
        }

        .catalogBtnBuy {
          background: rgba(246, 230, 230, 0.14);
          border: 1px solid rgba(246, 230, 230, 0.35);
          color: #fdf6f6;
        }

        .catalogBtnBuy:hover {
          background: rgba(246, 230, 230, 0.24);
        }

        .catalogBtnDisabled {
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.08);
          color: #210c0c;
          cursor: not-allowed;
        }

        .catalogBtnTopUp {
          background: rgba(246, 230, 230, 0.08);
          border: 1px solid rgba(246, 230, 230, 0.25);
          color: #fdf6f6;
          cursor: pointer;
        }

        .catalogBtnTopUp:hover {
          background: rgba(246, 230, 230, 0.18);
          border-color: rgba(246, 230, 230, 0.45);
        }

        .catalogBtnEquip {
          background: rgba(0, 0, 0, 0.08);
          border: 1px solid rgba(0, 0, 0, 0.16);
          color: #000;
        }

        .catalogBtnEquip:hover {
          background: rgba(0, 0, 0, 0.14);
        }

        .catalogBtnEquipped {
          background: rgba(246, 230, 230, 0.18);
          border: 1px solid rgba(246, 230, 230, 0.45);
          color: #fdf6f6;
        }

        /* Earn Grid */
        .earnGrid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
          gap: 16px;
        }

        .earnCard {
          display: flex;
          flex-direction: column;
          gap: 14px;
          padding: 20px;
          border-radius: 16px;
          background: rgba(18, 18, 24, 0.7);
          border: 1px solid rgba(0, 0, 0, 0.07);
        }

        .earnCardHeader {
          display: flex;
          align-items: flex-start;
          gap: 14px;
        }

        .earnIcon {
          font-size: 26px;
          line-height: 1;
        }

        .earnCardHeader strong {
          display: block;
          font-size: 15px;
          color: #000;
          margin-bottom: 3px;
        }

        .earnCardHeader p {
          margin: 0;
          font-size: 13px;
          color: #2d0909;
          line-height: 1.4;
        }

        .earnProgressWrap {
          display: flex;
          flex-direction: column;
          gap: 6px;
        }

        .earnProgressBar {
          height: 6px;
          border-radius: 999px;
          background: rgba(0, 0, 0, 0.08);
          overflow: hidden;
        }

        .earnProgressFill {
          height: 100%;
          border-radius: 999px;
          background: #f6e6e6;
          transition: width 0.3s ease;
        }

        .earnProgressWrap small {
          font-size: 11.5px;
          color: #2d0909;
        }

        .earnCardFooter {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: auto;
          padding-top: 10px;
          border-top: 1px solid rgba(0, 0, 0, 0.05);
        }

        .earnReward {
          font-size: 14px;
          font-weight: 750;
          color: #f6e6e6;
        }

        .earnBtn {
          padding: 8px 16px;
          border-radius: 10px;
          background: #f6e6e6;
          border: 1px solid #fdf6f6;
          color: #111;
          font-size: 13px;
          font-weight: 700;
          cursor: pointer;
          transition: all 0.15s ease;
        }

        .earnBtn:hover:not(:disabled) {
          background: #faefef;
        }

        .earnBtn:disabled {
          background: rgba(0, 0, 0, 0.06);
          border-color: rgba(0, 0, 0, 0.08);
          color: #210c0c;
          cursor: not-allowed;
        }

        .earnBtnGhost {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          border-radius: 10px;
          background: rgba(0, 0, 0, 0.06);
          border: 1px solid rgba(0, 0, 0, 0.12);
          color: #000;
          font-size: 13px;
          font-weight: 700;
          text-decoration: none;
          transition: all 0.15s ease;
        }

        .earnBtnGhost:hover {
          background: rgba(0, 0, 0, 0.12);
        }

        /* Packs Grid */
        .packsGrid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
          gap: 16px;
        }

        .packCard {
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          padding: 26px 20px;
          border-radius: 18px;
          background: rgba(18, 18, 24, 0.7);
          border: 1px solid rgba(0, 0, 0, 0.07);
        }

        .packCardPopular {
          border-color: rgba(246, 230, 230, 0.4);
          background: linear-gradient(180deg, rgba(246, 230, 230, 0.08), rgba(18, 18, 24, 0.8) 50%);
        }

        .packBadge {
          position: absolute;
          top: -10px;
          padding: 3px 12px;
          border-radius: 999px;
          background: #f6e6e6;
          color: #111;
          font-size: 11px;
          font-weight: 800;
          text-transform: uppercase;
          letter-spacing: 0.06em;
        }

        .packCoins {
          margin-bottom: 12px;
          color: #f6e6e6;
        }

        .packTitle {
          font-size: 17px;
          color: #000;
          margin: 0 0 6px;
        }

        .packAmount {
          font-size: 22px;
          font-weight: 850;
          color: #fdf6f6;
          margin-bottom: 4px;
        }

        .packPrice {
          font-size: 15px;
          font-weight: 600;
          color: #2d0909;
          margin-bottom: 18px;
        }

        .packBtn {
          width: 100%;
          padding: 10px;
          border-radius: 12px;
          background: #f6e6e6;
          color: #111;
          font-size: 13.5px;
          font-weight: 750;
          text-decoration: none;
          display: inline-block;
          transition: all 0.15s ease;
        }

        .packBtn:hover {
          background: #faefef;
          transform: translateY(-1px);
        }

        /* Transactions */
        .txList {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .txRow {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 14px 18px;
          border-radius: 12px;
          background: rgba(18, 18, 24, 0.5);
          border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .txInfo strong {
          display: block;
          font-size: 14px;
          color: #000;
        }

        .txInfo small {
          font-size: 12px;
          color: #210c0c;
        }

        .txAmountWrap {
          text-align: right;
        }

        .txAmount {
          display: block;
          font-size: 14.5px;
          font-weight: 750;
        }

        .txPositive {
          color: #de8383;
        }

        .txNegative {
          color: #f8d6d6;
        }

        .txBalance {
          font-size: 11.5px;
          color: #210c0c;
        }
      `}</style>
    </div>
  );
}
