// shop.jsx — Gift Shop (4U Points)

const { useState: useStateS } = React;

const PRODUCTS = [
  { id: 1, cat: 'Tehnologie', name: 'iPhone 15 Pro 256GB', pts: 850, stock: 'Stoc limitat', g1: '#1f2937', g2: '#52F20F' },
  { id: 2, cat: 'Tehnologie', name: 'AirPods Pro 2', pts: 220, stock: null, g1: '#0E0E0E', g2: '#FFD700' },
  { id: 3, cat: 'Călătorii', name: 'Weekend Maldive', pts: 1200, stock: 'Doar 3', g1: '#FFD700', g2: '#52F20F', tag: 'Premium' },
  { id: 4, cat: 'Modă', name: 'Geantă Louis Vuitton', pts: 680, stock: null, g1: '#3a2410', g2: '#FFD700' },
  { id: 5, cat: 'Tehnologie', name: 'PS5 Slim', pts: 380, stock: null, g1: '#101820', g2: '#52F20F', tag: 'Nou' },
  { id: 6, cat: 'Cosmetice', name: 'Pachet Dior Premium', pts: 145, stock: null, g1: '#1a0f0c', g2: '#FFD700' },
  { id: 7, cat: 'Experiențe', name: 'Cină Michelin București', pts: 90, stock: null, g1: '#0E0E0E', g2: '#52F20F' },
  { id: 8, cat: 'Modă', name: 'Sneakers Off-White', pts: 240, stock: null, g1: '#1a1a1a', g2: '#FFD700' },
  { id: 9, cat: 'Tehnologie', name: 'MacBook Air M3', pts: 1450, stock: 'Doar 1', g1: '#0E0E0E', g2: '#52F20F', tag: 'Top' },
  { id: 10, cat: 'Călătorii', name: 'City Break Roma', pts: 480, stock: null, g1: '#3a1f1a', g2: '#FFD700' },
  { id: 11, cat: 'Cosmetice', name: 'Set Charlotte Tilbury', pts: 65, stock: null, g1: '#2a0f1a', g2: '#FFD700' },
  { id: 12, cat: 'Experiențe', name: 'Concert Untold VIP', pts: 350, stock: 'Stoc limitat', g1: '#1a0a2a', g2: '#52F20F' },
];

