// card-v2.jsx — Rakhtkan PlayerCard v2
// Field tier-aware architecture (Bronze / Silver / Gold / Platinum).
// Two sizes: 'full' (320×500, hero/pack/detail) and 'compact' (180×280, slot/grid).
// Locale-aware (fa/en/ar). RTL by default.

// ─── tier tokens ────────────────────────────────────────────────────────────
const TIER = {
  bronze: {
    key: 'bronze',
    name: { fa: 'برنزی', en: 'Bronze', ar: 'برونزي' },
    base: '#D97706',
    glow: 'rgba(217,119,6,0.55)',
    rim:  'rgba(217,119,6,0.45)',
    // field: warm copper → deep brown → near-black
    field: 'radial-gradient(ellipse 90% 70% at 50% 42%, #8a4e16 0%, #4a2912 45%, #1a0f08 80%, #0c0805 100%)',
    pillBg: 'linear-gradient(180deg, rgba(255,189,89,0.22) 0%, rgba(140,72,16,0.18) 100%)',
    pillStroke: 'rgba(255,180,89,0.40)',
    overallColor: '#FFCC85',
    accentText: '#FFB766',
    imageFilter: 'saturate(0.92) contrast(1.03) hue-rotate(-6deg)',
    watermark: 'rgba(255,180,89,0.06)',
  },
  silver: {
    key: 'silver',
    name: { fa: 'نقره‌ای', en: 'Silver', ar: 'فضي' },
    base: '#94A3B8',
    glow: 'rgba(148,163,184,0.50)',
    rim:  'rgba(180,195,215,0.45)',
    field: 'radial-gradient(ellipse 90% 70% at 50% 42%, #5d6b80 0%, #2f3a4a 45%, #131820 80%, #07090d 100%)',
    pillBg: 'linear-gradient(180deg, rgba(220,230,245,0.20) 0%, rgba(120,140,165,0.16) 100%)',
    pillStroke: 'rgba(220,230,245,0.36)',
    overallColor: '#E2EAF5',
    accentText: '#C7D3E3',
    imageFilter: 'saturate(0.85) contrast(1.02)',
    watermark: 'rgba(200,215,235,0.06)',
  },
  gold: {
    key: 'gold',
    name: { fa: 'طلایی', en: 'Gold', ar: 'ذهبي' },
    base: '#FCD34D',
    glow: 'rgba(252,211,77,0.55)',
    rim:  'rgba(252,211,77,0.55)',
    field: 'radial-gradient(ellipse 90% 70% at 50% 42%, #8a6a1e 0%, #4a3a14 45%, #1a1408 80%, #0d0a05 100%)',
    pillBg: 'linear-gradient(180deg, rgba(255,225,120,0.26) 0%, rgba(170,130,30,0.18) 100%)',
    pillStroke: 'rgba(255,220,120,0.50)',
    overallColor: '#FFE48A',
    accentText: '#FFD56B',
    imageFilter: 'saturate(1.05) contrast(1.04) brightness(1.02)',
    watermark: 'rgba(255,220,120,0.07)',
  },
  platinum: {
    key: 'platinum',
    name: { fa: 'پلاتین', en: 'Platinum', ar: 'بلاتيني' },
    base: '#93C5FD',
    glow: 'rgba(147,197,253,0.55)',
    rim:  'rgba(180,215,255,0.55)',
    field: 'radial-gradient(ellipse 90% 70% at 50% 42%, #4a6f95 0%, #1f3550 45%, #0c1722 80%, #050a10 100%)',
    pillBg: 'linear-gradient(180deg, rgba(190,220,255,0.24) 0%, rgba(80,130,190,0.18) 100%)',
    pillStroke: 'rgba(190,225,255,0.48)',
    overallColor: '#DDEAFB',
    accentText: '#BAD4F5',
    imageFilter: 'saturate(0.95) contrast(1.05) brightness(1.04)',
    watermark: 'rgba(190,220,255,0.07)',
  },
};

