// ============================================================
// SHOP PAGE — Tyrone Coins reward system
// ------------------------------------------------------------
// Blue glassmorphism theme (matches former Live Arena palette).
// Sections:
//   • Hero with coin visual + balance card
//   • How It Works (4 steps)
//   • Rewards Grid (4 premium reward cards)
//   • Upload Proof form (Tradeify/Apex)
//   • My Activity (proofs + orders history)
// ============================================================

const SHOP_REWARDS = [
  {
    id: 'elite-call',
    title: 'Elite Call Access',
    desc: 'Acces la 1 live call Elite — Luni sau Vineri, 19:00 RO.',
    cost: 25000,
    color: 'blue',
    icon: 'video',
    badge: 'POPULAR',
  },
  {
    id: 'tradeify-growth-50k',
    title: 'Tradeify Growth 50K',
    desc: 'Cont Growth 50K gratuit pe Tradeify (eval + first activation).',
    cost: 90000,
    color: 'cyan',
    icon: 'shield',
    badge: 'BEST VALUE',
  },
  {
    id: 'apex-50k',
    title: 'Apex 50K Evaluation',
    desc: 'Cont 50K Apex + activation fee plătit de Tyrone.',
    cost: 150000,
    color: 'gold',
    icon: 'target',
    badge: null,
  },
  {
    id: 'elite-month',
    title: '1 Month Elite Access',
    desc: 'Acces premium o lună întreagă la Elite Plan.',
    cost: 185000,
    color: 'acid',
    icon: 'crown',
    badge: 'PREMIUM',
  },
  {
    id: 'mentor-3-concepts',
    title: 'Mentorat 1:1 — 3 Concepte',
    desc: 'Tyrone îți explică 1:1, pe apel, 3 concepte alese de tine.',
    cost: 7000,
    color: 'acid',
    icon: 'brain',
    badge: 'NEW',
  },
  {
    id: 'one-on-one-call',
    title: 'Apel 1:1 cu Tyrone',
    desc: 'Apel privat 30-45 min — întrebări, plan, feedback.',
    cost: 10000,
    color: 'blue',
    icon: 'phone',
    badge: null,
  },
  {
    id: 'elite-recordings-4',
    title: '4 Înregistrări Elite',
    desc: 'Acces la 4 înregistrări video din arhiva Elite calls.',
    cost: 19000,
    color: 'cyan',
    icon: 'video',
    badge: null,
  },
  {
    id: 'elite-live-2',
    title: '2 Apeluri Live Elite',
    desc: 'Acces live la 2 call-uri Elite (Luni + Vineri, 19:00).',
    cost: 40000,
    color: 'gold',
    icon: 'bolt',
    badge: null,
  },
];

// Coins formula:
//   Tradeify: my commission 15%, user gets 30% back  →  price × 0.045 × 1000 = price × 45
//   Apex:     my commission 15%, user gets 20% back  →  price × 0.030 × 1000 = price × 30
const SHOP_FIRM_MULT = { tradeify: 45, apex: 30 };
const calcCoins = (firm, price) => Math.round(Number(price || 0) * (SHOP_FIRM_MULT[firm] || 0));

// Full catalog of purchasable accounts (mirrors page-propfirms.jsx)
const SHOP_ACCOUNT_CATALOG = {
  tradeify: {
    label: 'Tradeify',
    color: 'cyan',
    accentRgb: '79, 231, 213',
    code: 'TYRONE',
    // Prețurile mirror page-propfirms.jsx (promo activ cu codul TYRONE)
    types: [
      {
        id: 'growth',
        label: 'Growth Plan',
        desc: '1-Step rapid · fără consistency în evaluare',
        sizes: [
          { size: '25K',  price: 59.40 },
          { size: '50K',  price: 99.00 },
          { size: '100K', price: 159.00 },
          { size: '150K', price: 221.40 },
        ],
      },
      {
        id: 'select-daily',
        label: 'Select Daily',
        desc: '1-Step · Daily Loss Limit',
        sizes: [
          { size: '25K',  price: 65.40 },
          { size: '50K',  price: 99.00 },
          { size: '100K', price: 159.00 },
          { size: '150K', price: 221.40 },
        ],
      },
      {
        id: 'select-flex',
        label: 'Select Flex',
        desc: '1-Step · Flex Drawdown',
        sizes: [
          { size: '25K',  price: 65.40 },
          { size: '50K',  price: 99.00 },
          { size: '100K', price: 159.00 },
          { size: '150K', price: 221.40 },
        ],
      },
      {
        id: 'lightning',
        label: 'Lightning Funded',
        desc: 'Instant — fără evaluare',
        sizes: [
          { size: '25K',  price: 203.40 },
          { size: '50K',  price: 281.40 },
          { size: '100K', price: 413.40 },
          { size: '150K', price: 477.60 },
        ],
      },
    ],
  },
  apex: {
    label: 'Apex',
    color: 'blue',
    accentRgb: '90, 200, 255',
    code: 'NWAPJXME',
    types: [
      {
        id: 'eod',
        label: 'EOD',
        desc: 'End of Day drawdown · ține pozițiile peste noapte',
        sizes: [
          { size: '25K',  price: 34.90 },
          { size: '50K',  price: 39.90 },
          { size: '100K', price: 59.90 },
          { size: '150K', price: 89.90 },
        ],
      },
      {
        id: 'intraday',
        label: 'Intraday',
        desc: 'Trailing drawdown · doar intraday',
        sizes: [
          { size: '25K',  price: 24.90 },
          { size: '50K',  price: 29.90 },
          { size: '100K', price: 44.90 },
          { size: '150K', price: 69.90 },
        ],
      },
    ],
  },
};

// Build a flat list of firm summary cards for the toggle
const SHOP_FIRMS = [
  { id: 'tradeify', label: 'Tradeify', color: 'cyan' },
  { id: 'apex',     label: 'Apex',     color: 'blue' },
];

