// ShopPage.jsx — Anika Williams Design

const SHOP_ITEMS = [
  {
    id: 1, title: 'Type Specimen Print — No. 01', price: '€120', cat: 'Print',
    desc: 'A3 risograph print. Saira Condensed specimen on 300gsm uncoated stock. Edition of 50.',
    edition: '50', sold: 12,
  },
  {
    id: 2, title: 'Studio Monograph Vol. I', price: '€85', cat: 'Publication',
    desc: 'Perfect-bound 128-page documentation of studio work from 2022–2024. Smyth-sewn case binding.',
    edition: '200', sold: 67,
  },
  {
    id: 3, title: 'Identity Archive Zine', price: '€28', cat: 'Publication',
    desc: 'Saddle-stitched A5 zine. 32 pages of identity sketches and process documentation.',
    edition: 'Open', sold: null,
  },
  {
    id: 4, title: 'Type Specimen Print — No. 02', price: '€120', cat: 'Print',
    desc: 'EB Garamond specimen. Letterpress on 270gsm cotton stock. Edition of 30.',
    edition: '30', sold: 30, soldOut: true,
  },
  {
    id: 5, title: 'Studio Tote — Black', price: '€45', cat: 'Object',
    desc: 'Heavy canvas tote. Studio wordmark silkscreened in white. 400gsm cotton duck.',
    edition: 'Open', sold: null,
  },
  {
    id: 6, title: 'Process Print — Grid Study', price: '€95', cat: 'Print',
    desc: 'A2 screen print. Grid and typographic composition. 2-color on 350gsm newsprint.',
    edition: '75', sold: 23,
  },
];

const SHOP_CATS = ['All', 'Print', 'Publication', 'Object'];

function ShopPage({ onNavigate }) {
  const [activeFilter, setActiveFilter] = React.useState('All');
  const [cart, setCart] = React.useState([]);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [added, setAdded] = React.useState(null);

  const filtered = activeFilter === 'All'
    ? SHOP_ITEMS
    : SHOP_ITEMS.filter(i => i.cat === activeFilter);

  const addToCart = (item) => {
    if (item.soldOut) return;
    setCart(prev => {
      const existing = prev.find(c => c.id === item.id);
      if (existing) return prev.map(c => c.id === item.id ? { ...c, qty: c.qty + 1 } : c);
      return [...prev, { ...item, qty: 1 }];
    });
    setAdded(item.id);
    setTimeout(() => setAdded(null), 1500);
  };

  const cartTotal = cart.reduce((sum, c) => {
    const price = parseFloat(c.price.replace('€', ''));
    return sum + price * c.qty;
  }, 0);

  const shopGrads = [
    'linear-gradient(135deg, #111 0%, #2a2a2a 100%)',
    'linear-gradient(160deg, #1c1c1c 0%, #0a0a0a 100%)',
    'linear-gradient(135deg, #0e0e0e 0%, #1e1e1e 100%)',
    'linear-gradient(120deg, #1a1a1a 0%, #0d0d0d 100%)',
    'linear-gradient(155deg, #181818 0%, #0f0f0f 100%)',
    'linear-gradient(135deg, #222 0%, #111 100%)',
  ];

  return (
    <div style={{ background: '#000', minHeight: '100vh', paddingTop: 68 }}>

      {/* Page Header */}
      <section style={{ padding: '80px 56px 64px', borderBottom: '1px solid #262626' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 10, letterSpacing: '3px', textTransform: 'uppercase',
            color: '#444', marginBottom: 20,
          }}>Shop</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
            <h1 style={{
              fontFamily: "'sedgwick-ave-display', sans-serif",
              fontSize: 'clamp(48px, 6vw, 80px)', fontWeight: 400,
              letterSpacing: '3px', textTransform: 'uppercase',
              color: '#F2EADB', lineHeight: 1.0, margin: 0,
            }}>Studio Editions</h1>
            {/* Cart button */}
            <button onClick={() => setCartOpen(true)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              background: cart.length > 0 ? '#F2EADB' : 'transparent',
              color: cart.length > 0 ? '#000' : '#F2EADB',
              border: '1px solid #F2EADB', borderRadius: 9999,
              padding: '11px 28px', minHeight: 44,
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 11, letterSpacing: '2px', textTransform: 'uppercase',
              cursor: 'pointer', transition: 'all 200ms',
            }}>
              Cart
              {cart.length > 0 && (
                <span style={{
                  background: cart.length > 0 ? '#000' : '#F2EADB',
                  color: cart.length > 0 ? '#F2EADB' : '#000',
                  borderRadius: '50%', width: 20, height: 20,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: "'JetBrains Mono', monospace",
                  fontSize: 10,
                }}>{cart.reduce((s, c) => s + c.qty, 0)}</span>
              )}
            </button>
          </div>
        </div>
      </section>

      {/* Filter Bar */}
      <section style={{
        padding: '0 56px', borderBottom: '1px solid #262626',
        background: '#000', position: 'sticky', top: 68, zIndex: 50,
      }}>
        <div style={{
          maxWidth: 1280, margin: '0 auto',
          display: 'flex', alignItems: 'center', height: 52,
        }}>
          {SHOP_CATS.map(c => (
            <ShopFilterBtn key={c} label={c} active={activeFilter === c} onClick={() => setActiveFilter(c)} />
          ))}
        </div>
      </section>

      {/* Products Grid */}
      <section style={{ padding: '64px 56px 120px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 1, background: '#262626',
          }}>
            {filtered.map((item, i) => (
              <ShopCard
                key={item.id} item={item}
                grad={shopGrads[i % shopGrads.length]}
                onAdd={() => addToCart(item)}
                justAdded={added === item.id}
              />
            ))}
          </div>
        </div>
      </section>

      {/* Cart Drawer */}
      {cartOpen && (
        <CartDrawer
          cart={cart}
          total={cartTotal}
          onClose={() => setCartOpen(false)}
          onRemove={(id) => setCart(prev => prev.filter(c => c.id !== id))}
          onQty={(id, delta) => setCart(prev =>
            prev.map(c => c.id === id ? { ...c, qty: Math.max(1, c.qty + delta) } : c)
          )}
        />
      )}

      <AWFooter onNavigate={onNavigate} />
    </div>
  );
}