function ShopPage({ onNav, user }) {
  const [cat, setCat] = useStateS('Toate');
  const [sort, setSort] = useStateS('Recente');
  const [cart, setCart] = useStateS([]);
  const [cartOpen, setCartOpen] = useStateS(false);
  const [detail, setDetail] = useStateS(null);
  const [Toast, toast] = useToast();
  const points = 1247;

  const cats = ['Toate', 'Tehnologie', 'Modă', 'Călătorii', 'Experiențe', 'Cosmetice'];
  const sortOpts = ['Recente', 'Preț ↑', 'Preț ↓', 'Popularitate'];

  let list = PRODUCTS.filter(p => cat === 'Toate' || p.cat === cat);
  if (sort === 'Preț ↑') list = [...list].sort((a, b) => a.pts - b.pts);
  if (sort === 'Preț ↓') list = [...list].sort((a, b) => b.pts - a.pts);

  const cartTotal = cart.reduce((s, c) => s + c.pts, 0);
  const remaining = points - cartTotal;

  const addToCart = (p) => {
    setCart(c => [...c, p]);
    toast(`${p.name} adăugat în coș`);
    setDetail(null);
    setCartOpen(true);
  };

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh' }}>
      <DashSidebar active="shop" onNav={onNav} user={user} />
      <main style={{ background: 'var(--bg-1)', minHeight: '100vh' }} className="dash-main">
        <div style={{ padding: '32px 48px 24px', borderBottom: '.5px solid var(--line-soft)', position: 'sticky', top: 0, background: 'rgba(14,14,14,0.92)', backdropFilter: 'blur(20px)', zIndex: 10 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24, flexWrap: 'wrap', gap: 16 }}>
            <div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--accent-1)', letterSpacing: '0.15em', marginBottom: 8 }}>● MAGAZIN CADOURI</div>
              <h1 className="display" style={{ fontSize: 40, margin: 0 }}>Răscumpără-ți punctele.</h1>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <div className="card-glass" style={{ padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 14 }}>💎</span>
                <div>
                  <div className="display mono" style={{ fontSize: 18, color: 'var(--accent-1)' }}>{points.toLocaleString('ro-RO')}</div>
                  <div className="mono" style={{ fontSize: 9, color: 'var(--txt-3)' }}>EXP. 19 MAI</div>
                </div>
              </div>
              <button onClick={() => setCartOpen(true)} className="btn btn-primary" style={{ position: 'relative' }}>
                Coș {cart.length > 0 && <span style={{ background: '#0A0A0F', color: 'var(--accent-1)', borderRadius: 999, padding: '2px 8px', fontSize: 11, marginLeft: 4 }}>{cart.length}</span>}
              </button>
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {cats.map(c => (
                <button key={c} onClick={() => setCat(c)} className="btn btn-sm" style={{
                  background: cat === c ? 'var(--accent-1)' : 'transparent',
                  color: cat === c ? '#0A0A0F' : 'var(--txt-2)',
                  border: cat === c ? 'none' : '.5px solid var(--line)',
                  fontWeight: cat === c ? 600 : 400,
                }}>{c}</button>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>SORT</span>
              <select value={sort} onChange={(e) => setSort(e.target.value)} className="input" style={{ width: 'auto', height: 34, fontSize: 13 }}>
                {sortOpts.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
          </div>
        </div>

        <div style={{ padding: '32px 48px 64px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }} className="shop-grid">
            {list.map(p => (
              <ProductCard key={p.id} p={p} onClick={() => setDetail(p)} canAfford={p.pts <= points} />
            ))}
          </div>
        </div>
      </main>

      {/* Detail modal */}
      {detail && (
        <div onClick={() => setDetail(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)', zIndex: 100, display: 'grid', placeItems: 'center', padding: 24 }}>
          <div onClick={(e) => e.stopPropagation()} className="card-glass" style={{ width: '100%', maxWidth: 880, padding: 0, overflow: 'hidden', display: 'grid', gridTemplateColumns: '1fr 1fr', animation: 'pageIn .3s' }} className2="detail-modal">
            <div style={{ background: `linear-gradient(135deg, ${detail.g1}, ${detail.g2})`, minHeight: 480, position: 'relative', overflow: 'hidden' }}>
              <div className="mono" style={{ position: 'absolute', top: 16, left: 16, fontSize: 10, color: 'rgba(255,255,255,.5)' }}>[ {detail.name.toLowerCase()} ]</div>
              <div style={{ position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(135deg, transparent 0 12px, rgba(255,255,255,.04) 12px 13px)' }}/>
            </div>
            <div style={{ padding: 32, display: 'flex', flexDirection: 'column' }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 8 }}>{detail.cat.toUpperCase()}</div>
              <h2 className="display" style={{ fontSize: 28, margin: 0 }}>{detail.name}</h2>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16 }}>
                <div className="display mono" style={{ fontSize: 36, color: 'var(--accent-1)' }}>💎 {detail.pts}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>4U Points</div>
              </div>
              <p style={{ color: 'var(--txt-2)', fontSize: 14, lineHeight: 1.6, marginTop: 24 }}>
                Premiu premium din magazinul 4U. Livrat acasă în maxim 7-10 zile lucrătoare. Garanție producător plus suport dedicat din partea echipei 4U.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 24, fontSize: 13 }}>
                {[['Stoc', detail.stock || 'Disponibil'], ['Livrare', '7-10 zile'], ['Cost livrare', 'Gratuit'], ['Garanție', '24 luni']].map(([k, v]) => (
                  <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderTop: '.5px solid var(--line-soft)' }}>
                    <span style={{ color: 'var(--txt-3)' }}>{k}</span><span>{v}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 'auto', paddingTop: 24, display: 'flex', gap: 8 }}>
                <button onClick={() => setDetail(null)} className="btn btn-glass" style={{ flex: 1 }}>Închide</button>
                <button onClick={() => addToCart(detail)} className="btn btn-primary btn-lg" style={{ flex: 2 }} disabled={detail.pts > points}>
                  {detail.pts > points ? 'Puncte insuficiente' : `Răscumpără pentru ${detail.pts} puncte →`}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Cart panel */}
      {cartOpen && (
        <>
          <div onClick={() => setCartOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100 }}/>
          <aside style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(440px, 100vw)', background: 'var(--bg-1)', borderLeft: '.5px solid var(--line)', zIndex: 101, display: 'flex', flexDirection: 'column', animation: 'slideIn .3s' }}>
            <style>{`@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); }}`}</style>
            <div style={{ padding: 24, borderBottom: '.5px solid var(--line-soft)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div className="display" style={{ fontSize: 22 }}>Coșul tău ({cart.length})</div>
              <button onClick={() => setCartOpen(false)} className="btn btn-ghost btn-sm">✕</button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
              {cart.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '64px 24px', color: 'var(--txt-3)' }}>
                  <div style={{ fontSize: 48, marginBottom: 16, opacity: 0.4 }}>◇</div>
                  <div style={{ fontSize: 14 }}>Coșul tău este gol</div>
                  <div style={{ fontSize: 12, marginTop: 4 }}>Adaugă produse pentru a continua.</div>
                </div>
              ) : cart.map((c, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: '.5px solid var(--line-soft)' }}>
                  <div style={{ width: 56, height: 56, borderRadius: 8, background: `linear-gradient(135deg, ${c.g1}, ${c.g2})`, flexShrink: 0 }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--accent-1)', marginTop: 4 }}>💎 {c.pts}</div>
                  </div>
                  <button onClick={() => setCart(cart.filter((_, k) => k !== i))} className="btn btn-ghost btn-sm">✕</button>
                </div>
              ))}
            </div>
            {cart.length > 0 && (
              <div style={{ padding: 24, borderTop: '.5px solid var(--line-soft)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: 13 }}>
                  <span style={{ color: 'var(--txt-2)' }}>Total puncte</span>
                  <span className="display mono" style={{ color: 'var(--accent-1)' }}>💎 {cartTotal}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, fontSize: 13 }}>
                  <span style={{ color: 'var(--txt-2)' }}>Sold rămas după achiziție</span>
                  <span className="mono" style={{ color: remaining < 0 ? 'var(--error)' : 'var(--txt-1)' }}>{remaining.toLocaleString('ro-RO')}</span>
                </div>
                <button className="btn btn-primary btn-lg" style={{ width: '100%' }} disabled={remaining < 0}
                  onClick={() => { fireConfetti(); toast('Comandă plasată cu succes!'); setCart([]); setTimeout(() => setCartOpen(false), 1200); }}>
                  Finalizează comanda →
                </button>
              </div>
            )}
          </aside>
        </>
      )}

      {Toast}
      <style>{`
        @media (max-width: 1100px) { .shop-grid { grid-template-columns: 1fr 1fr 1fr !important; }}
        @media (max-width: 800px) { .shop-grid { grid-template-columns: 1fr 1fr !important; } .dash-main { padding: 0 !important; }}
        @media (max-width: 500px) { .shop-grid { grid-template-columns: 1fr !important; }}
      `}</style>
    </div>
  );
}