// ─── i18n strings ───────────────────────────────────────────────────────────
const I18N = {
  fa: {
    pos: { GK: 'دروازه‌بان', DEF: 'دفاع', MID: 'هافبک', FWD: 'مهاجم' },
    posShort: { GK: 'GK', DEF: 'DEF', MID: 'MID', FWD: 'FWD' },
    stat: { ATT: 'حمله', MID: 'میانه', DEF: 'دفاع', GK: 'گلر', PAS: 'پاس', DRI: 'دریبل', PHY: 'فیزیک', SPD: 'سرعت' },
    overall: 'امتیاز',
    locked: 'قفل',
    details: 'جزئیات',
    team: 'تیم',
    tier: 'سطح',
    position: 'پوزیشن',
  },
  en: {
    pos: { GK: 'Goalkeeper', DEF: 'Defender', MID: 'Midfielder', FWD: 'Forward' },
    posShort: { GK: 'GK', DEF: 'DEF', MID: 'MID', FWD: 'FWD' },
    stat: { ATT: 'ATT', MID: 'MID', DEF: 'DEF', GK: 'GK', PAS: 'PAS', DRI: 'DRI', PHY: 'PHY', SPD: 'SPD' },
    overall: 'OVR',
    locked: 'LOCKED',
    details: 'Details',
    team: 'Team',
    tier: 'Tier',
    position: 'Position',
  },
  ar: {
    pos: { GK: 'حارس', DEF: 'مدافع', MID: 'وسط', FWD: 'مهاجم' },
    posShort: { GK: 'GK', DEF: 'DEF', MID: 'MID', FWD: 'FWD' },
    stat: { ATT: 'هجوم', MID: 'وسط', DEF: 'دفاع', GK: 'حراسة', PAS: 'تمرير', DRI: 'مراوغة', PHY: 'بدني', SPD: 'سرعة' },
    overall: 'تقييم',
    locked: 'مقفل',
    details: 'التفاصيل',
    team: 'الفريق',
    tier: 'المستوى',
    position: 'المركز',
  },
};

// Convert Latin digits to locale digits
function toLocaleDigits(num, locale) {
  if (num == null) return '';
  const s = String(num);
  if (locale === 'fa') return s.replace(/[0-9]/g, (d) => '۰۱۲۳۴۵۶۷۸۹'[+d]);
  if (locale === 'ar') return s.replace(/[0-9]/g, (d) => '٠١٢٣٤٥٦٧٨٩'[+d]);
  return s;
}