function ShopFilterBtn({ label, active, onClick }) {
  const [hov, setHov] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        background: 'transparent', border: 'none',
        borderBottom: active ? '2px solid #F2EADB' : '2px solid transparent',
        padding: '0 16px', height: 52,
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 10, letterSpacing: '2px', textTransform: 'uppercase',
        color: active ? '#F2EADB' : hov ? '#ccc' : '#555',
        cursor: 'pointer', transition: 'color 200ms, border-color 200ms',
        marginBottom: -1,
      }}
    >{label}</button>
  );
}

function ShopCard({ item, grad, onAdd, justAdded }) {
  const [hov, setHov] = React.useState(false);
  const remaining = item.edition !== 'Open' ? parseInt(item.edition) - (item.sold || 0) : null;

  return (
    <div
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        background: '#0d0d0d', display: 'flex', flexDirection: 'column',
        transition: 'background 200ms',
        opacity: item.soldOut ? 0.5 : 1,
      }}
    >
      {/* Image */}
      <div style={{
        aspectRatio: '4/3', background: grad,
        position: 'relative', overflow: 'hidden',
      }}>
        <img src={`https://picsum.photos/seed/aw-shop-${item.id}/600/450?grayscale`}
          alt={`${item.title} — ${item.cat.toLowerCase()} by Anika Williams Design${item.soldOut ? ' (sold out)' : ''}`}
          loading="lazy" style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', opacity: item.soldOut ? 0.4 : 0.9,
          }} />
        {item.soldOut && (
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: 'rgba(0,0,0,0.6)',
          }}>
            <span style={{
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 10, letterSpacing: '3px', textTransform: 'uppercase',
              color: '#F2EADB', border: '1px solid #F2EADB', padding: '8px 16px',
            }}>Sold Out</span>
          </div>
        )}
        {remaining !== null && !item.soldOut && (
          <div style={{
            position: 'absolute', top: 12, right: 12,
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 8, letterSpacing: '2px', textTransform: 'uppercase',
            color: '#888', background: 'rgba(0,0,0,0.8)', padding: '4px 8px',
          }}>{remaining} remaining</div>
        )}
      </div>
      {/* Info */}
      <div style={{ padding: '18px 20px 20px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 9, letterSpacing: '2px', textTransform: 'uppercase',
          color: '#555', marginBottom: 6,
        }}>{item.cat} — Ed. {item.edition}</div>
        <div style={{
          fontFamily: "'sedgwick-ave-display', sans-serif",
          fontSize: 20, fontWeight: 400, letterSpacing: '1.5px',
          textTransform: 'uppercase', color: '#F2EADB', marginBottom: 10,
        }}>{item.title}</div>
        <div style={{
          fontFamily: "'EB Garamond', serif",
          fontSize: 14, lineHeight: 1.6, color: '#666', flex: 1, marginBottom: 20,
        }}>{item.desc}</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{
            fontFamily: "'sedgwick-ave-display', sans-serif",
            fontSize: 24, fontWeight: 400, letterSpacing: '2px',
            color: '#F2EADB',
          }}>{item.price}</div>
          <AddBtn
            soldOut={item.soldOut}
            justAdded={justAdded}
            onClick={onAdd}
          />
        </div>
      </div>
    </div>
  );
}