function ProductCard({ p, onClick, canAfford }) {
  return (
    <div onClick={onClick} className="card hov" style={{ padding: 0, cursor: 'pointer', overflow: 'hidden' }}>
      <div style={{ height: 200, background: `linear-gradient(135deg, ${p.g1}, ${p.g2})`, position: 'relative', overflow: 'hidden', transition: 'transform .4s' }}>
        <div style={{ position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(135deg, transparent 0 16px, rgba(255,255,255,.04) 16px 17px)' }}/>
        <div className="mono" style={{ position: 'absolute', bottom: 12, left: 12, fontSize: 9, color: 'rgba(255,255,255,.55)' }}>[ {p.cat.toLowerCase()} ]</div>
        {p.tag && <div style={{ position: 'absolute', top: 12, left: 12, background: 'var(--accent-2)', color: '#0A0A0F', fontSize: 10, fontWeight: 700, padding: '4px 8px', borderRadius: 999 }}>{p.tag}</div>}
        {p.stock && <div className="pill" style={{ position: 'absolute', top: 12, right: 12, fontSize: 10, background: 'rgba(245,158,11,.15)', borderColor: 'rgba(245,158,11,.4)', color: 'var(--warning)' }}>{p.stock}</div>}
      </div>
      <div style={{ padding: 16 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 6 }}>{p.cat.toUpperCase()}</div>
        <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 12, minHeight: 36 }}>{p.name}</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '.5px solid var(--line-soft)', paddingTop: 12 }}>
          <div className="display mono" style={{ fontSize: 18, color: canAfford ? 'var(--accent-1)' : 'var(--txt-3)' }}>💎 {p.pts}</div>
          <span className="mono" style={{ fontSize: 11, color: 'var(--accent-1)' }}>→</span>
        </div>
      </div>
    </div>
  );
}

window.ShopPage = ShopPage;