// ─── icons ──────────────────────────────────────────────────────────────────
function IconChart({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 22 22" fill="none" aria-hidden="true">
      <rect x="3" y="13" width="3" height="6" rx="1" fill="currentColor" opacity="0.55"/>
      <rect x="9.5" y="9" width="3" height="10" rx="1" fill="currentColor" opacity="0.55"/>
      <rect x="16" y="5" width="3" height="14" rx="1" fill="currentColor" opacity="0.55"/>
      <path d="M17.5 3.2v3.6M15.7 5h3.6" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round" opacity="0.85"/>
    </svg>
  );
}
function IconSparkle({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 18 18" fill="none" aria-hidden="true">
      <path d="M9 1.5 L10.3 7.7 L16.5 9 L10.3 10.3 L9 16.5 L7.7 10.3 L1.5 9 L7.7 7.7 Z"
            fill="currentColor" opacity="0.65"/>
    </svg>
  );
}
function IconArrow({ size = 24 }) {
  // chevron — mirrored automatically in RTL via .pc-panel-cta svg rule
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none" aria-hidden="true">
      <path d="M5 3 L9 7 L5 11" stroke="currentColor" strokeWidth="2"
            fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ─── shared panel background (glass + stroke) ────────────────────────────────
// Notched panel shape with frosted-glass fill. The player image behind shows
// through as a soft blurred halo. Used by all 4 card types.
function PanelBackground({ compact, strokeColor = 'rgba(255,255,255,0.12)' }) {
  // Unified viewBox so the notch curve proportions match in BOTH compact and full.
  // With preserveAspectRatio="none" the path stretches to fill the container —
  // notch occupies the same fraction of width in both sizes.
  const W = 360;
  const H = 260;
  const cx = W / 2;
  const path = `M 24 0 L ${cx - 110} 0 Q ${cx - 90} 0 ${cx - 85} 18 Q ${cx - 70} 72 ${cx} 72 Q ${cx + 70} 72 ${cx + 85} 18 Q ${cx + 90} 0 ${cx + 110} 0 L ${W - 24} 0 Q ${W} 0 ${W} 24 L ${W} ${H - 24} Q ${W} ${H} ${W - 24} ${H} L 24 ${H} Q 0 ${H} 0 ${H - 24} L 0 24 Q 0 0 24 0 Z`;
  // Open top-edge subpath: traces just the top + notch curve — used for a
  // brighter highlight stroke so the panel's top edge reads against the player.
  const topPath = `M 24 0 L ${cx - 110} 0 Q ${cx - 90} 0 ${cx - 85} 18 Q ${cx - 70} 72 ${cx} 72 Q ${cx + 70} 72 ${cx + 85} 18 Q ${cx + 90} 0 ${cx + 110} 0 L ${W - 24} 0`;
  const svgStr = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${W} ${H}' preserveAspectRatio='none'><path d='${path}' fill='black'/></svg>`;
  const maskUrl = `url("data:image/svg+xml;utf8,${encodeURIComponent(svgStr)}")`;
  return (
    <React.Fragment>
      {/* Glass layer — translucent fill + backdrop-blur, masked to shape */}
      <div className="pc-panel-glass" style={{ WebkitMaskImage: maskUrl, maskImage: maskUrl }}></div>
      {/* Outline stroke (1px, non-scaling) — full perimeter */}
      <svg className="pc-panel-shape" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" aria-hidden="true">
        <path d={path}
              fill="none"
              stroke={strokeColor}
              strokeWidth="1"
              vectorEffect="non-scaling-stroke"/>
        {/* Brighter highlight along the top edge + notch curve only */}
        <path d={topPath}
              fill="none"
              stroke="rgba(255,255,255,0.32)"
              strokeWidth="1"
              vectorEffect="non-scaling-stroke"
              strokeLinecap="round"/>
      </svg>
    </React.Fragment>
  );
}

// ─── stats panel (Overall pill + 1 main stat + position label + name + CTA) ──
// Now contains player name and Details button INSIDE the glass panel.
function StatsPanel({ tier, locale, overall, statKey, statValue, position, compact,
                     playerName, onDetails }) {
  const tt = TIER[tier];
  const ll = I18N[locale];
  const statLabel = ll.stat[statKey] || statKey;
  const posLabel = ll.posShort[position] || position;
  const overallStr = toLocaleDigits(overall, locale);
  const statStr = toLocaleDigits(statValue, locale);

  return (
    <div className={`pc-stats ${compact ? 'pc-stats--compact' : ''}`}>
      {/* Floating Overall pill */}
      <div className="pc-pill" style={{
        backgroundImage: tt.pillBg,
        borderColor: tt.pillStroke,
        boxShadow: `0 8px 24px ${tt.glow.replace('0.55','0.30')}, inset 0 1px 0 rgba(255,255,255,0.18)`,
      }}>
        <div className="pc-pill-glow" style={{
          background: `radial-gradient(ellipse 70% 65% at 50% 60%, ${tt.glow} 0%, transparent 70%)`
        }}></div>
        <span className="pc-pill-overall" style={{ color: tt.overallColor }}>{overallStr}</span>
        <span className="pc-pill-label" style={{ color: tt.accentText }}>{ll.overall}</span>
      </div>

      {/* Glass panel with notched top — taller now to fit name + CTA */}
      <div className="pc-panel">
        <PanelBackground compact={compact} />
        <div className="pc-panel-content">
          <div className="pc-panel-row">
            <div className="pc-panel-side pc-panel-side--start">
              <span className="pc-panel-label" style={{ color: tt.accentText }}>{statLabel}</span>
              <span className="pc-panel-value">{statStr}</span>
            </div>
            <div className="pc-panel-side pc-panel-side--end">
              <span className="pc-panel-label" style={{ color: tt.accentText }}>{posLabel}</span>
            </div>
          </div>
          <div className="pc-panel-body">
            {playerName && <div className="pc-panel-name">{playerName}</div>}
            {onDetails && (
              <button className="pc-panel-cta" onClick={onDetails}
                      aria-label={ll.details}
                      title={ll.details}
                      style={{ borderColor: tt.pillStroke, color: tt.overallColor }}>
                <IconArrow />
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Details modal (portal-based, lives outside the design-canvas transform) ─
function CardDetailsModal({ open, onClose, title, subtitle, fields = [], accent = '#FCD34D', locale = 'fa' }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  const dir = locale === 'en' ? 'ltr' : 'rtl';
  const node = (
    <div className="pc-modal-backdrop" onClick={onClose} dir={dir} lang={locale}>
      <div className="pc-modal" onClick={(e) => e.stopPropagation()}
           style={{ '--accent': accent }}>
        <button className="pc-modal-close" onClick={onClose} aria-label="Close">×</button>
        <div className="pc-modal-accent" style={{ background: accent }}></div>
        <h2 className="pc-modal-title">{title}</h2>
        {subtitle && <div className="pc-modal-sub">{subtitle}</div>}
        <div className="pc-modal-grid">
          {fields.map((f, i) => (
            <div key={i} className="pc-modal-field">
              <span className="pc-modal-label">{f.label}</span>
              <span className="pc-modal-value">{f.value}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
  return ReactDOM.createPortal(node, document.body);
}

// ─── PlayerCard ─────────────────────────────────────────────────────────────
function PlayerCard({
  tier = 'gold',
  locale = 'fa',
  position = 'FWD',
  overall = 87,
  statKey = 'ATT',
  statValue = 92,
  playerName = 'مسی',
  playerImage = 'assets/mes.webp',
  teamName = 'آرژانتین',
  size = 'full',           // 'full' | 'compact'
  showWatermark = true,
  // Tuned for action-figure renders (full-body w/ golden base + nameplate):
  // the face sits high in the card and the base/nameplate clip behind the
  // stats glass panel. compact halves imageOffsetY internally (→ 137.5).
  imageScale = 2.03,
  imageOffsetY = 275,
  // Cross-screen modal integration: when a parent provides onDetails (or sets
  // window.__openCardDetails), the chevron forwards an inventory-shaped item
  // to the unified MyCardsDetailModal instead of opening the legacy provisional
  // modal embedded here. The embedded modal stays as a fallback for the
  // PlayerCard v2 standalone canvas if no parent is listening.
  onDetails,
}) {
  const tt = TIER[tier];
  const compact = size === 'compact';
  const [detailsOpen, setDetailsOpen] = React.useState(false);
  const ll = I18N[locale];

  // Resolve a click handler for the chevron: external first, then global
  // window registry, then fall back to the embedded modal.
  const externalOpen =
    onDetails ||
    (typeof window !== 'undefined' && window.__openCardDetails);
  const buildItem = () => {
    if (typeof window.toInventoryItem !== 'function' || typeof window.playerCardPropsToCard !== 'function') {
      // adapters not loaded — fall back to embedded modal
      return null;
    }
    const card = window.playerCardPropsToCard({
      tier, position, overall, statKey, statValue,
      playerName, teamName, playerImage,
    });
    return window.toInventoryItem(card, 'player', { isNew: false });
  };
  const handleDetails = () => {
    const item = buildItem();
    if (externalOpen && item) {
      externalOpen(item, locale);
    } else {
      setDetailsOpen(true);
    }
  };
  const useEmbedded = !externalOpen;

  return (
    <div className={`pc ${compact ? 'pc--compact' : ''}`} style={{
      // tier-driven rim glow on the outside
      boxShadow: `
        0 1px 0 rgba(255,255,255,0.05) inset,
        0 0 0 1px rgba(255,255,255,0.04),
        0 0 0 1px ${tt.rim} inset,
        0 20px 60px -10px ${tt.glow.replace('0.55','0.30')},
        0 30px 80px -20px rgba(0,0,0,0.6)
      `,
    }}>
      {/* Field background (tier tone) */}
      <div className="pc-field" style={{ background: tt.field }}></div>

      {/* Inner frame border (subtle) */}
      <div className="pc-frame"></div>

      {/* Top-right: tier badge — always English (GOLD/SILVER/BRONZE/PLATINUM) */}
      <div className="pc-tier-badge" style={{
        borderColor: tt.pillStroke,
        background: tt.pillBg,
        color: tt.overallColor,
      }}>
        <span>{tier.toUpperCase()}</span>
      </div>

      {/* Top-left: large sparkle (replaces old chart icon + bottom sparkle) */}
      <div className="pc-corner-sparkle" style={{ color: tt.accentText }}>
        <IconSparkle size={compact ? 28 : 48} />
      </div>

      {/* Team watermark behind player */}
      {showWatermark && (
        <div className="pc-watermark" style={{
          color: tt.watermark,
          // for FA/AR readable; for EN use display font
          fontFamily: locale === 'en' ? 'Boldonse, Inter, sans-serif' : 'inherit',
        }}>{teamName}</div>
      )}

      {/* Player image — action-figure render, full-body */}
      <div className="pc-player">
        <img className="pc-player-img" src={playerImage} alt={playerName}
             style={{
               filter: tt.imageFilter,
               transform: `translateY(${compact ? imageOffsetY * 0.5 : imageOffsetY}px) scale(${imageScale})`,
             }}
             onError={(e) => { e.target.style.opacity = '0.25'; }}/>
      </div>

      {/* Stats + name section */}
      <div className="pc-bottom">
        <StatsPanel
          tier={tier} locale={locale}
          overall={overall}
          statKey={statKey} statValue={statValue}
          position={position}
          compact={compact}
          playerName={playerName}
          onDetails={handleDetails}
        />
      </div>

      {/* Embedded legacy modal — kept ONLY as fallback when no external
          handler is registered. The unified My Cards modal is preferred. */}
      {useEmbedded && (
        <CardDetailsModal
          open={detailsOpen}
          onClose={() => setDetailsOpen(false)}
          locale={locale}
          accent={tt.base}
          title={playerName}
          subtitle={`${teamName} · ${ll.pos[position]}`}
          fields={[
            { label: ll.overall, value: toLocaleDigits(overall, locale) },
            { label: ll.stat[statKey] || statKey, value: toLocaleDigits(statValue, locale) },
            { label: ll.tier, value: tt.name[locale] },
            { label: ll.position, value: ll.pos[position] },
            { label: ll.team, value: teamName },
          ]}
        />
      )}
    </div>
  );
}

// expose to other scripts
Object.assign(window, { PlayerCard, PanelBackground, StatsPanel, CardDetailsModal, TIER, I18N, toLocaleDigits, IconChart, IconSparkle, IconArrow });

// ─── styles ─────────────────────────────────────────────────────────────────
const PC_CSS = `
  /* root card */
  .pc {
    position: relative;
    width: 360px;
    aspect-ratio: 360 / 560;
    border-radius: 28px;
    overflow: hidden;
    background: #06070A;
    color: #F5F4F0;
    isolation: isolate;
    font-family: inherit;
  }
  .pc--compact {
    width: 200px;
    border-radius: 18px;
  }

  /* Field tone */
  .pc-field {
    position: absolute;
    inset: 0;
    z-index: 0;
  }
  .pc-field::after {
    content: '';
    position: absolute;
    inset: 0;
    background:
      radial-gradient(ellipse 110% 50% at 50% 0%, rgba(0,0,0,0.45), transparent 55%),
      radial-gradient(ellipse 110% 55% at 50% 100%, rgba(0,0,0,0.55), transparent 50%);
  }

  /* Inner frame */
  .pc-frame {
    position: absolute;
    inset: 8px;
    border-radius: 22px;
    border: 1px solid rgba(255,255,255,0.06);
    box-shadow: 0 1px 0 rgba(255,255,255,0.06) inset;
    pointer-events: none;
    z-index: 5;
  }
  .pc--compact .pc-frame { inset: 5px; border-radius: 14px; }

  /* Top-right tier badge (English: GOLD/SILVER/BRONZE/PLATINUM/WILD/FAN/COACH) */
  .pc-tier-badge {
    position: absolute;
    top: 18px;
    right: 18px;
    z-index: 6;
    padding: 6px 14px;
    min-width: 64px;
    border-radius: 999px;
    border: 1px solid;
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
    font-weight: 700;
    font-size: 13px;
    letter-spacing: 0.10em;
    text-align: center;
    font-family: 'JetBrains Mono', ui-monospace, monospace !important;
    text-shadow: 0 1px 2px rgba(0,0,0,0.4);
    text-transform: uppercase;
  }
  .pc--compact .pc-tier-badge {
    top: 10px; right: 12px;
    padding: 3px 9px;
    font-size: 10px;
    min-width: 46px;
    letter-spacing: 0.08em;
  }
  /* mirror to left in LTR (English) so it stays in TOP-RIGHT optically? No,
     user wants top-right in ALL locales → keep physical right always */

  /* Top-left large sparkle */
  .pc-corner-sparkle {
    position: absolute;
    top: 14px;
    left: 18px;
    z-index: 6;
    opacity: 0.92;
    filter: drop-shadow(0 0 14px currentColor) drop-shadow(0 2px 6px rgba(0,0,0,0.4));
    pointer-events: none;
  }
  .pc--compact .pc-corner-sparkle {
    top: 8px; left: 12px;
  }

  /* Watermark team text */
  .pc-watermark {
    position: absolute;
    top: 26%;
    left: 0; right: 0;
    text-align: center;
    font-size: clamp(46px, 13vw, 84px);
    font-weight: 900;
    letter-spacing: -0.02em;
    z-index: 1;
    pointer-events: none;
    white-space: nowrap;
    line-height: 1;
    user-select: none;
  }
  .pc--compact .pc-watermark {
    top: 24%;
    font-size: 36px;
  }

  /* Player image */
  .pc-player {
    position: absolute;
    top: 12%;
    left: 0; right: 0;
    bottom: 24%;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    z-index: 2;
    overflow: visible;
    pointer-events: none;
  }
  .pc--compact .pc-player {
    top: 14%;
    bottom: 28%;
  }
  .pc-player-img {
    width: 84%;
    max-height: 100%;
    object-fit: contain;
    object-position: bottom center;
    transform-origin: bottom center;
    filter: drop-shadow(0 20px 30px rgba(0,0,0,0.55));
  }

  /* Null card: jersey on hanger — vertical center, top-aligned to reveal hanger */
  .pc-player--centered {
    align-items: center;
    top: 10%;
    bottom: 32%;
  }
  .pc-player-img--centered {
    object-position: center;
    transform-origin: center center;
    width: 70%;
    height: 100%;
  }

  /* Bottom section */
  .pc-bottom {
    position: absolute;
    left: 0; right: 0; bottom: 0;
    z-index: 3;
    padding: 0 16px 0;
  }
  .pc--compact .pc-bottom { padding: 0 10px 0; }

  /* Stats panel wrap */
  .pc-stats {
    position: relative;
  }

  .pc-panel {
    position: relative;
    width: 100%;
    height: 144px;
  }
  .pc--compact .pc-panel { height: 92px; }
  .pc-panel-shape {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }
  /* Glass effect — light blur (6px), heavier translucent fill via background */
  .pc-panel-glass {
    position: absolute;
    inset: 0;
    background: linear-gradient(180deg,
      rgb(18 18 28 / 58%) 0%,
      rgb(8 8 14 / 87%) 100%);
    -webkit-backdrop-filter: blur(32px) saturate(160%) brightness(0.55);
    backdrop-filter: blur(6px);
    -webkit-mask-size: 100% 100%;
    mask-size: 100% 100%;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
    pointer-events: none;
  }
  .pc-panel-content {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
  }
  .pc--compact .pc-panel-content { /* same column flex */ }
  .pc-panel-row {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 22px 0;
    min-height: 50px;
  }
  .pc--compact .pc-panel-row { padding: 12px 14px 0; min-height: 32px; }
  .pc-panel-body {
    flex: 1;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    padding: 0 22px 32px;
    min-width: 0;
  }
  .pc--compact .pc-panel-body { gap: 6px; padding: 10px 14px 10px; }
  .pc-panel-name {
    font-size: 30px;
    font-weight: 800;
    color: #FFFFFF;
    text-shadow: 0 1px 2px rgba(0,0,0,0.45);
    line-height: 1.1;
    text-align: start;
    max-width: calc(100% - 50px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    letter-spacing: -0.005em;
    flex: 1 1 auto;
    min-width: 0;
  }
  .pc--compact .pc-panel-name { font-size: 18px; font-weight: 700; max-width: calc(100% - 36px); }
  html[lang="en"] .pc-panel-name { font-weight: 800; }

  /* Circular icon-only Details button */
  .pc-panel-cta {
    font-family: inherit !important;
    flex: 0 0 auto;
    width: 48px;
    height: 48px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    border: 1px solid rgba(255,255,255,0.22);
    background: rgba(255,255,255,0.10);
    color: rgba(255,255,255,0.96);
    cursor: pointer;
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    transition: background .15s, border-color .15s, transform .12s, box-shadow .15s;
    box-shadow: 0 1px 0 rgba(255,255,255,0.06) inset, 0 2px 8px rgba(0,0,0,0.25);
  }
  .pc-panel-cta:hover {
    background: rgba(255,255,255,0.18);
    border-color: rgba(255,255,255,0.40);
    box-shadow: 0 1px 0 rgba(255,255,255,0.10) inset, 0 4px 14px rgba(0,0,0,0.4);
  }
  .pc-panel-cta:active { transform: scale(0.94); }
  .pc--compact .pc-panel-cta { width: 32px; height: 32px; }
  /* mirror chevron in RTL */
  html[dir="rtl"] .pc-panel-cta svg { transform: scaleX(-1); }
  .pc-panel-side {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1px;
    line-height: 1.05;
  }
  .pc-panel-label {
    font-size: 13px;
    font-weight: 600;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    font-family: 'JetBrains Mono', ui-monospace, monospace;
  }
  .pc--compact .pc-panel-label { font-size: 10px; }
  html[lang="fa"] .pc-panel-label,
  html[lang="ar"] .pc-panel-label {
    font-family: inherit;
    text-transform: none;
    letter-spacing: 0;
    font-size: 14px;
  }
  html[lang="fa"] .pc--compact .pc-panel-label,
  html[lang="ar"] .pc--compact .pc-panel-label {
    font-size: 11px;
  }
  .pc-panel-value {
    font-size: 22px;
    font-weight: 800;
    color: #FFFFFF;
    font-variant-numeric: tabular-nums;
    text-shadow: 0 1px 2px rgba(0,0,0,0.4);
  }
  .pc--compact .pc-panel-value { font-size: 16px; }

  /* Overall pill */
  .pc-pill {
    position: absolute;
    top: -28px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2;
    width: 38%;
    min-width: 130px;
    height: 78px;
    border-radius: 22px;
    border: 1px solid;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0;
    overflow: hidden;
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
    /* dark base — keeps text readable when blurred BG behind is bright (e.g.
       white jersey on Null card). Tier-color gradient layers on top via inline
       backgroundImage so the glass feel is preserved. */
    background-color: rgba(0, 0, 0, 0.40);
  }
  .pc--compact .pc-pill {
    top: -20px;
    width: 45%;
    min-width: 78px;
    height: 54px;
    border-radius: 14px;
  }
  .pc-pill-glow {
    position: absolute;
    inset: -20%;
    filter: blur(4px);
  }
  .pc-pill-overall {
    position: relative;
    font-size: 36px;
    font-weight: 900;
    letter-spacing: -0.02em;
    line-height: 1;
    font-variant-numeric: tabular-nums;
    text-shadow: 0 1px 7px rgb(0 0 0 / 67%);
    font-family: 'JetBrains Mono', ui-monospace, monospace;
  }
  .pc--compact .pc-pill-overall { font-size: 24px; }
  html[lang="fa"] .pc-pill-overall,
  html[lang="ar"] .pc-pill-overall {
    font-family: inherit;
  }
  .pc-pill-label {
    position: relative;
    font-size: 9px;
    font-weight: 600;
    letter-spacing: 0.14em;
    text-transform: uppercase;
    font-family: 'JetBrains Mono', ui-monospace, monospace;
    margin-top: 3px;
    opacity: 0.85;
  }
  .pc--compact .pc-pill-label { font-size: 7px; margin-top: 2px; }
  html[lang="fa"] .pc-pill-label,
  html[lang="ar"] .pc-pill-label {
    font-family: inherit;
    letter-spacing: 0.04em;
    text-transform: none;
    font-size: 10px;
  }
  html[lang="fa"] .pc--compact .pc-pill-label,
  html[lang="ar"] .pc--compact .pc-pill-label { font-size: 8px; }

  /* Name block (deprecated — name is now inside the glass panel) */
  .pc-name-block, .pc-name { display: none; }

  /* Old bottom sparkle + diamond pennant flags removed per user request */

  /* ===== Details modal (portal, lives on document.body) ===== */
  .pc-modal-backdrop {
    position: fixed; inset: 0;
    background: rgba(6, 6, 12, 0.78);
    backdrop-filter: blur(20px) saturate(140%);
    -webkit-backdrop-filter: blur(20px) saturate(140%);
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24px;
    animation: pc-modal-fade 0.18s ease;
  }
  @keyframes pc-modal-fade { from { opacity: 0; } to { opacity: 1; } }
  .pc-modal {
    position: relative;
    background: linear-gradient(180deg, rgba(22,22,30,0.96) 0%, rgba(10,10,16,0.96) 100%);
    border: 1px solid rgba(255,255,255,0.10);
    border-radius: 24px;
    padding: 36px 36px 32px;
    width: min(520px, 92vw);
    max-height: 86vh;
    overflow: auto;
    color: #F5F4F0;
    box-shadow: 0 30px 90px rgba(0,0,0,0.6), 0 0 80px var(--accent, transparent);
    animation: pc-modal-pop 0.22s cubic-bezier(.2,.7,.3,1.2);
    font-family: var(--font-current);
  }
  @keyframes pc-modal-pop { from { opacity: 0; transform: translateY(20px) scale(0.96); } to { opacity: 1; transform: none; } }
  .pc-modal-accent {
    position: absolute;
    top: 0; left: 24px; right: 24px;
    height: 3px;
    border-radius: 0 0 4px 4px;
    opacity: 0.85;
  }
  .pc-modal-close {
    position: absolute; top: 10px; left: 12px;
    background: transparent; border: 0; color: #B8B5AB;
    font-size: 28px; line-height: 1; cursor: pointer;
    width: 36px; height: 36px;
    display: flex; align-items: center; justify-content: center;
    border-radius: 10px;
    transition: background .12s, color .12s;
    font-family: inherit !important;
  }
  html[dir="ltr"] .pc-modal-close { left: auto; right: 12px; }
  .pc-modal-close:hover { background: rgba(255,255,255,0.08); color: #fff; }
  .pc-modal-title {
    margin: 4px 0 4px;
    font-size: 30px;
    font-weight: 800;
    letter-spacing: -0.01em;
    line-height: 1.15;
  }
  .pc-modal-sub {
    color: #B8B5AB;
    font-size: 14px;
    margin-bottom: 26px;
  }
  .pc-modal-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 18px 28px;
  }
  .pc-modal-field {
    display: flex; flex-direction: column;
    gap: 4px;
    min-width: 0;
  }
  .pc-modal-label {
    color: #8B8B83;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }
  html[lang="fa"] .pc-modal-label,
  html[lang="ar"] .pc-modal-label {
    text-transform: none;
    letter-spacing: 0;
    font-size: 12px;
  }
  .pc-modal-value {
    font-size: 20px;
    font-weight: 700;
    color: #F5F4F0;
    overflow: hidden;
    text-overflow: ellipsis;
  }
`;

const __pcStyleEl = document.createElement('style');
__pcStyleEl.textContent = PC_CSS;
document.head.appendChild(__pcStyleEl);