function AddBtn({ soldOut, justAdded, onClick }) {
  const [hov, setHov] = React.useState(false);
  const label = soldOut ? 'Sold Out' : justAdded ? 'Added ✓' : 'Add to Cart';
  return (
    <button
      onClick={onClick}
      disabled={soldOut}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        background: justAdded ? '#F2EADB' : hov && !soldOut ? '#F2EADB' : 'transparent',
        color: justAdded ? '#000' : hov && !soldOut ? '#000' : '#F2EADB',
        border: soldOut ? '1px solid #333' : '1px solid #F2EADB',
        borderRadius: 9999, padding: '9px 20px', minHeight: 40,
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 10, letterSpacing: '2px', textTransform: 'uppercase',
        cursor: soldOut ? 'not-allowed' : 'pointer',
        transition: 'all 200ms',
      }}
    >{label}</button>
  );
}

function CartDrawer({ cart, total, onClose, onRemove, onQty }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 400,
    }}>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.7)',
      }} />
      {/* Drawer */}
      <div style={{
        position: 'absolute', top: 0, right: 0, bottom: 0, width: 440,
        background: '#0d0d0d', borderLeft: '1px solid #262626',
        display: 'flex', flexDirection: 'column',
        overflowY: 'auto',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '28px 32px', borderBottom: '1px solid #262626',
        }}>
          <div style={{
            fontFamily: "'sedgwick-ave-display', sans-serif",
            fontSize: 20, letterSpacing: '3px', textTransform: 'uppercase', color: '#F2EADB',
          }}>Cart</div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none', color: '#666',
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 10, letterSpacing: '2px', textTransform: 'uppercase',
            cursor: 'pointer', transition: 'color 200ms',
          }}
            onMouseEnter={e => e.currentTarget.style.color = '#F2EADB'}
            onMouseLeave={e => e.currentTarget.style.color = '#666'}
          >Close ×</button>
        </div>

        {/* Items */}
        <div style={{ flex: 1, padding: '24px 32px' }}>
          {cart.length === 0 ? (
            <div style={{
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 10, letterSpacing: '2px', textTransform: 'uppercase',
              color: '#444', paddingTop: 40, textAlign: 'center',
            }}>Cart is empty</div>
          ) : cart.map(item => (
            <CartRow key={item.id} item={item} onRemove={onRemove} onQty={onQty} />
          ))}
        </div>

        {/* Footer */}
        {cart.length > 0 && (
          <div style={{ padding: '24px 32px', borderTop: '1px solid #262626' }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', marginBottom: 24,
            }}>
              <span style={{
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 10, letterSpacing: '2px', textTransform: 'uppercase', color: '#666',
              }}>Total</span>
              <span style={{
                fontFamily: "'sedgwick-ave-display', sans-serif",
                fontSize: 24, fontWeight: 400, letterSpacing: '2px', color: '#F2EADB',
              }}>€{total.toFixed(0)}</span>
            </div>
            <CheckoutBtn />
          </div>
        )}
      </div>
    </div>
  );
}

function CartRow({ item, onRemove, onQty }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
      paddingBottom: 20, marginBottom: 20, borderBottom: '1px solid #1a1a1a', gap: 16,
    }}>
      <div style={{ flex: 1 }}>
        <div style={{
          fontFamily: "'sedgwick-ave-display', sans-serif",
          fontSize: 16, letterSpacing: '1.5px', textTransform: 'uppercase',
          color: '#e6e6e6', marginBottom: 4,
        }}>{item.title}</div>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 9, letterSpacing: '2px', textTransform: 'uppercase',
          color: '#555',
        }}>{item.price}</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
        {/* Qty controls */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={() => onQty(item.id, -1)} style={qtyBtn}>−</button>
          <span style={{
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 11, color: '#F2EADB', minWidth: 16, textAlign: 'center',
          }}>{item.qty}</span>
          <button onClick={() => onQty(item.id, 1)} style={qtyBtn}>+</button>
        </div>
        <button onClick={() => onRemove(item.id)} style={{
          background: 'none', border: 'none',
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 9, letterSpacing: '2px', textTransform: 'uppercase',
          color: '#555', cursor: 'pointer', transition: 'color 200ms',
        }}
          onMouseEnter={e => e.currentTarget.style.color = '#c3d9f3'}
          onMouseLeave={e => e.currentTarget.style.color = '#555'}
        >Remove</button>
      </div>
    </div>
  );
}

const qtyBtn = {
  background: 'none', border: '1px solid #333', color: '#888',
  width: 28, height: 28, cursor: 'pointer',
  fontFamily: "'JetBrains Mono', monospace", fontSize: 12,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  transition: 'all 200ms',
};

function CheckoutBtn() {
  const [hov, setHov] = React.useState(false);
  return (
    <button
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        width: '100%', background: hov ? '#F2EADB' : 'transparent',
        color: hov ? '#000' : '#F2EADB',
        border: '1px solid #F2EADB', borderRadius: 9999,
        padding: '14px 0', minHeight: 44,
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 12, letterSpacing: '3px', textTransform: 'uppercase',
        cursor: 'pointer', transition: 'all 200ms',
      }}
    >Proceed to Checkout</button>
  );
}

Object.assign(window, { ShopPage });
