'use client';

import React, { useState, useMemo, useRef } from 'react';
import Link from 'next/link';
import {
  Coins,
  Package,
  Sparkles,
  Check,
  ChevronLeft,
  Search,
  ArrowRight,
  Gift,
  Crown,
  AlertCircle,
  PackageCheck,
  PackagePlus,
} from 'lucide-react';
import { CRATES_CATALOG, CrateTier, CrateReward, RARITY_CONFIG } from '@/lib/crates-catalog';
import {
  openCrateAction,
  openInventoryCrateAction,
  buyCrateToInventoryAction,
  OpenCrateResult,
  UserCratesInventoryState,
} from '@/lib/crates-actions';
import { equipCosmetic, UserCreditsState } from '@/lib/credits-actions';
import { Profile, SITE_NAME, DISCORD_INVITE_URL } from '@/lib/constants';
import SiteHeader from '@/components/SiteHeader';
import CrateVisual from '@/components/CrateVisual';
import DailyRewardsCard from '@/components/DailyRewardsCard';
import EarnCreditsSection from '@/components/EarnCreditsSection';
import CsCrateSpinner from '@/components/CsCrateSpinner';

interface CratesClientProps {
  user: { id: string } | null;
  username: string;
  profile: Profile | null;
  initialCreditsState: UserCreditsState | null;
  initialInventory?: UserCratesInventoryState | null;
}