const fmtCoins = (n) => Number(n || 0).toLocaleString('en-US');
const fmtUsd   = (n) => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// ===== HOW IT WORKS =====
const ShopHowItWorks = () => {
  const steps = [
    { n: 1, title: 'Cumperi cu codul meu',  desc: 'Tradeify (cod TYRONE) sau Apex (cod NWAPJXME).' },
    { n: 2, title: 'Încarci dovada',         desc: 'Upload screenshot cu factura sau emailul de confirmare.' },
    { n: 3, title: 'Primești Tyrone Coins',  desc: 'După aprobarea admin, coins-urile intră automat în cont.' },
    { n: 4, title: 'Răscumperi recompense',  desc: 'Elite calls, conturi funded, abonament Elite — totul în Shop.' },
  ];
  return (
    <section style={{ paddingTop: 80, paddingBottom: 60 }}>
      <div className="container">
        <SectionHeader
          eyebrow="HOW IT WORKS"
          title="Cum funcționează."
          subtitle="4 pași simpli ca să transformi achizițiile reale în recompense exclusive." />
        <div className="grid grid-4 shop-steps">
          {steps.map((s) => (
            <div key={s.n} className="card card-pad-lg shop-step">
              <div className="shop-step-num">{String(s.n).padStart(2,'0')}</div>
              <h4 style={{ marginTop: 16 }}>{s.title}</h4>
              <p style={{ marginTop: 8, fontSize: 13.5, color: 'var(--text-dim)' }}>{s.desc}</p>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        .shop-steps { gap: 18px; }
        .shop-step {
          position: relative;
          transition: transform 0.3s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.3s, box-shadow 0.3s;
          background:
            linear-gradient(180deg, rgba(90,200,255,0.04) 0%, rgba(10,10,12,0.85) 100%);
          border: 1px solid rgba(90,200,255,0.15);
        }
        .shop-step:hover {
          transform: translateY(-4px);
          border-color: rgba(90,200,255,0.40);
          box-shadow: 0 24px 60px rgba(0,0,0,0.6), 0 0 40px rgba(90,200,255,0.18);
        }
        .shop-step-num {
          font-family: 'JetBrains Mono', monospace;
          font-size: 13px;
          letter-spacing: 0.18em;
          color: var(--blue, #5AC8FF);
          padding: 4px 10px;
          background: rgba(90,200,255,0.10);
          border: 1px solid rgba(90,200,255,0.28);
          border-radius: 999px;
          display: inline-block;
        }
      `}</style>
    </section>
  );
};

// ===== HERO =====
const ShopHero = ({ user, balance, onScrollTo }) => {
  const isLoggedIn = !!user;
  return (
    <section style={{ paddingTop: 70, paddingBottom: 40 }}>
      <div className="container">
        <div className="shop-hero">
          <div>
            <div className="eyebrow"><span className="dot" style={{background:'var(--blue,#5AC8FF)'}}/>SHOP · REWARDS</div>
            <h1 style={{ marginTop: 22 }}>
              Tyrone Coins <span className="shop-acc">Shop</span>.
            </h1>
            <p className="lead" style={{ marginTop: 22, maxWidth: 560 }}>
              Câștigi coins când cumperi conturi prop firm cu codul meu. Le folosești pentru Elite access, conturi funded și recompense exclusive.
            </p>

            <div className="shop-balance-card">
              <div className="shop-balance-glow" />
              <div className="shop-balance-row">
                <div>
                  <div className="shop-balance-label">SOLD CURENT</div>
                  {isLoggedIn ? (
                    <div className="shop-balance-value">
                      <span className="shop-coin-icn">🪙</span>
                      <span className="shop-balance-num">{fmtCoins(balance)}</span>
                      <span className="shop-balance-suffix">TC</span>
                    </div>
                  ) : (
                    <div className="shop-balance-value shop-balance-locked">Login pentru sold</div>
                  )}
                </div>
                <div className="shop-balance-meta">
                  <div className="shop-balance-eq">
                    {isLoggedIn ? (
                      <>~ <strong>${(balance/1000).toFixed(2)}</strong> valoare internă</>
                    ) : (
                      <>1.000 TC = $1 valoare internă</>
                    )}
                  </div>
                </div>
              </div>

              <div className="shop-cta-row">
                <Button variant="acid" size="lg" onClick={() => onScrollTo('rewards')}>
                  Vezi recompense
                </Button>
                <Button variant="ghost" size="lg" onClick={() => onScrollTo('upload')}>
                  <Icon name="upload" size={16}/> Încarcă dovadă
                </Button>
              </div>
            </div>
          </div>

          <div className="shop-coin-wrap">
            <div className="shop-coin-halo" />
            <div className="shop-coin-halo shop-coin-halo-2" />
            <img src="assets/tyrone-coin.png" alt="Tyrone Coin" className="shop-coin-img"
                 onError={(e) => { e.target.style.display = 'none'; e.target.parentNode.classList.add('no-coin'); }} />
            <div className="shop-coin-fallback">
              <div className="shop-coin-fallback-inner">🪙</div>
            </div>
            <div className="shop-coin-sparkles">
              <span/><span/><span/><span/><span/><span/>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .shop-hero {
          display: grid;
          grid-template-columns: 1.1fr 1fr;
          gap: 60px;
          align-items: center;
        }
        @media (max-width: 920px) { .shop-hero { grid-template-columns: 1fr; gap: 40px; } }

        .shop-acc {
          background: linear-gradient(180deg, #B2E8FF 0%, #5AC8FF 60%, #2EA8E8 100%);
          -webkit-background-clip: text; background-clip: text;
          color: transparent;
        }

        .shop-balance-card {
          position: relative;
          margin-top: 36px;
          padding: 28px 30px;
          border-radius: 22px;
          background:
            linear-gradient(180deg, rgba(90,200,255,0.07) 0%, rgba(10,10,12,0.85) 100%);
          border: 1px solid rgba(90,200,255,0.30);
          box-shadow:
            0 24px 70px rgba(0,0,0,0.60),
            0 0 50px rgba(90,200,255,0.10),
            inset 0 1px 0 rgba(255,255,255,0.05);
          overflow: hidden;
          isolation: isolate;
        }
        .shop-balance-glow {
          position: absolute;
          top: -50%; left: -10%;
          width: 120%; height: 200%;
          background: radial-gradient(ellipse at center, rgba(90,200,255,0.12) 0%, transparent 60%);
          z-index: -1;
          animation: shopGlow 8s ease-in-out infinite;
        }
        @keyframes shopGlow {
          0%,100% { opacity: 0.7; transform: translate(0,0); }
          50%     { opacity: 1; transform: translate(20px,-15px); }
        }
        .shop-balance-row {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          gap: 20px;
          flex-wrap: wrap;
        }
        .shop-balance-label {
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          letter-spacing: 0.18em;
          color: rgba(255,255,255,0.50);
        }
        .shop-balance-value {
          margin-top: 6px;
          display: flex;
          align-items: baseline;
          gap: 10px;
          line-height: 1;
        }
        .shop-coin-icn { font-size: 28px; }
        .shop-balance-num {
          font-size: 44px;
          font-weight: 800;
          letter-spacing: -0.03em;
          background: linear-gradient(180deg, #FFFFFF 0%, #5AC8FF 100%);
          -webkit-background-clip: text; background-clip: text;
          color: transparent;
        }
        .shop-balance-suffix {
          font-family: 'JetBrains Mono', monospace;
          font-size: 14px;
          color: var(--blue,#5AC8FF);
          font-weight: 700;
        }
        .shop-balance-locked {
          font-size: 18px;
          color: rgba(255,255,255,0.45);
          font-weight: 500;
        }
        .shop-balance-meta {
          font-size: 12px;
          color: var(--text-mute);
          font-family: 'JetBrains Mono', monospace;
        }
        .shop-balance-meta strong { color: var(--blue,#5AC8FF); }
        .shop-cta-row {
          margin-top: 22px;
          display: flex;
          gap: 12px;
          flex-wrap: wrap;
        }

        /* Coin visual */
        .shop-coin-wrap {
          position: relative;
          aspect-ratio: 1/1;
          max-width: 460px;
          margin-left: auto;
          display: grid;
          place-items: center;
        }
        .shop-coin-halo {
          position: absolute;
          inset: 8%;
          border-radius: 50%;
          background: radial-gradient(circle at center, rgba(90,200,255,0.45) 0%, rgba(90,200,255,0) 60%);
          filter: blur(40px);
          animation: shopHalo 4s ease-in-out infinite;
        }
        .shop-coin-halo-2 {
          inset: 18%;
          background: radial-gradient(circle at center, rgba(255,203,82,0.30) 0%, rgba(255,203,82,0) 70%);
          filter: blur(30px);
          animation-delay: 1.5s;
        }
        @keyframes shopHalo {
          0%,100% { opacity: 0.6; transform: scale(1); }
          50%     { opacity: 1; transform: scale(1.08); }
        }
        .shop-coin-img {
          position: relative;
          width: 86%;
          height: 86%;
          object-fit: contain;
          z-index: 2;
          animation: shopCoinFloat 6s ease-in-out infinite;
          filter: drop-shadow(0 30px 60px rgba(255,203,82,0.45)) drop-shadow(0 0 30px rgba(90,200,255,0.30));
        }
        @keyframes shopCoinFloat {
          0%,100% { transform: translateY(0) rotate(-6deg); }
          50%     { transform: translateY(-14px) rotate(6deg); }
        }
        /* fallback if image missing */
        .shop-coin-fallback { position: absolute; inset: 0; display: none; place-items: center; z-index: 1; }
        .no-coin .shop-coin-fallback { display: grid; }
        .shop-coin-fallback-inner {
          font-size: 200px;
          filter: drop-shadow(0 20px 40px rgba(255,203,82,0.5));
        }

        .shop-coin-sparkles { position: absolute; inset: 0; pointer-events: none; }
        .shop-coin-sparkles span {
          position: absolute;
          width: 4px; height: 4px;
          background: #FFE694;
          border-radius: 50%;
          box-shadow: 0 0 10px #FFCB52;
          animation: shopSparkle 3s ease-in-out infinite;
        }
        .shop-coin-sparkles span:nth-child(1) { top: 10%; left: 20%; animation-delay: 0s; }
        .shop-coin-sparkles span:nth-child(2) { top: 25%; right: 15%; animation-delay: 0.4s; }
        .shop-coin-sparkles span:nth-child(3) { top: 60%; right: 8%;  animation-delay: 0.8s; }
        .shop-coin-sparkles span:nth-child(4) { bottom: 18%; left: 14%; animation-delay: 1.2s; }
        .shop-coin-sparkles span:nth-child(5) { bottom: 35%; right: 22%; animation-delay: 1.6s; }
        .shop-coin-sparkles span:nth-child(6) { top: 45%; left: 8%;  animation-delay: 2s; }
        @keyframes shopSparkle {
          0%,100% { opacity: 0; transform: scale(0.5); }
          50%     { opacity: 1; transform: scale(1.5); }
        }
      `}</style>
    </section>
  );
};

// ===== REWARDS GRID =====
const ShopRewards = ({ user, balance, onRedeem, busyId }) => {
  return (
    <section id="rewards" style={{ paddingTop: 60, paddingBottom: 60 }}>
      <div className="container">
        <SectionHeader
          eyebrow="REWARDS"
          title="Răscumpără cu Tyrone Coins."
          subtitle="Recompense reale, plătite cu coins-urile pe care le-ai câștigat din achizițiile cu codul meu." />
        <div className="grid grid-4 shop-rewards-grid">
          {SHOP_REWARDS.map(r => {
            const canAfford = !!user && balance >= r.cost;
            const isBusy = busyId === r.id;
            return (
              <div key={r.id} className={`card card-pad-lg shop-reward shop-reward-${r.color} ${!canAfford ? 'is-locked' : ''}`}>
                {r.badge && <div className={`shop-reward-badge sr-badge-${r.color}`}>{r.badge}</div>}
                <div className="shop-reward-icon-wrap">
                  <IconChip icon={r.icon} color={r.color === 'blue' ? 'blue' : r.color} size="lg" />
                </div>
                <h3 style={{ marginTop: 18, fontSize: 19 }}>{r.title}</h3>
                <p style={{ marginTop: 8, fontSize: 13, color: 'var(--text-dim)', minHeight: 38 }}>{r.desc}</p>
                <div className="shop-reward-cost">
                  <span className="shop-coin-icn" style={{ fontSize: 18 }}>🪙</span>
                  <span className="shop-reward-cost-num">{fmtCoins(r.cost)}</span>
                  <span className="shop-reward-cost-suffix">TC</span>
                </div>
                <button
                  className={`btn ${canAfford ? 'btn-acid' : 'btn-ghost'} shop-reward-btn`}
                  disabled={!canAfford || isBusy}
                  onClick={() => onRedeem(r)}>
                  {isBusy ? 'Se procesează…' :
                   !user ? 'Login pentru a răscumpăra' :
                   !canAfford ? `Mai ai nevoie de ${fmtCoins(r.cost - balance)} TC` :
                   'Răscumpără acum →'}
                </button>
              </div>
            );
          })}
        </div>
      </div>
      <style>{`
        .shop-rewards-grid { gap: 18px; }
        .shop-reward {
          position: relative;
          display: flex;
          flex-direction: column;
          transition: transform 0.35s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.3s, box-shadow 0.3s;
          background:
            linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(10,10,12,0.85) 100%);
          border: 1px solid rgba(255,255,255,0.08);
          overflow: hidden;
        }
        .shop-reward-blue { border-color: rgba(90,200,255,0.20); }
        .shop-reward-cyan { border-color: rgba(79,231,213,0.20); }
        .shop-reward-gold { border-color: rgba(255,203,82,0.20); }
        .shop-reward-acid { border-color: rgba(183,255,26,0.20); }
        .shop-reward:hover {
          transform: translateY(-6px);
          border-color: rgba(90,200,255,0.55);
          box-shadow: 0 30px 70px rgba(0,0,0,0.65), 0 0 50px rgba(90,200,255,0.18);
        }
        .shop-reward-cyan:hover  { box-shadow: 0 30px 70px rgba(0,0,0,0.65), 0 0 50px rgba(79,231,213,0.20); border-color: rgba(79,231,213,0.55); }
        .shop-reward-gold:hover  { box-shadow: 0 30px 70px rgba(0,0,0,0.65), 0 0 50px rgba(255,203,82,0.22); border-color: rgba(255,203,82,0.55); }
        .shop-reward-acid:hover  { box-shadow: 0 30px 70px rgba(0,0,0,0.65), 0 0 50px rgba(183,255,26,0.20); border-color: rgba(183,255,26,0.55); }
        .shop-reward.is-locked { opacity: 0.78; }
        .shop-reward.is-locked:hover { transform: none; }

        .shop-reward-badge {
          position: absolute;
          top: 14px; right: 14px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 9.5px;
          letter-spacing: 0.18em;
          padding: 4px 9px;
          border-radius: 999px;
          background: rgba(0,0,0,0.55);
          backdrop-filter: blur(6px);
          z-index: 2;
        }
        .sr-badge-blue { color: var(--blue,#5AC8FF); border: 1px solid rgba(90,200,255,0.35); }
        .sr-badge-cyan { color: var(--cyan,#4FE7D5); border: 1px solid rgba(79,231,213,0.35); }
        .sr-badge-gold { color: var(--gold,#FFCB52); border: 1px solid rgba(255,203,82,0.35); }
        .sr-badge-acid { color: var(--acid,#B7FF1A); border: 1px solid rgba(183,255,26,0.35); }

        .shop-reward-icon-wrap { display: inline-block; }
        .shop-reward-cost {
          margin-top: auto;
          padding-top: 16px;
          display: flex;
          align-items: baseline;
          gap: 6px;
          line-height: 1;
        }
        .shop-reward-cost-num {
          font-size: 26px;
          font-weight: 800;
          letter-spacing: -0.02em;
        }
        .shop-reward-cost-suffix {
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          color: var(--text-mute);
        }
        .shop-reward-btn { margin-top: 14px; width: 100%; }
      `}</style>
    </section>
  );
};

// ===== UPLOAD PROOF =====
const MAX_FILE_MB = 50;
const ACCEPT_MIME = 'image/png,image/jpeg,image/jpg,image/webp,video/mp4,video/quicktime,video/webm,video/x-m4v';

const ShopUpload = ({ user, onSubmitted }) => {
  const [firm,    setFirm]    = React.useState('tradeify');
  const [typeId,  setTypeId]  = React.useState(SHOP_ACCOUNT_CATALOG.tradeify.types[0].id);
  const [sizeIdx, setSizeIdx] = React.useState(null);  // index inside current type's sizes
  const [note,    setNote]    = React.useState('');
  const [file,    setFile]    = React.useState(null);
  const [busy,    setBusy]    = React.useState(false);
  const [msg,     setMsg]     = React.useState('');
  const [err,     setErr]     = React.useState('');

  const switchFirm = (newFirm) => {
    setFirm(newFirm);
    setTypeId(SHOP_ACCOUNT_CATALOG[newFirm].types[0].id);
    setSizeIdx(null);
  };
  const switchType = (newTypeId) => {
    setTypeId(newTypeId);
    setSizeIdx(null);
  };

  if (!user) {
    return (
      <section id="upload" style={{ paddingTop: 60, paddingBottom: 60 }}>
        <div className="container">
          <div className="card card-pad-lg" style={{ textAlign:'center' }}>
            <div className="eyebrow" style={{ justifyContent:'center', display:'inline-flex' }}>
              <span className="dot" style={{background:'var(--blue,#5AC8FF)'}}/>LOGIN REQUIRED
            </div>
            <h3 style={{ marginTop: 14 }}>Loghează-te pentru a încărca dovada</h3>
            <p style={{ marginTop: 8, color: 'var(--text-dim)' }}>
              Trebuie să ai un cont gratuit pentru a putea încărca dovada achiziției și a primi Tyrone Coins.
            </p>
          </div>
        </div>
      </section>
    );
  }

  const firmCatalog   = SHOP_ACCOUNT_CATALOG[firm];
  const currentType   = firmCatalog.types.find(t => t.id === typeId) || firmCatalog.types[0];
  const selectedSize  = sizeIdx != null ? currentType.sizes[sizeIdx] : null;
  const selectedPrice = selectedSize ? selectedSize.price : 0;
  const expectedCoins = calcCoins(firm, selectedPrice);

  const submit = async (e) => {
    e?.preventDefault?.();
    setErr(''); setMsg('');
    if (!selectedSize) { setErr('Selectează contul cumpărat (tip + mărime).'); return; }
    if (!file)         { setErr('Atașează dovada (imagine sau video).'); return; }
    if (file.size > MAX_FILE_MB * 1024 * 1024) {
      setErr(`Fișierul depășește ${MAX_FILE_MB} MB. Compresează-l sau scurtează video-ul.`); return;
    }
    if (!window.sb) { setErr('Backend indisponibil.'); return; }
    setBusy(true);

    try {
      // 1) Upload la storage bucket "coin-proofs"
      const ext = (file.name.split('.').pop() || 'png').toLowerCase().replace(/[^a-z0-9]/g,'');
      const path = `${user.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${ext}`;
      const { error: upErr } = await window.sb.storage.from('coin-proofs').upload(path, file, {
        cacheControl: '3600', upsert: false, contentType: file.type || 'application/octet-stream',
      });
      if (upErr) throw upErr;

      // 2) Insert proof — account label is human readable, amount is the real price
      const accountLabel = `${currentType.label} — ${selectedSize.size}`;
      const { error: insErr } = await window.sb.from('coin_proofs').insert({
        user_id:        user.id,
        firm,
        account_type:   accountLabel,
        amount:         selectedPrice,
        screenshot_url: path,
        note:           note.trim() || null,
        status:         'pending',
        coins_awarded:  0,
      });
      if (insErr) throw insErr;

      setMsg(`Dovadă trimisă cu succes! Vei primi ~${fmtCoins(expectedCoins)} TC după aprobarea admin.`);
      setSizeIdx(null); setNote(''); setFile(null);
      const fileInput = document.getElementById('shop-file-input');
      if (fileInput) fileInput.value = '';
      onSubmitted?.();
    } catch (e2) {
      setErr(e2.message || 'A apărut o eroare la trimitere.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <section id="upload" style={{ paddingTop: 60, paddingBottom: 60 }}>
      <div className="container">
        <SectionHeader
          eyebrow="UPLOAD PROOF"
          title="Încarcă dovada achiziției."
          subtitle="Selectează contul exact pe care l-ai cumpărat. Coins-urile se calculează automat din prețul contului." />

        <div className="card card-pad-lg shop-upload-card">
          <form onSubmit={submit} className="shop-upload-form">

            {/* STEP 1 — firm */}
            <div className="shop-field-group">
              <label className="shop-label">1. Firma</label>
              <div className="shop-firm-toggle">
                {SHOP_FIRMS.map(f => (
                  <button key={f.id} type="button"
                    className={`shop-firm-opt shop-firm-${f.id} ${firm === f.id ? 'is-active' : ''}`}
                    onClick={() => switchFirm(f.id)}>
                    {f.label}
                    <span className="shop-firm-coins">
                      cod {SHOP_ACCOUNT_CATALOG[f.id].code}
                    </span>
                  </button>
                ))}
              </div>
            </div>

            {/* STEP 2 — account type pills */}
            <div className="shop-field-group">
              <label className="shop-label">2. Tipul contului</label>
              <div className="shop-type-pills">
                {firmCatalog.types.map(t => (
                  <button key={t.id} type="button"
                    className={`shop-type-pill ${typeId === t.id ? 'is-active' : ''}`}
                    onClick={() => switchType(t.id)}>
                    {t.label}
                  </button>
                ))}
              </div>
              <div className="shop-type-desc">{currentType.desc}</div>
            </div>

            {/* STEP 3 — size cards grid */}
            <div className="shop-field-group">
              <label className="shop-label">3. Mărimea contului</label>
              <div className="shop-size-grid">
                {currentType.sizes.map((s, idx) => {
                  const isSelected = sizeIdx === idx;
                  const coinsForCard = calcCoins(firm, s.price);
                  return (
                    <button key={s.size} type="button"
                      className={`shop-size-card ${isSelected ? 'is-selected' : ''}`}
                      onClick={() => setSizeIdx(idx)}>
                      <div className="shop-size-name">{s.size}</div>
                      <div className="shop-size-price">${fmtUsd(s.price)}</div>
                      <div className="shop-size-coins">
                        <span className="shop-coin-icn-sm">🪙</span> +{fmtCoins(coinsForCard)} TC
                      </div>
                      {isSelected && <div className="shop-size-check"><Icon name="check" size={13} stroke={3}/></div>}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Estimated reward summary */}
            <div className={`shop-estimate ${selectedSize ? 'is-ready' : ''}`}>
              <div className="shop-est-label">RECOMPENSĂ ESTIMATĂ</div>
              {selectedSize ? (
                <>
                  <div className="shop-est-main">
                    <span className="shop-coin-icn">🪙</span>
                    <span className="shop-est-num">{fmtCoins(expectedCoins)}</span>
                    <span className="shop-est-suf">TC</span>
                  </div>
                  <div className="shop-est-detail">
                    {currentType.label} {selectedSize.size} · ${fmtUsd(selectedPrice)}
                  </div>
                </>
              ) : (
                <div className="shop-est-empty">Selectează un cont pentru a vedea estimarea.</div>
              )}
            </div>

            {/* STEP 4 — file */}
            <div className="shop-field-group">
              <label className="shop-label" htmlFor="shop-file-input">
                4. Dovadă (imagine SAU video până la {MAX_FILE_MB} MB)
              </label>
              <input id="shop-file-input" type="file" accept={ACCEPT_MIME}
                onChange={(e) => setFile(e.target.files?.[0] || null)}
                className="shop-file" />
              {file && (
                <div className="shop-file-meta">
                  {file.type.startsWith('video/') ? '🎬' : '📎'} {file.name} ({(file.size/1024/1024).toFixed(2)} MB)
                  {file.size > MAX_FILE_MB*1024*1024 && (
                    <span style={{ color: '#FB7185', marginLeft: 8 }}>⚠ peste {MAX_FILE_MB} MB</span>
                  )}
                </div>
              )}
              <div className="shop-file-hint">
                Recomandat: <strong>video scurt</strong> (15-60 sec) cu pașii de checkout unde se vede clar codul <strong>{firmCatalog.code}</strong> aplicat.
              </div>
            </div>

            {/* Optional note */}
            <div className="shop-field-group">
              <label className="shop-label" htmlFor="shop-note">Notă (opțional)</label>
              <textarea id="shop-note" className="shop-input shop-textarea"
                rows={3}
                placeholder="Detalii suplimentare pentru admin (opțional)"
                value={note} onChange={(e) => setNote(e.target.value)} />
            </div>

            {err && <div className="shop-msg shop-err">{err}</div>}
            {msg && <div className="shop-msg shop-ok">{msg}</div>}

            <div className="shop-submit-row">
              <div className="shop-expect">
                {selectedSize ? (
                  <>Vei primi: <strong>+{fmtCoins(expectedCoins)} TC</strong> după aprobare</>
                ) : (
                  <>Selectează un cont pentru a vedea recompensa</>
                )}
              </div>
              <Button type="submit" variant="acid" size="lg" disabled={busy || !selectedSize}>
                {busy ? 'Se trimite…' : 'Trimite dovada'} <Icon name="arrowUR" size={14}/>
              </Button>
            </div>
          </form>
        </div>
      </div>

      <style>{`
        .shop-upload-card {
          background:
            linear-gradient(180deg, rgba(90,200,255,0.04) 0%, rgba(10,10,12,0.85) 100%);
          border: 1px solid rgba(90,200,255,0.20);
          box-shadow: 0 24px 60px rgba(0,0,0,0.55), 0 0 40px rgba(90,200,255,0.08);
        }
        .shop-upload-form { display: flex; flex-direction: column; gap: 18px; max-width: 640px; margin: 0 auto; }
        .shop-field-group { display: flex; flex-direction: column; gap: 8px; }
        .shop-label {
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          letter-spacing: 0.14em;
          text-transform: uppercase;
          color: rgba(255,255,255,0.55);
        }
        .shop-input {
          padding: 12px 16px;
          border-radius: 10px;
          background: rgba(0,0,0,0.45);
          border: 1px solid rgba(255,255,255,0.10);
          color: #fff;
          font: inherit;
          font-size: 14px;
          outline: none;
          transition: border-color 0.25s, background 0.25s;
        }
        .shop-input:focus {
          border-color: rgba(90,200,255,0.50);
          background: rgba(0,0,0,0.6);
          box-shadow: 0 0 0 3px rgba(90,200,255,0.10);
        }
        .shop-textarea { resize: vertical; min-height: 80px; font-family: inherit; }

        .shop-firm-toggle { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .shop-firm-opt {
          display: flex; flex-direction: column; align-items: center; gap: 4px;
          padding: 14px 16px;
          border-radius: 12px;
          background: rgba(255,255,255,0.03);
          border: 1px solid rgba(255,255,255,0.10);
          color: var(--text-dim);
          font: inherit; font-size: 14px; font-weight: 600;
          cursor: pointer;
          transition: all 0.25s;
        }
        .shop-firm-opt:hover { background: rgba(255,255,255,0.07); color: #fff; }
        .shop-firm-opt.is-active {
          background: linear-gradient(180deg, rgba(90,200,255,0.15) 0%, rgba(90,200,255,0.05) 100%);
          border-color: rgba(90,200,255,0.55);
          color: #fff;
          box-shadow: 0 0 24px rgba(90,200,255,0.20);
        }
        .shop-firm-tradeify.is-active {
          background: linear-gradient(180deg, rgba(79,231,213,0.15) 0%, rgba(79,231,213,0.05) 100%);
          border-color: rgba(79,231,213,0.55);
          box-shadow: 0 0 24px rgba(79,231,213,0.20);
        }
        .shop-firm-coins {
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          color: var(--blue,#5AC8FF);
          letter-spacing: 0.06em;
        }

        /* ----- Type pills (Growth Plan / Select Daily / EOD / Intraday / etc) ----- */
        .shop-type-pills {
          display: flex; flex-wrap: wrap; gap: 8px;
          padding: 4px;
          border-radius: 14px;
          background: rgba(255,255,255,0.02);
          border: 1px solid rgba(255,255,255,0.06);
        }
        .shop-type-pill {
          padding: 8px 14px;
          border-radius: 10px;
          background: transparent;
          border: 1px solid transparent;
          color: var(--text-dim);
          font: inherit; font-size: 12.5px; font-weight: 500;
          cursor: pointer;
          transition: all 0.2s;
        }
        .shop-type-pill:hover { background: rgba(255,255,255,0.04); color: #fff; }
        .shop-type-pill.is-active {
          background: rgba(90,200,255,0.14);
          border-color: rgba(90,200,255,0.45);
          color: #fff;
          box-shadow: 0 0 16px rgba(90,200,255,0.18);
        }
        .shop-type-desc {
          margin-top: 8px;
          font-size: 12.5px;
          color: var(--text-faint, rgba(255,255,255,0.45));
          font-style: italic;
        }

        /* ----- Size cards grid ----- */
        .shop-size-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
          gap: 10px;
        }
        .shop-size-card {
          position: relative;
          padding: 16px 14px 14px;
          border-radius: 14px;
          background: rgba(255,255,255,0.03);
          border: 1px solid rgba(255,255,255,0.10);
          color: var(--text-dim);
          font: inherit;
          cursor: pointer;
          text-align: left;
          transition: transform 0.2s, border-color 0.2s, box-shadow 0.3s, background 0.2s;
        }
        .shop-size-card:hover {
          transform: translateY(-2px);
          background: rgba(255,255,255,0.05);
          border-color: rgba(255,255,255,0.20);
        }
        .shop-size-card.is-selected {
          background: linear-gradient(180deg, rgba(90,200,255,0.16) 0%, rgba(90,200,255,0.04) 100%);
          border-color: var(--blue, #5AC8FF);
          box-shadow: 0 0 28px rgba(90,200,255,0.30), inset 0 1px 0 rgba(255,255,255,0.08);
          color: #fff;
        }
        .shop-size-name {
          font-size: 18px;
          font-weight: 800;
          letter-spacing: -0.02em;
          color: #fff;
          line-height: 1;
        }
        .shop-size-price {
          margin-top: 6px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 13px;
          color: var(--gold, #FFCB52);
          font-weight: 600;
        }
        .shop-size-coins {
          margin-top: 8px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          color: var(--blue, #5AC8FF);
          letter-spacing: 0.04em;
        }
        .shop-coin-icn-sm { font-size: 11px; margin-right: 2px; }
        .shop-size-check {
          position: absolute;
          top: 10px; right: 10px;
          width: 22px; height: 22px;
          border-radius: 50%;
          background: var(--blue, #5AC8FF);
          color: #050505;
          display: grid; place-items: center;
          box-shadow: 0 0 14px rgba(90,200,255,0.50);
        }

        /* ----- Estimate banner ----- */
        .shop-estimate {
          padding: 18px 22px;
          border-radius: 14px;
          background: linear-gradient(180deg, rgba(90,200,255,0.06) 0%, rgba(10,10,12,0.5) 100%);
          border: 1px dashed rgba(90,200,255,0.30);
          transition: border-color 0.3s, background 0.3s;
        }
        .shop-estimate.is-ready {
          border-style: solid;
          border-color: rgba(90,200,255,0.50);
          background: linear-gradient(180deg, rgba(90,200,255,0.12) 0%, rgba(10,10,12,0.6) 100%);
          box-shadow: 0 0 28px rgba(90,200,255,0.16);
        }
        .shop-est-label {
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          letter-spacing: 0.18em;
          color: rgba(255,255,255,0.55);
        }
        .shop-est-main {
          display: flex; align-items: baseline; gap: 6px;
          margin-top: 6px;
          line-height: 1;
        }
        .shop-est-num {
          font-size: 32px;
          font-weight: 800;
          letter-spacing: -0.02em;
          background: linear-gradient(180deg, #fff 0%, var(--blue,#5AC8FF) 100%);
          -webkit-background-clip: text; background-clip: text;
          color: transparent;
        }
        .shop-est-suf {
          font-family: 'JetBrains Mono', monospace;
          font-size: 12px;
          color: var(--blue,#5AC8FF);
          font-weight: 700;
        }
        .shop-est-detail {
          margin-top: 6px;
          font-size: 11.5px;
          color: var(--text-faint, rgba(255,255,255,0.45));
          font-family: 'JetBrains Mono', monospace;
          letter-spacing: 0.02em;
        }
        .shop-est-empty {
          margin-top: 6px;
          font-size: 13px;
          color: var(--text-mute);
        }

        .shop-file {
          padding: 10px;
          border-radius: 10px;
          background: rgba(0,0,0,0.45);
          border: 1px dashed rgba(255,255,255,0.18);
          color: var(--text-dim);
          font: inherit;
          font-size: 13px;
        }
        .shop-file::-webkit-file-upload-button {
          margin-right: 12px;
          padding: 6px 14px;
          border-radius: 8px;
          background: var(--blue,#5AC8FF);
          color: #050505;
          border: none;
          font-weight: 700;
          cursor: pointer;
        }
        .shop-file-meta { font-size: 12px; color: var(--text-mute); margin-top: 4px; }
        .shop-file-hint {
          font-size: 11.5px;
          color: var(--text-faint, rgba(255,255,255,0.40));
          margin-top: 6px;
          line-height: 1.5;
        }
        .shop-file-hint strong { color: var(--blue, #5AC8FF); }

        .shop-submit-row {
          display: flex; justify-content: space-between; align-items: center;
          gap: 14px; flex-wrap: wrap; margin-top: 4px;
        }
        .shop-expect {
          font-size: 13px;
          color: var(--text-dim);
        }
        .shop-expect strong { color: var(--blue,#5AC8FF); font-weight: 700; }

        .shop-msg { padding: 12px 14px; border-radius: 10px; font-size: 13.5px; line-height: 1.5; }
        .shop-err { background: rgba(255,80,80,0.08); border: 1px solid rgba(255,80,80,0.25); color: #ff9090; }
        .shop-ok  { background: rgba(90,200,255,0.08); border: 1px solid rgba(90,200,255,0.30); color: var(--blue,#5AC8FF); }
      `}</style>
    </section>
  );
};

// ===== MY ACTIVITY =====
const ShopActivity = ({ user, refreshKey }) => {
  const [proofs, setProofs] = React.useState([]);
  const [orders, setOrders] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [tab, setTab] = React.useState('proofs');

  React.useEffect(() => {
    if (!user || !window.sb) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      setLoading(true);
      const [p, o] = await Promise.all([
        window.sb.from('coin_proofs').select('*').eq('user_id', user.id).order('created_at', { ascending: false }).limit(20),
        window.sb.from('shop_orders').select('*').eq('user_id', user.id).order('created_at', { ascending: false }).limit(20),
      ]);
      if (cancelled) return;
      setProofs(p.data || []);
      setOrders(o.data || []);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [user, refreshKey]);

  if (!user) return null;

  const statusTag = (s) => {
    if (s === 'pending')   return <span className="tag gold">PENDING REVIEW</span>;
    if (s === 'accepted')  return <span className="tag acid">ACCEPTED</span>;
    if (s === 'rejected')  return <span className="tag rose">REJECTED</span>;
    if (s === 'completed') return <span className="tag acid">COMPLETED</span>;
    if (s === 'cancelled') return <span className="tag rose">CANCELLED</span>;
    return <span className="tag">{s}</span>;
  };

  return (
    <section style={{ paddingTop: 60, paddingBottom: 80 }}>
      <div className="container">
        <SectionHeader
          eyebrow="MY ACTIVITY"
          title="Istoricul tău."
          subtitle="Toate dovezile încărcate și recompensele răscumpărate." />

        <div className="shop-activity-tabs">
          <button className={`shop-tab ${tab === 'proofs' ? 'is-active' : ''}`} onClick={() => setTab('proofs')}>
            <Icon name="upload" size={14}/> Dovezi încărcate ({proofs.length})
          </button>
          <button className={`shop-tab ${tab === 'orders' ? 'is-active' : ''}`} onClick={() => setTab('orders')}>
            <Icon name="gift" size={14}/> Recompense ({orders.length})
          </button>
        </div>

        {loading ? (
          <div className="card card-pad-lg" style={{ textAlign:'center', color:'var(--text-mute)' }}>Loading…</div>
        ) : tab === 'proofs' ? (
          proofs.length === 0 ? (
            <div className="card card-pad-lg" style={{ textAlign:'center', color:'var(--text-mute)' }}>
              Nu ai încă dovezi încărcate. Folosește formularul de mai sus.
            </div>
          ) : (
            <div className="col" style={{ gap: 12 }}>
              {proofs.map(p => (
                <div key={p.id} className="card card-pad-lg shop-activity-row">
                  <div className="shop-activity-left">
                    <div className="row" style={{ gap: 10, alignItems:'center' }}>
                      <span className={`tag ${p.firm === 'apex' ? 'blue' : 'cyan'}`}>{p.firm.toUpperCase()}</span>
                      {statusTag(p.status)}
                    </div>
                    <h4 style={{ marginTop: 10, fontSize: 16 }}>{p.account_type}</h4>
                    <p style={{ marginTop: 4, fontSize: 13, color: 'var(--text-mute)' }}>
                      ${p.amount || '—'} · {new Date(p.created_at).toLocaleString('ro-RO')}
                    </p>
                    {p.admin_note && (
                      <p style={{ marginTop: 8, fontSize: 12.5, color: 'var(--text-dim)', fontStyle:'italic' }}>
                        Notă admin: {p.admin_note}
                      </p>
                    )}
                  </div>
                  <div className="shop-activity-right">
                    {p.status === 'accepted' && (
                      <div className="shop-activity-coin">
                        +{fmtCoins(p.coins_awarded)} <span>TC</span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )
        ) : (
          orders.length === 0 ? (
            <div className="card card-pad-lg" style={{ textAlign:'center', color:'var(--text-mute)' }}>
              Nu ai încă recompense răscumpărate.
            </div>
          ) : (
            <div className="col" style={{ gap: 12 }}>
              {orders.map(o => (
                <div key={o.id} className="card card-pad-lg shop-activity-row">
                  <div className="shop-activity-left">
                    <div className="row" style={{ gap: 10, alignItems:'center' }}>
                      <span className="tag blue">{o.reward_id.toUpperCase()}</span>
                      {statusTag(o.status)}
                    </div>
                    <h4 style={{ marginTop: 10, fontSize: 16 }}>{o.reward_name}</h4>
                    <p style={{ marginTop: 4, fontSize: 13, color: 'var(--text-mute)' }}>
                      {new Date(o.created_at).toLocaleString('ro-RO')}
                      {o.completed_at && <> · finalizat {new Date(o.completed_at).toLocaleDateString('ro-RO')}</>}
                    </p>
                    {o.admin_note && (
                      <p style={{ marginTop: 8, fontSize: 12.5, color: 'var(--text-dim)', fontStyle:'italic' }}>
                        Notă admin: {o.admin_note}
                      </p>
                    )}
                  </div>
                  <div className="shop-activity-right">
                    <div className="shop-activity-coin shop-activity-spent">
                      −{fmtCoins(o.coin_cost)} <span>TC</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )
        )}
      </div>

      <style>{`
        .shop-activity-tabs {
          display: flex; gap: 6px; padding: 6px;
          border-radius: 999px;
          background: rgba(255,255,255,0.03);
          border: 1px solid var(--line);
          margin: 0 0 24px;
          width: fit-content;
        }
        .shop-tab {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 9px 16px;
          border-radius: 999px;
          background: transparent;
          border: none;
          color: var(--text-dim);
          font: inherit; font-size: 13px; font-weight: 500;
          cursor: pointer;
        }
        .shop-tab:hover { color: #fff; background: rgba(255,255,255,0.04); }
        .shop-tab.is-active {
          color: #050505;
          background: var(--blue,#5AC8FF);
          box-shadow: 0 6px 20px rgba(90,200,255,0.30);
        }
        .shop-activity-row {
          display: flex; justify-content: space-between; align-items: center;
          gap: 16px;
          background: linear-gradient(180deg, rgba(90,200,255,0.03) 0%, rgba(10,10,12,0.85) 100%);
          border: 1px solid rgba(90,200,255,0.15);
        }
        .shop-activity-right { text-align: right; }
        .shop-activity-coin {
          font-family: 'JetBrains Mono', monospace;
          font-size: 22px;
          font-weight: 800;
          color: var(--acid,#B7FF1A);
          letter-spacing: -0.01em;
        }
        .shop-activity-coin span {
          font-size: 11px;
          color: var(--text-mute);
          margin-left: 3px;
        }
        .shop-activity-spent { color: var(--rose, #FB7185); }
      `}</style>
    </section>
  );
};

// ===== CONFIRM MODAL (pre-redeem) =====
const ShopConfirmModal = ({ reward, balance, onConfirm, onCancel }) => {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onCancel(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onCancel]);

  const remaining = balance - reward.cost;
  return (
    <div className="shop-conf-overlay" onClick={onCancel}>
      <div className="shop-conf-card" onClick={(e) => e.stopPropagation()}>
        <button className="shop-conf-close" onClick={onCancel}><Icon name="x" size={18}/></button>

        <div className="shop-conf-eyebrow">
          <span className="dot" style={{background:'var(--blue,#5AC8FF)'}}/>
          CONFIRMARE ACHIZIȚIE
        </div>
        <h3 className="shop-conf-title">Confirmi răscumpărarea?</h3>

        <div className="shop-conf-reward-box">
          <div className="shop-conf-reward-label">RECOMPENSĂ</div>
          <div className="shop-conf-reward-name">{reward.title}</div>
          <div className="shop-conf-reward-cost">
            <span className="shop-coin-icn">🪙</span>
            <span className="shop-conf-cost-num">{fmtCoins(reward.cost)}</span>
            <span className="shop-conf-cost-suffix">TC</span>
          </div>
        </div>

        <div className="shop-conf-balance">
          <div className="shop-conf-bal-row">
            <span>Sold curent</span>
            <strong>{fmtCoins(balance)} TC</strong>
          </div>
          <div className="shop-conf-bal-row">
            <span>După achiziție</span>
            <strong className="shop-conf-bal-after">{fmtCoins(remaining)} TC</strong>
          </div>
        </div>

        <div className="shop-conf-actions">
          <button type="button" className="shop-conf-btn shop-conf-btn-ghost" onClick={onCancel}>
            Anulează
          </button>
          <button type="button" className="shop-conf-btn shop-conf-btn-acid" onClick={onConfirm}>
            Confirmă <span style={{marginLeft:5, fontWeight:800}}>→</span>
          </button>
        </div>
      </div>

      <style>{`
        .shop-conf-overlay {
          position: fixed; inset: 0; z-index: 110;
          background: rgba(0,0,0,0.80);
          backdrop-filter: blur(10px);
          display: grid; place-items: center;
          padding: 24px;
          animation: shop-conf-fade 0.25s ease;
        }
        @keyframes shop-conf-fade { from { opacity: 0; } to { opacity: 1; } }
        .shop-conf-card {
          position: relative;
          width: 100%; max-width: 420px;
          padding: 32px 28px 26px;
          border-radius: 22px;
          background:
            radial-gradient(ellipse at top, rgba(90,200,255,0.16) 0%, transparent 60%),
            linear-gradient(180deg, rgba(18,24,32,0.96) 0%, rgba(8,10,14,0.98) 100%);
          border: 1px solid rgba(90,200,255,0.30);
          box-shadow: 0 36px 80px rgba(0,0,0,0.70), 0 0 60px rgba(90,200,255,0.15);
          animation: shop-conf-pop 0.45s cubic-bezier(0.22, 1, 0.36, 1);
        }
        @keyframes shop-conf-pop {
          from { opacity: 0; transform: translateY(20px) scale(0.95); }
          to   { opacity: 1; transform: translateY(0) scale(1); }
        }
        .shop-conf-close {
          position: absolute; top: 14px; right: 14px;
          width: 32px; height: 32px; border-radius: 50%;
          background: rgba(255,255,255,0.06);
          border: 1px solid rgba(255,255,255,0.10);
          color: rgba(255,255,255,0.6);
          cursor: pointer;
          display: grid; place-items: center;
          transition: all 0.2s;
        }
        .shop-conf-close:hover { background: rgba(255,255,255,0.12); color: #fff; }
        .shop-conf-eyebrow {
          display: inline-flex; align-items: center; gap: 6px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          letter-spacing: 0.18em;
          color: var(--blue, #5AC8FF);
        }
        .shop-conf-title {
          margin: 10px 0 18px;
          font-size: 22px;
          font-weight: 700;
          letter-spacing: -0.015em;
        }

        .shop-conf-reward-box {
          padding: 16px 18px;
          border-radius: 14px;
          background: rgba(90,200,255,0.08);
          border: 1px solid rgba(90,200,255,0.30);
          margin-bottom: 14px;
        }
        .shop-conf-reward-label {
          font-family: 'JetBrains Mono', monospace;
          font-size: 9.5px;
          letter-spacing: 0.18em;
          color: rgba(255,255,255,0.50);
        }
        .shop-conf-reward-name {
          margin-top: 4px;
          font-size: 17px;
          font-weight: 700;
          letter-spacing: -0.01em;
          color: #fff;
        }
        .shop-conf-reward-cost {
          margin-top: 8px;
          display: flex; align-items: baseline; gap: 5px;
          line-height: 1;
        }
        .shop-conf-cost-num {
          font-size: 24px;
          font-weight: 800;
          color: var(--gold, #FFCB52);
          letter-spacing: -0.02em;
        }
        .shop-conf-cost-suffix {
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          color: var(--text-mute);
        }

        .shop-conf-balance {
          padding: 14px 16px;
          border-radius: 12px;
          background: rgba(255,255,255,0.03);
          border: 1px solid rgba(255,255,255,0.08);
          font-size: 13px;
        }
        .shop-conf-bal-row {
          display: flex; justify-content: space-between;
          padding: 4px 0;
          color: var(--text-dim);
        }
        .shop-conf-bal-row strong { color: #fff; font-family: 'JetBrains Mono', monospace; }
        .shop-conf-bal-after { color: var(--acid, #B7FF1A) !important; }

        .shop-conf-actions {
          display: flex; gap: 10px;
          margin-top: 22px;
        }
        .shop-conf-btn {
          flex: 1;
          padding: 12px 18px;
          border-radius: 12px;
          font: inherit; font-size: 13.5px; font-weight: 700;
          border: 1px solid transparent;
          cursor: pointer;
          transition: transform 0.2s, box-shadow 0.25s, background 0.2s, color 0.2s;
        }
        .shop-conf-btn-ghost {
          background: rgba(255,255,255,0.04);
          color: rgba(255,255,255,0.7);
          border-color: rgba(255,255,255,0.10);
        }
        .shop-conf-btn-ghost:hover {
          background: rgba(255,255,255,0.08); color: #fff;
        }
        .shop-conf-btn-acid {
          background: linear-gradient(180deg, #C8FF35 0%, #A8F00B 100%);
          color: #050505;
          box-shadow: inset 0 1px 0 rgba(255,255,255,0.4), 0 8px 22px rgba(183,255,26,0.35);
        }
        .shop-conf-btn-acid:hover {
          transform: translateY(-1px);
          box-shadow: inset 0 1px 0 rgba(255,255,255,0.5), 0 12px 28px rgba(183,255,26,0.45);
        }
      `}</style>
    </div>
  );
};

// ===== SUCCESS MODAL =====
const ShopSuccessModal = ({ reward, onClose }) => {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);
  if (!reward) return null;
  return (
    <div className="shop-succ-overlay" onClick={onClose}>
      <div className="shop-succ-card" onClick={(e) => e.stopPropagation()}>
        <button className="shop-succ-close" onClick={onClose} aria-label="Close">
          <Icon name="x" size={18}/>
        </button>

        <div className="shop-succ-confetti">
          {Array.from({ length: 14 }).map((_, i) => <span key={i} className={`shop-conf shop-conf-${i % 4}`} />)}
        </div>

        <div className="shop-succ-icon">
          <div className="shop-succ-icon-bg" />
          <Icon name="check" size={42} stroke={3}/>
        </div>

        <div className="shop-succ-eyebrow">
          <span className="dot" style={{background:'var(--blue,#5AC8FF)'}}/>
          ACHIZIȚIE CONFIRMATĂ
        </div>
        <h2 className="shop-succ-title">Felicitări! 🎉</h2>
        <p className="shop-succ-sub">
          Ai achiziționat cu succes
        </p>
        <div className="shop-succ-reward">{reward.title}</div>
        <div className="shop-succ-cost">
          <span className="shop-coin-icn">🪙</span>
          <span className="shop-succ-cost-num">{fmtCoins(reward.cost)}</span>
          <span className="shop-succ-cost-suffix">TC</span>
        </div>

        <div className="shop-succ-message">
          O să fii contactat <strong>foarte curând</strong> pentru revendicare.
          Verifică emailul tău (inclusiv Spam / Promoții).
        </div>

        <button className="shop-succ-btn" onClick={onClose}>
          Continuă <span style={{ marginLeft: 6, fontWeight: 800 }}>→</span>
        </button>
      </div>

      <style>{`
        .shop-succ-overlay {
          position: fixed; inset: 0; z-index: 120;
          background: rgba(0,0,0,0.82);
          backdrop-filter: blur(12px);
          display: grid; place-items: center;
          padding: 24px;
          animation: shop-succ-fade 0.3s ease;
        }
        @keyframes shop-succ-fade { from { opacity: 0; } to { opacity: 1; } }

        .shop-succ-card {
          position: relative;
          width: 100%; max-width: 440px;
          padding: 38px 34px 30px;
          border-radius: 24px;
          background:
            radial-gradient(ellipse at top, rgba(90,200,255,0.20) 0%, transparent 60%),
            linear-gradient(180deg, rgba(20,28,40,0.95) 0%, rgba(8,10,14,0.98) 100%);
          border: 1px solid rgba(90,200,255,0.40);
          box-shadow:
            0 40px 100px rgba(0,0,0,0.7),
            0 0 80px rgba(90,200,255,0.25),
            inset 0 1px 0 rgba(255,255,255,0.08);
          text-align: center;
          overflow: hidden;
          animation: shop-succ-pop 0.55s cubic-bezier(0.22, 1, 0.36, 1);
        }
        @keyframes shop-succ-pop {
          0%   { opacity: 0; transform: translateY(20px) scale(0.92); }
          60%  { transform: translateY(-4px) scale(1.02); }
          100% { opacity: 1; transform: translateY(0) scale(1); }
        }

        .shop-succ-close {
          position: absolute; top: 14px; right: 14px;
          width: 32px; height: 32px; border-radius: 50%;
          background: rgba(255,255,255,0.06);
          border: 1px solid rgba(255,255,255,0.10);
          color: rgba(255,255,255,0.6);
          cursor: pointer;
          display: grid; place-items: center;
          transition: all 0.2s;
        }
        .shop-succ-close:hover {
          background: rgba(255,255,255,0.12); color: #fff;
        }

        .shop-succ-icon {
          position: relative;
          width: 84px; height: 84px; margin: 0 auto 22px;
          border-radius: 50%;
          display: grid; place-items: center;
          color: #050505;
          background: linear-gradient(180deg, #B7FF1A 0%, #8FE000 100%);
          box-shadow:
            0 12px 40px rgba(183,255,26,0.45),
            0 0 60px rgba(183,255,26,0.30),
            inset 0 2px 0 rgba(255,255,255,0.45);
          animation: shop-succ-icon-pulse 2.2s ease-in-out infinite;
          z-index: 2;
        }
        .shop-succ-icon-bg {
          position: absolute; inset: -12px;
          border-radius: 50%;
          background: radial-gradient(circle, rgba(183,255,26,0.25) 0%, transparent 70%);
          z-index: -1;
          animation: shop-succ-ring 2.2s ease-in-out infinite;
        }
        @keyframes shop-succ-icon-pulse {
          0%,100% { transform: scale(1); }
          50%     { transform: scale(1.06); }
        }
        @keyframes shop-succ-ring {
          0%,100% { opacity: 0.6; transform: scale(1); }
          50%     { opacity: 1; transform: scale(1.2); }
        }

        .shop-succ-eyebrow {
          display: inline-flex; align-items: center; gap: 6px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          letter-spacing: 0.18em;
          color: var(--blue, #5AC8FF);
        }
        .shop-succ-title {
          margin: 12px 0 8px;
          font-size: 30px;
          font-weight: 800;
          letter-spacing: -0.02em;
          background: linear-gradient(180deg, #fff 0%, #B2E8FF 100%);
          -webkit-background-clip: text; background-clip: text;
          color: transparent;
        }
        .shop-succ-sub {
          font-size: 13.5px;
          color: rgba(255,255,255,0.6);
          margin-bottom: 14px;
        }
        .shop-succ-reward {
          font-size: 19px;
          font-weight: 700;
          color: #fff;
          letter-spacing: -0.01em;
          padding: 12px 18px;
          border-radius: 14px;
          background: rgba(90,200,255,0.10);
          border: 1px solid rgba(90,200,255,0.32);
        }
        .shop-succ-cost {
          margin-top: 14px;
          display: inline-flex; align-items: baseline; gap: 6px;
          line-height: 1;
        }
        .shop-succ-cost-num {
          font-size: 28px;
          font-weight: 800;
          color: var(--gold, #FFCB52);
          letter-spacing: -0.02em;
        }
        .shop-succ-cost-suffix {
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          color: rgba(255,203,82,0.7);
        }

        .shop-succ-message {
          margin-top: 20px;
          padding: 14px 16px;
          border-radius: 12px;
          background: rgba(255,255,255,0.04);
          border: 1px dashed rgba(255,255,255,0.12);
          font-size: 13px;
          line-height: 1.55;
          color: var(--text-dim, rgba(255,255,255,0.75));
        }
        .shop-succ-message strong { color: var(--blue, #5AC8FF); font-weight: 700; }

        .shop-succ-btn {
          margin-top: 22px;
          width: 100%;
          padding: 13px 22px;
          border-radius: 12px;
          background: linear-gradient(180deg, #C8FF35 0%, #A8F00B 100%);
          color: #050505;
          font: inherit;
          font-size: 14px;
          font-weight: 700;
          letter-spacing: 0.01em;
          border: 1px solid rgba(0,0,0,0.18);
          cursor: pointer;
          box-shadow:
            inset 0 1px 0 rgba(255,255,255,0.45),
            0 10px 28px rgba(183,255,26,0.40),
            0 0 36px rgba(183,255,26,0.30);
          transition: transform 0.2s, box-shadow 0.3s;
        }
        .shop-succ-btn:hover {
          transform: translateY(-2px);
          box-shadow:
            inset 0 1px 0 rgba(255,255,255,0.55),
            0 14px 36px rgba(183,255,26,0.50),
            0 0 44px rgba(183,255,26,0.45);
        }

        /* Confetti */
        .shop-succ-confetti {
          position: absolute; inset: 0; pointer-events: none;
          overflow: hidden;
          z-index: 0;
        }
        .shop-conf {
          position: absolute;
          width: 7px; height: 12px;
          opacity: 0;
          animation: shop-conf-fall 2.2s ease-out forwards;
        }
        .shop-conf-0 { background: #B7FF1A; }
        .shop-conf-1 { background: #5AC8FF; }
        .shop-conf-2 { background: #FFCB52; }
        .shop-conf-3 { background: #FB7185; }
        ${Array.from({length: 14}).map((_, i) => `.shop-conf:nth-child(${i+1}) {
          left: ${(i * 7 + 5) % 95}%;
          top: -10px;
          animation-delay: ${i * 80}ms;
          transform: rotate(${(i*47) % 360}deg);
        }`).join('\n')}
        @keyframes shop-conf-fall {
          0%   { opacity: 1; transform: translateY(0) rotate(0deg); }
          100% { opacity: 0; transform: translateY(420px) rotate(720deg); }
        }
      `}</style>
    </div>
  );
};

// ===== MAIN PAGE =====
const ShopPage = ({ user, onLogin, onNav }) => {
  const [balance, setBalance] = React.useState(0);
  const [refreshKey, setRefreshKey] = React.useState(0);
  const [busyId, setBusyId] = React.useState(null);
  const [redeemMsg, setRedeemMsg] = React.useState('');
  const [successReward, setSuccessReward] = React.useState(null);
  const [confirmReward, setConfirmReward] = React.useState(null); // shows pre-redeem modal

  // Load balance
  const loadBalance = React.useCallback(async () => {
    if (!user || !window.sb) return;
    const { data } = await window.sb.from('profiles').select('tyrone_coins').eq('id', user.id).maybeSingle();
    setBalance(data?.tyrone_coins || 0);
  }, [user]);

  React.useEffect(() => { loadBalance(); }, [loadBalance, refreshKey]);

  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  // Step 1: click Răscumpără → open in-app confirm modal (not native confirm)
  const handleRedeem = (reward) => {
    if (!user) { onLogin?.(); return; }
    if (balance < reward.cost) return;
    setConfirmReward(reward);
  };

  // Step 2: user confirms in the modal → actually place the order
  const confirmRedeem = async () => {
    if (!confirmReward) return;
    const reward = confirmReward;
    setConfirmReward(null);
    setBusyId(reward.id);
    setRedeemMsg('');
    try {
      const { error } = await window.sb.rpc('place_shop_order', {
        p_reward_id:   reward.id,
        p_reward_name: reward.title,
        p_coin_cost:   reward.cost,
      });
      if (error) throw error;
      setSuccessReward(reward);
      setRefreshKey(k => k + 1);
      window.dispatchEvent(new CustomEvent('tyrone-coins-changed'));
    } catch (e) {
      setRedeemMsg(`Eroare: ${e.message || 'încercare eșuată'}`);
      setTimeout(() => setRedeemMsg(''), 5000);
    } finally {
      setBusyId(null);
    }
  };

  return (
    <>
      <ShopHero user={user} balance={balance} onScrollTo={scrollTo} />
      <ShopHowItWorks />
      <ShopRewards user={user} balance={balance} onRedeem={handleRedeem} busyId={busyId} />
      {redeemMsg && (
        <div className="shop-redeem-toast">{redeemMsg}</div>
      )}
      <ShopUpload user={user} onSubmitted={() => setRefreshKey(k => k + 1)} />
      <ShopActivity user={user} refreshKey={refreshKey} />

      {confirmReward && (
        <ShopConfirmModal
          reward={confirmReward}
          balance={balance}
          onConfirm={confirmRedeem}
          onCancel={() => setConfirmReward(null)}
        />
      )}

      {successReward && (
        <ShopSuccessModal
          reward={successReward}
          onClose={() => setSuccessReward(null)}
        />
      )}

      <style>{`
        .shop-redeem-toast {
          position: fixed;
          left: 50%; bottom: 30px;
          transform: translateX(-50%);
          padding: 14px 22px;
          border-radius: 999px;
          background: rgba(10,10,12,0.95);
          border: 1px solid rgba(90,200,255,0.45);
          box-shadow: 0 12px 40px rgba(0,0,0,0.6), 0 0 30px rgba(90,200,255,0.20);
          color: var(--blue,#5AC8FF);
          font-size: 14px;
          font-weight: 500;
          z-index: 90;
          animation: shop-toast-in 0.4s cubic-bezier(0.22, 1, 0.36, 1);
        }
        @keyframes shop-toast-in {
          from { opacity: 0; transform: translateX(-50%) translateY(20px); }
          to   { opacity: 1; transform: translateX(-50%) translateY(0); }
        }
      `}</style>
    </>
  );
};

Object.assign(window, { ShopPage });