export default function CratesClient({
  user,
  username,
  profile: initialProfile,
  initialCreditsState,
  initialInventory,
}: CratesClientProps) {
  const [profile, setProfile] = useState(initialProfile);
  const [creditsState, setCreditsState] = useState(initialCreditsState);
  const [credits, setCredits] = useState<number>(
    initialCreditsState?.credits ?? initialProfile?.credits ?? 0
  );

  // View state: 'grid' (Image 2 style) or 'inspect' (Image 3 style)
  const [activeTier, setActiveTier] = useState<CrateTier>(CRATES_CATALOG[2]); // Default to Gold
  const [viewMode, setViewMode] = useState<'grid' | 'inspect'>('inspect');
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<'default' | 'price-asc' | 'price-desc' | 'jackpot'>('default');
  const [selectedFilter, setSelectedFilter] = useState<string>('all');

  // Inventory state
  const [inventory, setInventory] = useState<UserCratesInventoryState | null>(
    initialInventory ?? null
  );
  const [isBuyingToInventory, setIsBuyingToInventory] = useState(false);
  const [inventoryNotice, setInventoryNotice] = useState<string | null>(null);
  const [buyQuantity, setBuyQuantity] = useState<number>(1);

  // Unboxing sequence state
  const [isOpening, setIsOpening] = useState(false);
  const [openingPhase, setOpeningPhase] = useState<'idle' | 'rolling' | 'revealed'>('idle');
  const [showCsSpinner, setShowCsSpinner] = useState(false);
  const [result, setResult] = useState<OpenCrateResult | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [equippedSuccess, setEquippedSuccess] = useState(false);

  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const inspectSectionRef = useRef<HTMLDivElement | null>(null);
  const freeCreditsSectionRef = useRef<HTMLDivElement | null>(null);

  // Filter & sort catalog for the grid view
  const filteredCrates = useMemo(() => {
    let list = [...CRATES_CATALOG];

    if (selectedFilter !== 'all') {
      list = list.filter((c) => c.id === selectedFilter);
    }

    if (searchTerm.trim()) {
      const q = searchTerm.toLowerCase();
      list = list.filter(
        (c) =>
          c.name.toLowerCase().includes(q) ||
          c.tagline.toLowerCase().includes(q) ||
          c.lootTable.some((entry) => entry.reward.name.toLowerCase().includes(q))
      );
    }

    if (sortBy === 'price-asc') {
      list.sort((a, b) => a.price - b.price);
    } else if (sortBy === 'price-desc') {
      list.sort((a, b) => b.price - a.price);
    } else if (sortBy === 'jackpot') {
      list.sort((a, b) => {
        const maxA = Math.max(...a.lootTable.map((l) => l.reward.amount || 0));
        const maxB = Math.max(...b.lootTable.map((l) => l.reward.amount || 0));
        return maxB - maxA;
      });
    }

    return list;
  }, [selectedFilter, searchTerm, sortBy]);

  const handleSelectCrate = (crate: CrateTier) => {
    setActiveTier(crate);
    setViewMode('inspect');
    setResult(null);
    setOpeningPhase('idle');
    setErrorMsg(null);
    setEquippedSuccess(false);

    if (inspectSectionRef.current) {
      inspectSectionRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const maxAffordable = Math.max(1, Math.min(50, Math.floor(credits / (activeTier.price || 1))));

  const handleOpenInventoryCrate = async () => {
    if (!user) {
      setErrorMsg('You must be logged in to open mystery crates.');
      return;
    }

    if (isOpening) return;

    const owned = inventory?.counts[activeTier.id] || 0;
    if (owned <= 0) {
      setErrorMsg(`You do not have any ${activeTier.name} stored in your inventory.`);
      return;
    }

    setIsOpening(true);
    setErrorMsg(null);
    setInventoryNotice(null);
    setOpeningPhase('idle');
    setEquippedSuccess(false);

    try {
      const res = await openInventoryCrateAction(activeTier.id);
      setIsOpening(false);

      if (!res.success) {
        setErrorMsg(res.error || 'Failed to open crate from inventory.');
        setOpeningPhase('idle');
        return;
      }

      setResult(res);
      setOpeningPhase('idle');
      setShowCsSpinner(true);
      if (res.newBalance !== undefined) {
        setCredits(res.newBalance);
        setProfile((prev) => (prev ? { ...prev, credits: res.newBalance } : null));
        setCreditsState((prev) => (prev ? { ...prev, credits: res.newBalance! } : null));
      }
      setInventory((prev) => {
        if (!prev) return null;
        const nextCounts = { ...prev.counts };
        nextCounts[activeTier.id] = Math.max(0, (nextCounts[activeTier.id] || 1) - 1);
        return {
          totalUnopened: Math.max(0, prev.totalUnopened - 1),
          counts: nextCounts,
          unopened: prev.unopened.filter((u, idx) => idx !== 0),
        };
      });
    } catch {
      setIsOpening(false);
      setErrorMsg('Network error while opening crate from inventory.');
      setOpeningPhase('idle');
    }
  };

  const handleBuyCrateToInventory = async (overrideQty?: number) => {
    if (!user) {
      setErrorMsg('You must be logged in to purchase crates.');
      return;
    }

    if (isOpening || isBuyingToInventory) return;

    const qtyToBuy = Math.max(1, Math.min(50, overrideQty ?? buyQuantity));
    const totalCost = activeTier.price * qtyToBuy;

    if (credits < totalCost) {
      setErrorMsg(`Insufficient credits. You need ${(totalCost - credits).toLocaleString()} more.`);
      return;
    }

    setIsBuyingToInventory(true);
    setErrorMsg(null);
    setInventoryNotice(null);

    try {
      const res = await buyCrateToInventoryAction(activeTier.id, qtyToBuy);
      setIsBuyingToInventory(false);

      if (!res.success) {
        setErrorMsg(res.error || 'Failed to purchase crate to inventory.');
      } else {
        const qtyBought = res.quantityBought || qtyToBuy;
        if (res.newBalance !== undefined) {
          setCredits(res.newBalance);
          setProfile((prev) => (prev ? { ...prev, credits: res.newBalance } : null));
          setCreditsState((prev) => (prev ? { ...prev, credits: res.newBalance! } : null));
        }
        setInventory((prev) => {
          const base = prev || { totalUnopened: 0, counts: {}, unopened: [] };
          const nextCounts = res.counts || { ...base.counts };
          if (!res.counts) {
            nextCounts[activeTier.id] = (nextCounts[activeTier.id] || 0) + qtyBought;
          }
          const newRows = Array.from({ length: qtyBought }).map((_, i) => ({
            id: res.inventoryId ? `${res.inventoryId}-${i}` : 'inv-' + Date.now() + '-' + i,
            crateId: activeTier.id,
            source: 'purchase',
            createdAt: new Date().toISOString(),
          }));
          return {
            totalUnopened: base.totalUnopened + qtyBought,
            counts: nextCounts,
            unopened: [...newRows, ...base.unopened],
          };
        });
        setInventoryNotice(`Saved ${qtyBought}x ${activeTier.name} to your inventory. Open them whenever you want!`);
      }
    } catch {
      setIsBuyingToInventory(false);
      setErrorMsg('Network error purchasing crate.');
    }
  };

  const handleOpenCrate = async () => {
    if (!user) {
      setErrorMsg('You must be logged in to open mystery crates.');
      return;
    }

    if (isOpening) return;

    if (credits < activeTier.price) {
      setErrorMsg(`Insufficient credits. You need ${(activeTier.price - credits).toLocaleString()} more.`);
      return;
    }

    setIsOpening(true);
    setErrorMsg(null);
    setOpeningPhase('idle');
    setEquippedSuccess(false);

    try {
      const res = await openCrateAction(activeTier.id);
      setIsOpening(false);

      if (!res.success) {
        setErrorMsg(res.error || 'Failed to open crate.');
        setOpeningPhase('idle');
        return;
      }

      setResult(res);
      setOpeningPhase('idle');
      setShowCsSpinner(true);
      if (res.newBalance !== undefined) {
        setCredits(res.newBalance);
        setProfile((prev) => (prev ? { ...prev, credits: res.newBalance } : null));
        setCreditsState((prev) => (prev ? { ...prev, credits: res.newBalance! } : null));
      }
    } catch {
      setIsOpening(false);
      setErrorMsg('Network error while opening crate.');
      setOpeningPhase('idle');
    }
  };

  const handleEquipWonItem = async (reward: CrateReward) => {
    if (!reward.itemId) return;
    if (reward.type === 'avatar_frame' || reward.type === 'avatar_decoration' || reward.type === 'card_frame') {
      try {
        const res = await equipCosmetic(reward.type, reward.itemId);
        if (res.success) {
          setEquippedSuccess(true);
        }
      } catch (err) {
        console.error('Failed to equip cosmetic:', err);
      }
    }
  };

  // Particle confetti on drops
  const triggerConfetti = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const particles: {
      x: number;
      y: number;
      vx: number;
      vy: number;
      color: string;
      size: number;
      alpha: number;
    }[] = [];

    const colors = ['#ffffff', '#f5e1e1', '#f7d9d9', '#f8e3e3', '#de8383', '#000000'];

    for (let i = 0; i < 90; i++) {
      particles.push({
        x: canvas.width / 2 + (Math.random() - 0.5) * 120,
        y: canvas.height * 0.45,
        vx: (Math.random() - 0.5) * 16,
        vy: (Math.random() - 0.8) * 18,
        color: colors[Math.floor(Math.random() * colors.length)],
        size: Math.random() * 7 + 4,
        alpha: 1,
      });
    }

    const render = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      let alive = false;

      particles.forEach((p) => {
        p.x += p.vx;
        p.y += p.vy;
        p.vy += 0.45;
        p.alpha -= 0.014;

        if (p.alpha > 0) {
          alive = true;
          ctx.save();
          ctx.globalAlpha = Math.max(0, p.alpha);
          ctx.fillStyle = p.color;
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
          ctx.fill();
          ctx.restore();
        }
      });

      if (alive) {
        requestAnimationFrame(render);
      } else {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
    };

    requestAnimationFrame(render);
  };

  // Compute probability for loot items
  const totalWeight = useMemo(() => {
    return activeTier.lootTable.reduce((sum, item) => sum + item.weight, 0);
  }, [activeTier]);

  // Rare special items (top tier items)
  const specialItems = useMemo(() => {
    return activeTier.lootTable
      .filter((l) => l.reward.rarity === 'legendary' || l.reward.rarity === 'mythic' || l.reward.rarity === 'epic')
      .map((l) => l.reward);
  }, [activeTier]);

  const scrollToFreeCredits = () => {
    if (freeCreditsSectionRef.current) {
      freeCreditsSectionRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  return (
    <main className="landingShell">
      {/* Canvas for win celebration */}
      <canvas
        ref={canvasRef}
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none',
          zIndex: 99999,
        }}
      />

      {/* CS2-Style Carousel Spinner */}
      <CsCrateSpinner
        isOpen={showCsSpinner && Boolean(result?.reward)}
        crate={activeTier}
        winningReward={result?.reward || null}
        duplicateRefund={result?.duplicateRefund}
        onFinish={() => {
          triggerConfetti();
        }}
        onClose={() => {
          setShowCsSpinner(false);
          setResult(null);
          setOpeningPhase('idle');
        }}
        onEquip={handleEquipWonItem}
        equippedSuccess={equippedSuccess}
        canOpenAnother={
          (inventory?.counts[activeTier.id] || 0) > 0 || credits >= activeTier.price
        }
        onOpenAnother={() => {
          setShowCsSpinner(false);
          setResult(null);
          setOpeningPhase('idle');
          if ((inventory?.counts[activeTier.id] || 0) > 0) {
            void handleOpenInventoryCrate();
          } else {
            void handleOpenCrate();
          }
        }}
        remainingCredits={credits}
      />

      {/* 1. Shared Responsive Site Header */}
      <SiteHeader
        user={user}
        username={username}
        activePath="/crates"
        showThemeToggle
        extraActions={
          user ? (
            <button
              type="button"
              onClick={scrollToFreeCredits}
              className="landingCreditsChip"
              title="Your Sinss Credits · Click to earn free credits"
            >
              <Coins size={13} className="coinIcon" />
              <span className="creditsVal">{credits.toLocaleString()}</span>
              <span className="creditsAdd">+ Free</span>
            </button>
          ) : null
        }
      />

      {/* 2. Page Content in landingContainer */}
      <div className="landingContainer" style={{ paddingTop: 40, paddingBottom: 80 }}>
        {/* Hero Header with Site-Wide Typography */}
        <header className="cratesPageHero">
          <div className="landingEyebrow">Mystery Vault</div>
          <h1 className="cratesTitle">Mystery Crates</h1>
          <p className="landingLead">
            Spend Sinss Credits to unbox tiered mystery cases. Unlock rare avatar frames, Discord
            decorations, cosmetic borders, and credit jackpots.
          </p>
        </header>

        {/* Crate Inventory Bar */}
        {profile && (
          <div className="cratesInventoryBar">
            <div className="inventoryBarLeft">
              <div className="inventoryBarIcon">
                <PackageCheck size={18} />
              </div>
              <div className="inventoryBarInfo">
                <span className="inventoryBarTitle">
                  Crate Inventory · <strong>{inventory?.totalUnopened || 0} Unopened</strong>
                </span>
                <span className="inventoryBarSub">
                  Crates saved from drops or purchases. Open them now or save them for later.
                </span>
              </div>
            </div>
            <div className="inventoryPills">
              {CRATES_CATALOG.map((c) => {
                const count = inventory?.counts[c.id] || 0;
                return (
                  <button
                    key={c.id}
                    type="button"
                    className={`inventoryPill ${count > 0 ? 'hasCrates' : 'empty'} ${
                      activeTier.id === c.id && viewMode === 'inspect' ? 'active' : ''
                    }`}
                    onClick={() => handleSelectCrate(c)}
                    title={`${c.name}: ${count} stored in inventory`}
                  >
                    <span className="invPillDot" style={{ background: c.color }} />
                    <span className="invPillName">{c.name.replace(' Crate', '')}</span>
                    <span className="invPillCount">{count}</span>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {inventoryNotice && (
          <div className="inventoryNoticeBanner">
            <PackageCheck size={15} />
            <span>{inventoryNotice}</span>
          </div>
        )}

        {/* Filter Controls Bar (Search, Order, Tabs) */}
        <div className="cratesToolbar">
          <div className="cratesSearchRow">
            <div className="cratesSearchBox">
              <Search size={15} className="cratesSearchIcon" />
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Search crates, items, or rarities..."
                className="cratesSearchInput"
              />
            </div>

            <div className="cratesSortWrap">
              <span className="cratesSortLabel">Order by</span>
              <select
                value={sortBy}
                onChange={(e) =>
                  setSortBy(e.target.value as 'default' | 'price-asc' | 'price-desc' | 'jackpot')
                }
                className="cratesSortSelect"
              >
                <option value="default">Default</option>
                <option value="price-asc">Price: Low to High</option>
                <option value="price-desc">Price: High to Low</option>
                <option value="jackpot">Highest Jackpot</option>
              </select>
            </div>
          </div>

          {/* Capsule Filter Group */}
          <div className="leaderboardFilterGroup cratesTabs">
            <button
              type="button"
              className={`leaderboardFilterBtn ${
                selectedFilter === 'all' && viewMode === 'grid' ? 'active' : ''
              }`}
              onClick={() => {
                setSelectedFilter('all');
                setViewMode('grid');
              }}
            >
              All Crates
            </button>
            {CRATES_CATALOG.map((crate) => (
              <button
                type="button"
                key={crate.id}
                className={`leaderboardFilterBtn ${
                  activeTier.id === crate.id && viewMode === 'inspect' ? 'active' : ''
                }`}
                onClick={() => handleSelectCrate(crate)}
              >
                {crate.name}
              </button>
            ))}
          </div>
        </div>

        {/* MODE A: Crates Catalog Grid matching Image 2 in sinss.lol Glassmorphism */}
        {viewMode === 'grid' && (
          <section className="cratesCatalogSection">
            <div className="cratesCardsGrid">
              {filteredCrates.map((crate) => {
                const ribbonText =
                  crate.id === 'crate-obsidian'
                    ? 'NEW'
                    : crate.id === 'crate-gold'
                    ? 'HOT'
                    : crate.id === 'crate-silver'
                    ? 'POPULAR'
                    : 'STARTER';

                const ownedCount = inventory?.counts[crate.id] || 0;

                return (
                  <article
                    key={crate.id}
                    className="crateCard"
                    onClick={() => handleSelectCrate(crate)}
                  >
                    {/* Ribbon badge in top left */}
                    <div
                      className={`crateRibbon crateRibbon-${ribbonText.toLowerCase()}`}
                    >
                      {ribbonText}
                    </div>

                    {ownedCount > 0 && (
                      <div className="crateInvTag">
                        <PackageCheck size={11} />
                        <span>{ownedCount} stored</span>
                      </div>
                    )}

                    <div className="crateVisualStage">
                      <CrateVisual tierId={crate.id} size={175} />
                    </div>

                    <div className="crateMeta">
                      <h3>{crate.name}</h3>
                      <div className="cratePrice">
                        <Coins size={14} className="cratePriceCoin" />
                        <span>{crate.price.toLocaleString()} Credits</span>
                      </div>
                      <p className="crateTagline">{crate.tagline}</p>
                    </div>

                    <button type="button" className="crateInspectBtn">
                      <span>Inspect Case</span>
                      <ArrowRight size={14} />
                    </button>
                  </article>
                );
              })}
            </div>
          </section>
        )}

        {/* MODE B: Crate Inspection & Unboxing View matching Image 3 in sinss.lol Glassmorphism */}
        {viewMode === 'inspect' && (
          <section ref={inspectSectionRef} className="cratesInspectSection">
            {/* Top Showcase Hero */}
            <div className="inspectHeroCard">
              <div className="inspectLeft">
                <button
                  type="button"
                  className="inspectBackBtn"
                  onClick={() => setViewMode('grid')}
                >
                  <ChevronLeft size={16} />
                  <span>Browse all cases</span>
                </button>

                <div className="inspectVisualWrap">
                  <CrateVisual tierId={activeTier.id} size={260} glow />
                </div>
              </div>

              <div className="inspectRight">
                <div className="inspectHeaderRow">
                  <h2>{activeTier.name}</h2>
                  <div className="inspectChipRow">
                    {(inventory?.counts[activeTier.id] || 0) > 0 && (
                      <span className="inspectInventoryChip">
                        <PackageCheck size={12} />
                        {inventory?.counts[activeTier.id]} in Inventory
                      </span>
                    )}
                    <span className="inspectTierChip">
                      Tier {activeTier.id.replace('crate-', '').toUpperCase()}
                    </span>
                  </div>
                </div>

                <p className="inspectDesc">{activeTier.tagline}</p>

                {errorMsg && (
                  <div className="inspectErrorBanner">
                    <AlertCircle size={15} />
                    <span>{errorMsg}</span>
                  </div>
                )}

                {/* Revealed Win Item Card */}
                {openingPhase === 'revealed' && result?.reward && (
                  <div className="wonCardBox">
                    <div className="wonCardHeader">
                      <span
                        className="wonRarityPill"
                        style={{
                          background: RARITY_CONFIG[result.reward.rarity].bg,
                          color: RARITY_CONFIG[result.reward.rarity].color,
                          borderColor: RARITY_CONFIG[result.reward.rarity].border,
                        }}
                      >
                        {RARITY_CONFIG[result.reward.rarity].label}
                      </span>
                      {result.duplicateRefund && (
                        <span className="duplicateRefundBadge">
                          <Coins size={12} />
                          <span>Duplicate: +{result.duplicateRefund} Credits</span>
                        </span>
                      )}
                    </div>

                    <div className="wonCardBody">
                      <div className="wonVisual">
                        {result.reward.previewUrl ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img src={result.reward.previewUrl} alt="" className="wonImg" />
                        ) : (
                          <span className="wonIcon">{result.reward.icon || '🎁'}</span>
                        )}
                      </div>
                      <div className="wonDetails">
                        <h3>{result.reward.name}</h3>
                        <p>{result.reward.description}</p>
                      </div>
                    </div>

                    <div className="wonActions">
                      {result.reward.itemId &&
                        !result.duplicateRefund &&
                        ['avatar_frame', 'avatar_decoration', 'card_frame'].includes(
                          result.reward.type
                        ) && (
                          <button
                            type="button"
                            className="landingClaimButton wonEquipBtn"
                            onClick={() => handleEquipWonItem(result.reward)}
                            disabled={equippedSuccess}
                          >
                            {equippedSuccess ? <Check size={14} /> : <Sparkles size={14} />}
                            <span>
                              {equippedSuccess ? 'Equipped on profile' : 'Equip to profile'}
                            </span>
                          </button>
                        )}
                      {(inventory?.counts[activeTier.id] || 0) > 0 ? (
                        <button
                          type="button"
                          className="landingPrimaryBtn openFromInventoryBtn"
                          onClick={handleOpenInventoryCrate}
                          disabled={isOpening}
                        >
                          <PackageCheck size={15} />
                          <span>
                            Open another from inventory ({inventory?.counts[activeTier.id]} left)
                          </span>
                        </button>
                      ) : (
                        <button
                          type="button"
                          className="landingPrimaryBtn"
                          onClick={handleOpenCrate}
                          disabled={isOpening}
                        >
                          <Package size={15} />
                          <span>Open another ({activeTier.price} Credits)</span>
                        </button>
                      )}
                    </div>
                  </div>
                )}

                {/* Standard Action Trigger */}
                {openingPhase === 'idle' && (
                  <div className="inspectActionBlock">
                    <div className="inspectStatsStrip">
                      <div className="inspectStat">
                        <span className="statSub">Price</span>
                        <span className="statVal priceVal">
                          <Coins size={14} className="coinIcon" />
                          {activeTier.price.toLocaleString()} Credits
                        </span>
                      </div>
                      <div className="inspectStat">
                        <span className="statSub">Total Drops</span>
                        <span className="statVal">{activeTier.lootTable.length} Items</span>
                      </div>
                      <div className="inspectStat">
                        <span className="statSub">Recycle Value</span>
                        <span className="statVal">70% on Dupes</span>
                      </div>
                    </div>

                    <div className="inspectActionBtns">
                      <div className="crateBuyQtyBar">
                        <span className="qtyBarLabel">Buy Quantity</span>
                        <div className="qtyPresetGroup">
                          {[1, 5, 10].map((q) => (
                            <button
                              key={q}
                              type="button"
                              className={`qtyPresetBtn ${buyQuantity === q ? 'active' : ''}`}
                              onClick={() => setBuyQuantity(q)}
                              disabled={isOpening || isBuyingToInventory}
                            >
                              {q}x
                            </button>
                          ))}
                          {maxAffordable > 1 && (
                            <button
                              type="button"
                              className={`qtyPresetBtn ${buyQuantity === maxAffordable && buyQuantity !== 1 && buyQuantity !== 5 && buyQuantity !== 10 ? 'active' : ''}`}
                              onClick={() => setBuyQuantity(maxAffordable)}
                              disabled={isOpening || isBuyingToInventory}
                              title={`Buy max affordable (${maxAffordable}x)`}
                            >
                              Max ({maxAffordable}x)
                            </button>
                          )}
                        </div>
                      </div>

                      {(inventory?.counts[activeTier.id] || 0) > 0 ? (
                        <div className="inspectMultiAction">
                          <button
                            type="button"
                            className="landingPrimaryBtn openFromInventoryBtn"
                            onClick={handleOpenInventoryCrate}
                            disabled={isOpening}
                          >
                            <PackageCheck size={16} />
                            <span>
                              {isOpening ? 'Opening...' : `Open from Inventory (${inventory?.counts[activeTier.id]} available)`}
                            </span>
                          </button>
                          <div className="inspectSecondaryRow">
                            <button
                              type="button"
                              className="inspectActionBtnSecondary"
                              onClick={handleOpenCrate}
                              disabled={isOpening || credits < activeTier.price}
                              title={`Spend ${activeTier.price} credits to open immediately`}
                            >
                              <Package size={14} />
                              <span>
                                Open Instantly ({activeTier.price.toLocaleString()}c)
                              </span>
                            </button>
                            <button
                              type="button"
                              className="inspectActionBtnSecondary"
                              onClick={() => handleBuyCrateToInventory()}
                              disabled={
                                isOpening ||
                                isBuyingToInventory ||
                                credits < activeTier.price * buyQuantity
                              }
                              title={`Buy ${buyQuantity}x for ${(activeTier.price * buyQuantity).toLocaleString()} credits and save in inventory`}
                            >
                              <PackagePlus size={14} />
                              <span>
                                {isBuyingToInventory
                                  ? 'Saving...'
                                  : `Buy ${buyQuantity}x (${(activeTier.price * buyQuantity).toLocaleString()}c)`}
                              </span>
                            </button>
                          </div>
                        </div>
                      ) : credits >= activeTier.price ? (
                        <div className="inspectMultiAction">
                          <button
                            type="button"
                            className="landingPrimaryBtn openCratePrimaryBtn"
                            onClick={handleOpenCrate}
                            disabled={isOpening}
                          >
                            <Package size={16} />
                            <span>
                              {isOpening ? 'Opening...' : `Open Instantly (${activeTier.price.toLocaleString()} Credits)`}
                            </span>
                          </button>
                          <button
                            type="button"
                            className="inspectActionBtnSecondary fullWidth"
                            onClick={() => handleBuyCrateToInventory()}
                            disabled={
                              isOpening ||
                              isBuyingToInventory ||
                              credits < activeTier.price * buyQuantity
                            }
                          >
                            <PackagePlus size={14} />
                            <span>
                              {isBuyingToInventory
                                ? 'Saving to Inventory...'
                                : `Buy ${buyQuantity}x to Inventory (${(activeTier.price * buyQuantity).toLocaleString()} Credits)`}
                            </span>
                          </button>
                        </div>
                      ) : (
                        <div className="insufficientCard">
                          <div className="insufficientText">
                            <strong>
                              Need {(activeTier.price - credits).toLocaleString()} more credits
                            </strong>
                            <p>Claim daily rewards and free quests below to open this crate.</p>
                          </div>
                          <button
                            type="button"
                            className="landingPrimaryBtn"
                            onClick={scrollToFreeCredits}
                          >
                            <Gift size={14} />
                            <span>Claim free credits</span>
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Case Contents Grid */}
            <div className="caseContentsSection">
              <div className="contentsHeaderRow">
                <h3>{activeTier.name} contents</h3>
                <span className="contentsCount">
                  {activeTier.lootTable.length} potential drops
                </span>
              </div>

              <div className="contentsGrid">
                {/* Special Rare Items Card matching Image 3 leftmost gold card */}
                {specialItems.length > 0 && (
                  <div className="rareSpecialCard">
                    <div className="rareSpecialHead">
                      <div className="laurelWreath">
                        <Crown size={24} className="crownIcon" />
                      </div>
                      <h4>Rare Special Items</h4>
                    </div>
                    <div className="rareSpecialList">
                      {specialItems.map((item) => (
                        <div key={item.id} className="rareSpecialRow">
                          <span className="specialStar">★</span>
                          <span>{item.name}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Individual Case Content Item Tiles */}
                {activeTier.lootTable.map((entry) => {
                  const item = entry.reward;
                  const rarity = RARITY_CONFIG[item.rarity];
                  const dropChance = ((entry.weight / totalWeight) * 100).toFixed(1);

                  return (
                    <div
                      key={item.id}
                      className="contentItemCard"
                      style={{ borderBottom: `2.5px solid ${rarity.color}` }}
                    >
                      <div className="contentItemVisual">
                        {item.previewUrl ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img src={item.previewUrl} alt={item.name} className="contentItemImg" />
                        ) : (
                          <span className="contentItemIcon">{item.icon || '🎁'}</span>
                        )}
                      </div>

                      <div className="contentItemMeta">
                        <h4 style={{ color: rarity.color }}>{item.name}</h4>
                        <span className="contentItemType">
                          {item.type === 'avatar_frame'
                            ? 'Avatar Frame'
                            : item.type === 'avatar_decoration'
                            ? 'Discord Decoration'
                            : item.type === 'card_frame'
                            ? 'Card Border'
                            : item.type === 'cursor_trail'
                            ? 'Cursor Trail'
                            : item.type === 'badge'
                            ? 'Profile Badge'
                            : item.type === 'premium'
                            ? 'Premium Pass'
                            : 'Credit Drop'}
                        </span>

                        <div className="contentItemStats">
                          <div className="contentItemStat">
                            <span className="sub">Drop</span>
                            <span className="val" style={{ color: rarity.color }}>
                              {dropChance}%
                            </span>
                          </div>
                          <div className="contentItemStat">
                            <span className="sub">Dupe</span>
                            <span className="val">
                              +{Math.floor((item.amount || activeTier.price * 0.7) * 0.7)} Cr
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </section>
        )}

        {/* 3. COMPANION SECTION: Free Credits & Daily Rewards */}
        <section ref={freeCreditsSectionRef} className="freeCreditsCompanion">
          <div className="companionHeader">
            <div>
              <div className="landingEyebrow">Free rolls & drops</div>
              <h2 className="companionTitle">Earn Free Sinss Credits</h2>
              <p className="landingLead">
                Claim your daily login streak and complete verified community milestones to unbox
                crates without spending a dime.
              </p>
              <div className="companionNoticeChip">
                <Coins size={13} className="coinIcon" />
                <span>
                  Daily rewards and free quest credits can only be claimed on one account across your linked profiles. You can freely transfer credits between your linked accounts.
                </span>
              </div>
            </div>

            <div className="companionTopUp">
              <span className="topUpHint">Want immediate credits?</span>
              <Link href="/premium" className="landingClaimButton topUpBtn">
                <Coins size={13} />
                <span>Credit Packs ($2.99+)</span>
              </Link>
            </div>
          </div>

          <div className="companionModulesGrid">
            {/* 1. Daily Login Rewards Calendar */}
            <div className="moduleCard">
              <DailyRewardsCard
                profile={profile || undefined}
                onClaimSuccess={(data) => {
                  setCredits(data.newBalance);
                  setProfile((prev) => (prev ? { ...prev, credits: data.newBalance } : null));
                  setCreditsState((prev) =>
                    prev ? { ...prev, credits: data.newBalance } : null
                  );
                }}
              />
            </div>

            {/* 2. Earn Sinss Credits Quests with 'Claimed' status */}
            <div className="moduleCard">
              <EarnCreditsSection
                profile={profile || {}}
                claimedMilestones={creditsState?.claimedMilestones || []}
                onClaimSuccess={(milestoneId, earned, newBalance) => {
                  setCredits(newBalance);
                  setProfile((prev) => (prev ? { ...prev, credits: newBalance } : null));
                  setCreditsState((prev) =>
                    prev
                      ? {
                          ...prev,
                          credits: newBalance,
                          claimedMilestones: [
                            ...(prev.claimedMilestones || []),
                            milestoneId,
                          ],
                        }
                      : null
                  );
                }}
              />
            </div>
          </div>
        </section>
      </div>

      {/* 4. Site-wide Footer */}
      <footer className="landingFooter">
        <div className="landingContainer landingFooterInner">
          <div className="landingFooterLeft">
            <Link href="/" className="landingBrand" aria-label={`${SITE_NAME} home`}>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="/addons/logo.svg" alt="" width={24} height={24} />
              {SITE_NAME}
            </Link>
            <span>A space to be yourself.</span>
          </div>
          <div className="landingFooterRight">
            <Link href="/#features">Features</Link>
            <Link href="/premium">Premium</Link>
            <Link href="/addons">Add-ons</Link>
            <Link href="/leaderboard">Leaderboard</Link>
            <Link href="/crates">Crates</Link>
            <a href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
              Community
            </a>
            <Link href="/privacy">Privacy</Link>
            <Link href="/terms">Terms</Link>
            <span>© {new Date().getFullYear()} {SITE_NAME}</span>
          </div>
        </div>
      </footer>

      {/* Scoped CSS using site variables */}
      <style jsx>{`
        .landingAccountGroup {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .landingCreditsChip {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          background: #11141c;
          border: 1px solid rgba(0, 0, 0, 0.12);
          padding: 6px 12px;
          border-radius: 9999px;
          font-size: 13px;
          font-family: inherit;
          color: #420202;
          cursor: pointer;
          transition: border-color 0.2s, background 0.2s;
        }
        .landingCreditsChip:hover {
          border-color: var(--lp-blue);
          background: #141a26;
        }
        .coinIcon {
          color: #f5e1e1;
        }
        .creditsVal {
          font-weight: 600;
          color: #000;
        }
        .creditsAdd {
          font-size: 11px;
          font-weight: 500;
          color: var(--lp-blue);
          margin-left: 2px;
        }

        /* Hero */
        .cratesPageHero {
          margin-bottom: 24px;
        }
        .cratesTitle {
          font-family: Unbounded, sans-serif !important;
          font-size: 38px !important;
          font-weight: 500 !important;
          letter-spacing: -1.6px !important;
          margin: 16px 0 14px !important;
          color: #000 !important;
        }

        /* Crate Inventory Bar */
        .cratesInventoryBar {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 20px;
          flex-wrap: wrap;
          padding: 18px 24px;
          margin-bottom: 30px;
          background: linear-gradient(145deg, rgba(19, 24, 34, 0.85) 0%, rgba(12, 15, 22, 0.95) 100%);
          border: 1px solid rgba(255, 255, 255, 0.16);
          border-radius: 14px;
          box-shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
        }
        .inventoryBarLeft {
          display: flex;
          align-items: center;
          gap: 14px;
          min-width: 260px;
        }
        .inventoryBarIcon {
          width: 42px;
          height: 42px;
          border-radius: 10px;
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.25);
          color: var(--lp-blue);
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }
        .inventoryBarInfo {
          display: flex;
          flex-direction: column;
          gap: 3px;
        }
        .inventoryBarTitle {
          font-size: 14px;
          color: #420202;
          font-weight: 500;
        }
        .inventoryBarTitle strong {
          color: var(--lp-blue);
          font-weight: 700;
        }
        .inventoryBarSub {
          font-size: 12px;
          color: var(--lp-muted);
        }
        .inventoryPills {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;
        }
        .inventoryPill {
          display: inline-flex;
          align-items: center;
          gap: 7px;
          padding: 6px 12px;
          border-radius: 8px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.08);
          color: #650d0d;
          font-family: inherit;
          font-size: 12.5px;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .inventoryPill.hasCrates {
          background: rgba(255, 255, 255, 0.09);
          border-color: rgba(255, 255, 255, 0.3);
          color: #000000;
        }
        .inventoryPill.hasCrates:hover,
        .inventoryPill.active {
          border-color: var(--lp-blue);
          background: rgba(255, 255, 255, 0.18);
          transform: translateY(-1px);
        }
        .invPillDot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          box-shadow: 0 0 6px currentColor;
        }
        .invPillName {
          font-weight: 500;
        }
        .invPillCount {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          padding: 1px 6px;
          border-radius: 999px;
          background: rgba(0, 0, 0, 0.4);
          font-size: 11px;
          font-weight: 700;
          color: var(--lp-blue);
        }
        .inventoryNoticeBanner {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 12px 18px;
          margin-bottom: 24px;
          border-radius: 10px;
          background: rgba(222, 131, 131, 0.12);
          border: 1px solid rgba(222, 131, 131, 0.35);
          color: #de8383;
          font-size: 13.5px;
          font-weight: 600;
        }
        .crateInvTag {
          position: absolute;
          top: 14px;
          right: 14px;
          z-index: 4;
          display: inline-flex;
          align-items: center;
          gap: 5px;
          padding: 3px 8px;
          border-radius: 6px;
          background: rgba(222, 131, 131, 0.15);
          border: 1px solid rgba(222, 131, 131, 0.4);
          color: #de8383;
          font-size: 11px;
          font-weight: 700;
          letter-spacing: 0.02em;
        }
        .inspectChipRow {
          display: flex;
          align-items: center;
          gap: 8px;
        }
        .inspectInventoryChip {
          display: inline-flex;
          align-items: center;
          gap: 5px;
          font-size: 10.5px;
          font-weight: 700;
          padding: 3px 9px;
          border-radius: 5px;
          background: rgba(222, 131, 131, 0.14);
          border: 1px solid rgba(222, 131, 131, 0.38);
          color: #de8383;
          letter-spacing: 0.03em;
        }
        .inspectMultiAction {
          display: flex;
          flex-direction: column;
          gap: 10px;
          width: 100%;
        }
        .openFromInventoryBtn {
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          gap: 8px !important;
          padding: 12px 24px !important;
          font-size: 14px !important;
          font-weight: 700 !important;
          background: linear-gradient(135deg, #f8e3e3 0%, #ebbdbd 100%) !important;
          border-color: #fae5e5 !important;
          color: #000000 !important;
        }
        .openFromInventoryBtn:hover {
          filter: brightness(1.1);
          transform: translateY(-1px);
        }
        .inspectSecondaryRow {
          display: flex;
          gap: 8px;
          width: 100%;
        }
        .inspectActionBtnSecondary {
          flex: 1;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 7px;
          padding: 10px 14px;
          border-radius: 9px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.12);
          color: #390505;
          font-family: inherit;
          font-size: 13px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .inspectActionBtnSecondary:hover:not(:disabled) {
          background: rgba(0, 0, 0, 0.09);
          border-color: rgba(0, 0, 0, 0.25);
          color: #000000;
        }
        .inspectActionBtnSecondary:disabled {
          opacity: 0.45;
          cursor: not-allowed;
        }
        .inspectActionBtnSecondary.fullWidth {
          width: 100%;
        }
        .crateBuyQtyBar {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 8px 14px;
          border-radius: 9px;
          background: rgba(0, 0, 0, 0.03);
          border: 1px solid rgba(0, 0, 0, 0.08);
          margin-bottom: 2px;
        }
        .qtyBarLabel {
          font-size: 11px;
          font-weight: 700;
          color: #551212;
          text-transform: uppercase;
          letter-spacing: 0.05em;
        }
        .qtyPresetGroup {
          display: flex;
          align-items: center;
          gap: 6px;
        }
        .qtyPresetBtn {
          padding: 3px 9px;
          border-radius: 6px;
          border: 1px solid rgba(0, 0, 0, 0.1);
          background: rgba(0, 0, 0, 0.04);
          color: #7e0b0b;
          font-family: inherit;
          font-size: 11.5px;
          font-weight: 700;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .qtyPresetBtn:hover:not(:disabled) {
          border-color: rgba(0, 0, 0, 0.25);
          color: #000000;
        }
        .qtyPresetBtn.active {
          border-color: var(--lp-blue, #f5caca);
          background: rgba(245, 202, 202, 0.15);
          color: var(--lp-blue, #f5caca);
        }
        .qtyPresetBtn:disabled {
          opacity: 0.4;
          cursor: not-allowed;
        }

        /* Toolbar */
        .cratesToolbar {
          display: flex;
          flex-direction: column;
          gap: 16px;
          margin-bottom: 32px;
        }
        .cratesSearchRow {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 16px;
          flex-wrap: wrap;
        }
        @media (max-width: 600px) {
          .cratesSearchRow {
            flex-direction: column;
            align-items: stretch;
            gap: 10px;
          }
          .cratesSearchBox {
            max-width: 100% !important;
          }
          .cratesSortWrap {
            justify-content: space-between;
            width: 100%;
          }
          .cratesSortSelect {
            flex: 1;
          }
        }
        .cratesSearchBox {
          position: relative;
          flex: 1;
          max-width: 380px;
        }
        :global(.cratesSearchIcon) {
          position: absolute;
          left: 14px;
          top: 50%;
          transform: translateY(-50%);
          color: #210b0b;
        }
        .cratesSearchInput {
          width: 100%;
          padding: 9px 14px 9px 38px;
          background: #101116;
          border: 1px solid rgba(0, 0, 0, 0.1);
          border-radius: 10px;
          color: #000;
          font-family: inherit;
          font-size: 13.5px;
          outline: none;
          transition: border-color 0.2s, box-shadow 0.2s;
        }
        .cratesSearchInput:focus {
          border-color: var(--lp-blue);
          box-shadow: 0 0 0 4px var(--lp-blue-glow);
        }
        .cratesSortWrap {
          display: flex;
          align-items: center;
          gap: 8px;
        }
        .cratesSortLabel {
          font-size: 13px;
          color: var(--lp-muted);
        }
        .cratesSortSelect {
          background: #101116;
          border: 1px solid rgba(0, 0, 0, 0.1);
          border-radius: 8px;
          padding: 7px 12px;
          color: #000;
          font-family: inherit;
          font-size: 13px;
          outline: none;
          cursor: pointer;
          transition: border-color 0.2s;
        }
        .cratesSortSelect:focus {
          border-color: var(--lp-blue);
        }
        .cratesTabs {
          align-self: flex-start;
          overflow-x: auto;
          max-width: 100%;
        }

        /* Crates Catalog Grid */
        .cratesCatalogSection {
          margin-bottom: 60px;
        }
        .cratesCardsGrid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 20px;
        }
        @media (max-width: 1024px) {
          .cratesCardsGrid {
            grid-template-columns: repeat(2, 1fr);
          }
        }
        @media (max-width: 600px) {
          .cratesCardsGrid {
            grid-template-columns: 1fr;
          }
        }

        .crateCard {
          position: relative;
          background: linear-gradient(140deg, #101115, #0c0d10);
          border: 1px solid rgba(0, 0, 0, 0.09);
          border-radius: 14px;
          padding: 24px 20px 20px;
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          cursor: pointer;
          overflow: hidden;
          transition: border-color 0.25s, transform 0.25s, box-shadow 0.25s;
        }
        .crateCard:hover {
          border-color: rgba(255, 255, 255, 0.3);
          transform: translateY(-3px);
          box-shadow: 0 16px 36px rgba(0, 0, 0, 0.45);
        }
        .crateRibbon {
          position: absolute;
          top: 14px;
          left: 14px;
          font-size: 9px;
          letter-spacing: 1px;
          text-transform: uppercase;
          font-weight: 600;
          padding: 3px 8px;
          border-radius: 5px;
        }
        .crateRibbon-starter {
          background: rgba(255, 255, 255, 0.12);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: var(--lp-blue);
        }
        .crateRibbon-popular {
          background: rgba(248, 227, 227, 0.12);
          border: 1px solid rgba(248, 227, 227, 0.3);
          color: #f8e3e3;
        }
        .crateRibbon-hot {
          background: rgba(245, 225, 225, 0.12);
          border: 1px solid rgba(245, 225, 225, 0.3);
          color: #fbf1f1;
        }
        .crateRibbon-new {
          background: rgba(247, 217, 217, 0.12);
          border: 1px solid rgba(247, 217, 217, 0.3);
          color: #fceaea;
        }

        .crateVisualStage {
          margin: 12px 0 14px;
          display: flex;
          align-items: center;
          justify-content: center;
          min-height: 140px;
        }
        .crateMeta {
          width: 100%;
        }
        .crateMeta h3 {
          font-family: Unbounded, sans-serif !important;
          font-size: 16px !important;
          font-weight: 500 !important;
          letter-spacing: -0.4px !important;
          margin: 0 0 6px !important;
          color: #000 !important;
        }
        .cratePrice {
          display: inline-flex;
          align-items: center;
          gap: 5px;
          font-size: 13.5px;
          font-weight: 600;
          color: #420202;
          margin-bottom: 8px;
        }
        .cratePriceCoin {
          color: #f5e1e1;
        }
        .crateTagline {
          font-size: 12px;
          color: #420d0d;
          line-height: 1.6;
          margin: 0 0 16px;
          min-height: 38px;
        }
        .crateInspectBtn {
          width: 100%;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 7px;
          padding: 10px 16px;
          border-radius: 8px;
          background: #141720;
          border: 1px solid rgba(0, 0, 0, 0.12);
          color: #000;
          font-size: 13px;
          font-weight: 500;
          font-family: inherit;
          cursor: pointer;
          transition: background 0.2s, border-color 0.2s, color 0.2s;
        }
        .crateCard:hover .crateInspectBtn {
          background: var(--lp-blue);
          border-color: #ffffff;
          color: #604a4a;
        }

        /* Inspect / Unboxing Section */
        .cratesInspectSection {
          margin-bottom: 60px;
        }
        .inspectHeroCard {
          display: flex;
          background: linear-gradient(140deg, #101115, #0c0d10);
          border: 1px solid rgba(0, 0, 0, 0.09);
          border-radius: 16px;
          padding: 36px 32px;
          gap: 40px;
          margin-bottom: 36px;
          align-items: center;
          flex-wrap: wrap;
        }
        .inspectLeft {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          flex: 1;
          min-width: 280px;
        }
        .inspectBackBtn {
          align-self: flex-start;
          display: inline-flex;
          align-items: center;
          gap: 6px;
          background: transparent;
          border: none;
          color: var(--lp-muted);
          font-size: 13px;
          font-family: inherit;
          cursor: pointer;
          margin-bottom: 16px;
          padding: 0;
          transition: color 0.2s;
        }
        .inspectBackBtn:hover {
          color: #000;
        }
        .inspectVisualWrap {
          padding: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .inspectRight {
          flex: 1.4;
          min-width: 320px;
        }
        .inspectHeaderRow {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 8px;
        }
        .inspectHeaderRow h2 {
          font-family: Unbounded, sans-serif !important;
          font-size: 26px !important;
          font-weight: 500 !important;
          letter-spacing: -0.8px !important;
          margin: 0 !important;
          color: #000 !important;
        }
        .inspectTierChip {
          font-size: 9.5px;
          letter-spacing: 1px;
          text-transform: uppercase;
          font-weight: 600;
          padding: 3px 9px;
          border-radius: 5px;
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.25);
          color: var(--lp-blue);
        }
        .inspectDesc {
          color: #420d0d;
          font-size: 13.5px;
          line-height: 1.7;
          margin: 0 0 20px;
        }
        .inspectErrorBanner {
          display: flex;
          align-items: center;
          gap: 8px;
          background: rgba(239, 191, 191, 0.1);
          border: 1px solid rgba(239, 191, 191, 0.3);
          color: #f8d6d6;
          padding: 10px 14px;
          border-radius: 8px;
          font-size: 13px;
          margin-bottom: 18px;
        }
        .inspectActionBlock {
          display: flex;
          flex-direction: column;
          gap: 20px;
        }
        .inspectStatsStrip {
          display: flex;
          gap: 24px;
          padding: 12px 18px;
          background: rgba(0, 0, 0, 0.03);
          border: 1px solid rgba(0, 0, 0, 0.06);
          border-radius: 10px;
        }
        .inspectStat {
          display: flex;
          flex-direction: column;
          gap: 2px;
        }
        .statSub {
          font-size: 11px;
          color: var(--lp-muted);
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        .statVal {
          font-size: 14.5px;
          font-weight: 600;
          color: #000;
        }
        .priceVal {
          display: inline-flex;
          align-items: center;
          gap: 5px;
          color: var(--lp-blue);
        }
        .openCratePrimaryBtn {
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          gap: 8px !important;
          padding: 12px 28px !important;
          font-size: 13.5px !important;
        }
        .insufficientCard {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 16px;
          padding: 14px 18px;
          background: rgba(0, 0, 0, 0.02);
          border: 1px solid rgba(0, 0, 0, 0.07);
          border-radius: 10px;
          flex-wrap: wrap;
        }
        .insufficientText strong {
          display: block;
          color: #000;
          font-size: 13.5px;
          font-weight: 600;
        }
        .insufficientText p {
          color: #420d0d;
          font-size: 12px;
          margin: 2px 0 0;
        }

        /* Unboxing Ticker Area */
        .unboxingRollArea {
          padding: 20px;
          background: rgba(0, 0, 0, 0.35);
          border: 1px solid rgba(0, 0, 0, 0.08);
          border-radius: 12px;
          margin-bottom: 16px;
        }
        .rollTicker {
          position: relative;
          height: 70px;
          background: #08090d;
          border: 1px solid rgba(0, 0, 0, 0.1);
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          overflow: hidden;
        }
        .tickerIndicator {
          position: absolute;
          top: 0;
          bottom: 0;
          left: 50%;
          width: 2px;
          background: var(--lp-blue);
          box-shadow: 0 0 10px var(--lp-blue);
          z-index: 5;
        }
        .tickerItemInner {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 8px 16px;
          border-radius: 8px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid;
        }
        .tickerIcon {
          font-size: 24px;
        }
        .tickerName {
          font-weight: 700;
          font-size: 15px;
        }
        .unboxingRollingText {
          color: #420d0d;
          font-size: 12px;
          text-align: center;
          margin: 10px 0 0;
        }

        /* Revealed Win Card */
        .wonCardBox {
          padding: 20px;
          background: linear-gradient(140deg, #12151c, #0a0b0e);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 12px;
          margin-bottom: 16px;
        }
        .wonCardHeader {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 14px;
        }
        .wonRarityPill {
          font-size: 10px;
          font-weight: 700;
          letter-spacing: 0.5px;
          text-transform: uppercase;
          padding: 3px 9px;
          border-radius: 5px;
          border: 1px solid;
        }
        .duplicateRefundBadge {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          font-size: 11px;
          color: #f5e1e1;
          font-weight: 600;
        }
        .wonCardBody {
          display: flex;
          align-items: center;
          gap: 16px;
          margin-bottom: 16px;
        }
        .wonVisual {
          width: 56px;
          height: 56px;
          border-radius: 10px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.08);
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .wonImg {
          width: 44px;
          height: 44px;
          object-fit: contain;
        }
        .wonIcon {
          font-size: 28px;
        }
        .wonDetails h3 {
          font-family: Unbounded, sans-serif !important;
          font-size: 17px !important;
          font-weight: 500 !important;
          margin: 0 0 4px !important;
          color: #000 !important;
        }
        .wonDetails p {
          font-size: 12px;
          color: #420d0d;
          margin: 0;
        }
        .wonActions {
          display: flex;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;
        }
        .wonEquipBtn {
          display: inline-flex !important;
          align-items: center !important;
          gap: 6px !important;
        }

        /* Case Contents Grid */
        .caseContentsSection {
          margin-top: 20px;
        }
        .contentsHeaderRow {
          display: flex;
          align-items: baseline;
          justify-content: space-between;
          margin-bottom: 16px;
        }
        .contentsHeaderRow h3 {
          font-family: Unbounded, sans-serif !important;
          font-size: 18px !important;
          font-weight: 500 !important;
          letter-spacing: -0.4px !important;
          color: #000 !important;
          margin: 0 !important;
        }
        .contentsCount {
          font-size: 12px;
          color: var(--lp-muted);
        }
        .contentsGrid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
          gap: 14px;
        }

        /* Gold Rare Special Items Card */
        .rareSpecialCard {
          grid-column: span 1;
          background: linear-gradient(140deg, #1a160d, #0f0d08);
          border: 1px solid rgba(245, 225, 225, 0.25);
          border-radius: 12px;
          padding: 16px 14px;
          display: flex;
          flex-direction: column;
        }
        .rareSpecialHead {
          text-align: center;
          margin-bottom: 12px;
        }
        .laurelWreath {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 44px;
          height: 44px;
          border-radius: 50%;
          background: rgba(245, 225, 225, 0.1);
          margin-bottom: 6px;
        }
        .crownIcon {
          color: #fbf1f1;
        }
        .rareSpecialHead h4 {
          font-size: 12px;
          font-weight: 700;
          color: #fbf1f1;
          text-transform: uppercase;
          letter-spacing: 0.5px;
          margin: 0;
        }
        .rareSpecialList {
          display: flex;
          flex-direction: column;
          gap: 6px;
          font-size: 11px;
          color: #9b0707;
        }
        .rareSpecialRow {
          display: flex;
          align-items: center;
          gap: 6px;
        }
        .specialStar {
          color: #fbf1f1;
          font-size: 9px;
        }

        /* Individual Drop Card */
        .contentItemCard {
          background: #0d0f14;
          border: 1px solid rgba(0, 0, 0, 0.08);
          border-radius: 12px;
          padding: 14px 12px;
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          transition: border-color 0.2s, transform 0.2s;
        }
        .contentItemCard:hover {
          transform: translateY(-2px);
          border-color: rgba(0, 0, 0, 0.18);
        }
        .contentItemVisual {
          width: 52px;
          height: 52px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 10px;
        }
        .contentItemImg {
          width: 46px;
          height: 46px;
          object-fit: contain;
        }
        .contentItemIcon {
          font-size: 26px;
        }
        .contentItemMeta {
          width: 100%;
        }
        .contentItemMeta h4 {
          font-size: 12.5px;
          font-weight: 600;
          margin: 0 0 3px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .contentItemType {
          display: block;
          font-size: 10.5px;
          color: var(--lp-muted);
          margin-bottom: 10px;
        }
        .contentItemStats {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-top: 8px;
          border-top: 1px solid rgba(0, 0, 0, 0.06);
          font-size: 10px;
        }
        .contentItemStat {
          display: flex;
          flex-direction: column;
          gap: 1px;
        }
        .contentItemStat .sub {
          color: var(--lp-muted);
        }
        .contentItemStat .val {
          font-weight: 600;
          color: #000;
        }

        /* Companion Free Credits Section */
        .freeCreditsCompanion {
          margin-top: 64px;
          padding-top: 48px;
          border-top: 1px solid var(--lp-line);
        }
        .companionHeader {
          display: flex;
          align-items: flex-end;
          justify-content: space-between;
          gap: 24px;
          margin-bottom: 28px;
          flex-wrap: wrap;
        }
        .companionTitle {
          font-family: Unbounded, sans-serif !important;
          font-size: 26px !important;
          font-weight: 500 !important;
          letter-spacing: -0.8px !important;
          color: #000 !important;
          margin: 12px 0 6px !important;
        }
        .companionTopUp {
          display: flex;
          align-items: center;
          gap: 12px;
        }
        .topUpHint {
          font-size: 12.5px;
          color: var(--lp-muted);
        }
        .topUpBtn {
          display: inline-flex !important;
          align-items: center !important;
          gap: 6px !important;
          padding: 8px 16px !important;
        }
        .companionModulesGrid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 24px;
        }
        @media (max-width: 900px) {
          .companionModulesGrid {
            grid-template-columns: 1fr;
          }
        }
        .moduleCard {
          display: flex;
          flex-direction: column;
        }
        .companionNoticeChip {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          margin-top: 10px;
          padding: 8px 14px;
          background: rgba(0, 0, 0, 0.03);
          border: 1px solid rgba(0, 0, 0, 0.08);
          border-radius: 10px;
          font-size: 11.5px;
          color: #420d0d;
          max-width: 620px;
        }
      `}</style>
    </main>
  );
}
