This commit is contained in:
root
2025-12-21 17:36:44 +01:00
parent bb1c5b43d6
commit 8a0835c564
15 changed files with 1124 additions and 193 deletions

View File

@@ -13,6 +13,7 @@ interface DropData {
unit: string
ppu: number
image_url: string | null
images?: string[] // Array of image URLs (up to 4)
created_at: string
start_time: string | null
is_upcoming?: boolean
@@ -30,6 +31,8 @@ export default function Drop() {
const [drop, setDrop] = useState<DropData | null>(null)
const [loading, setLoading] = useState(true)
const [selectedSize, setSelectedSize] = useState(50)
const [customQuantity, setCustomQuantity] = useState<string>('')
const [quantityError, setQuantityError] = useState<string>('')
const [selectedCurrency, setSelectedCurrency] = useState<string>('btc')
const [availableCurrencies, setAvailableCurrencies] = useState<string[]>([])
const [loadingCurrencies, setLoadingCurrencies] = useState(false)
@@ -48,11 +51,19 @@ export default function Drop() {
const [checkingAuth, setCheckingAuth] = useState(true)
const [isWholesaleUnlocked, setIsWholesaleUnlocked] = useState(false)
const [showUnlockModal, setShowUnlockModal] = useState(false)
const [selectedImageIndex, setSelectedImageIndex] = useState(0)
useEffect(() => {
fetchActiveDrop()
checkAuth()
checkWholesaleStatus()
// Poll active drop every 30 seconds
const interval = setInterval(() => {
fetchActiveDrop()
}, 30000) // 30 seconds
return () => clearInterval(interval)
}, [])
const checkWholesaleStatus = async () => {
@@ -122,7 +133,10 @@ export default function Drop() {
const fetchActiveDrop = async () => {
try {
const response = await fetch('/api/drops/active')
const response = await fetch('/api/drops/active', {
// Add cache control to prevent stale data
cache: 'no-store',
})
if (response.ok) {
const data = await response.json()
// Handle both null response and actual drop data
@@ -169,6 +183,71 @@ export default function Drop() {
return sizes.filter((size) => size <= remainingInGrams)
}
const getRemainingInGrams = () => {
if (!drop) return 0
if (drop.unit === 'kg') {
return (drop.size - drop.fill) * 1000
}
return drop.size - drop.fill
}
const getMinimumGrams = () => {
if (!drop) return 0
// Minimum price is 5 CHF
// Calculate minimum grams needed for 5 CHF
const pricePerGram = drop.ppu / 1000
// Use the higher price (standard) to ensure minimum is met
return Math.ceil(5 / pricePerGram)
}
const handleCustomQuantityChange = (value: string) => {
setCustomQuantity(value)
setQuantityError('')
// Clear selected preset size when custom input is used
if (value.trim() !== '') {
const numValue = parseInt(value, 10)
if (!isNaN(numValue) && numValue > 0) {
setSelectedSize(numValue)
}
}
}
const validateCustomQuantity = () => {
if (!drop || !customQuantity.trim()) {
setQuantityError('')
return true
}
const numValue = parseInt(customQuantity, 10)
const remaining = getRemainingInGrams()
const minimum = getMinimumGrams()
if (isNaN(numValue) || numValue <= 0) {
setQuantityError('Please enter a valid number')
return false
}
if (numValue < minimum) {
setQuantityError(`Minimum ${minimum}g required (5 CHF minimum)`)
return false
}
if (numValue > remaining) {
setQuantityError(`Maximum ${remaining}g available`)
return false
}
setQuantityError('')
return true
}
const handleQuantityButtonClick = (size: number) => {
setSelectedSize(size)
setCustomQuantity('')
setQuantityError('')
}
const fetchAvailableCurrencies = async () => {
setLoadingCurrencies(true)
try {
@@ -233,6 +312,11 @@ export default function Drop() {
}
const handleJoinDrop = () => {
// Validate custom quantity if entered
if (customQuantity && !validateCustomQuantity()) {
return
}
// Check if user is logged in
if (!user) {
setShowAuthModal(true)
@@ -357,6 +441,18 @@ export default function Drop() {
return selectedSize * priceToUse
}
const calculateStandardPrice = () => {
if (!drop) return 0
const pricePerGram = drop.ppu / 1000
return selectedSize * pricePerGram
}
const calculateWholesalePrice = () => {
if (!drop) return 0
const pricePerGram = drop.ppu / 1000
return selectedSize * pricePerGram * 0.76
}
const getTimeUntilStart = () => {
if (!drop || !drop.is_upcoming || !drop.start_time) return null
@@ -379,6 +475,22 @@ export default function Drop() {
}
}
// Get images array (prioritize new images array, fallback to legacy image_url)
// Must be defined before early returns to maintain hook order
const images = drop?.images && drop.images.length > 0
? drop.images
: (drop?.image_url ? [drop.image_url] : [])
// Reset selected image index when images change
// Must be called before early returns to maintain hook order
useEffect(() => {
if (images.length > 0 && selectedImageIndex >= images.length) {
setSelectedImageIndex(0)
} else if (images.length === 0) {
setSelectedImageIndex(0)
}
}, [images, selectedImageIndex])
if (loading) {
return (
<div className="drop">
@@ -416,14 +528,66 @@ export default function Drop() {
return (
<div className="drop">
{drop.image_url ? (
<Image
src={drop.image_url}
alt={drop.item}
width={420}
height={420}
style={{ width: '100%', height: 'auto', borderRadius: '16px', objectFit: 'cover' }}
/>
{images.length > 0 ? (
<div>
{/* Main large image */}
<div style={{ marginBottom: '12px' }}>
<Image
src={images[selectedImageIndex]}
alt={`${drop.item} - Image ${selectedImageIndex + 1}`}
width={420}
height={420}
style={{
width: '100%',
height: 'auto',
borderRadius: '16px',
objectFit: 'cover',
aspectRatio: '1 / 1'
}}
/>
</div>
{/* Thumbnails */}
{images.length > 1 && (
<div style={{
display: 'grid',
gridTemplateColumns: `repeat(${Math.min(images.length, 4)}, 1fr)`,
gap: '8px'
}}>
{images.slice(0, 4).map((imgUrl, index) => (
<button
key={index}
onClick={() => setSelectedImageIndex(index)}
style={{
padding: 0,
border: selectedImageIndex === index
? '2px solid var(--accent)'
: '2px solid transparent',
borderRadius: '8px',
background: 'transparent',
cursor: 'pointer',
overflow: 'hidden',
aspectRatio: '1 / 1'
}}
>
<Image
src={imgUrl}
alt={`${drop.item} - Thumbnail ${index + 1}`}
width={100}
height={100}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
opacity: selectedImageIndex === index ? 1 : 0.7,
transition: 'opacity 0.2s'
}}
/>
</button>
))}
</div>
)}
</div>
) : (
<div
style={{
@@ -506,18 +670,74 @@ export default function Drop() {
</>
)}
{!isUpcoming && hasRemaining && availableSizes.length > 0 && (
{!isUpcoming && hasRemaining && (
<>
<div className="options">
{availableSizes.map((size) => (
<button
key={size}
className={selectedSize === size ? 'active' : ''}
onClick={() => setSelectedSize(size)}
>
{size}g
</button>
))}
<div style={{ display: 'flex', gap: '12px', alignItems: 'flex-start', flexWrap: 'wrap' }}>
{availableSizes.length > 0 && (
<div className="options" style={{ flex: '1', minWidth: '200px' }}>
{availableSizes.map((size) => (
<button
key={size}
className={selectedSize === size && !customQuantity ? 'active' : ''}
onClick={() => handleQuantityButtonClick(size)}
>
{size}g
</button>
))}
</div>
)}
<div style={{ flex: availableSizes.length > 0 ? '1' : '100%', minWidth: '150px' }}>
<input
type="number"
value={customQuantity}
onChange={(e) => handleCustomQuantityChange(e.target.value)}
onBlur={validateCustomQuantity}
placeholder="Custom (g)"
min={getMinimumGrams()}
max={getRemainingInGrams()}
style={{
width: '100%',
padding: '14px',
borderRadius: '12px',
border: `1px solid ${quantityError ? '#dc2626' : 'var(--border)'}`,
background: 'var(--bg-soft)',
color: 'var(--text)',
fontSize: '14px',
}}
/>
{quantityError && (
<div style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>
{quantityError}
</div>
)}
{!quantityError && customQuantity && (
<div style={{ marginTop: '6px', fontSize: '12px', color: 'var(--muted)' }}>
Min: {getMinimumGrams()}g · Max: {getRemainingInGrams()}g
</div>
)}
</div>
</div>
<div style={{ marginTop: '24px', marginBottom: '16px' }}>
{isWholesaleUnlocked ? (
<>
<div style={{ fontSize: '18px', fontWeight: 500, marginBottom: '8px' }}>
Total: {calculatePrice().toFixed(2)} CHF
</div>
<div style={{ fontSize: '14px', color: 'var(--muted)' }}>
Standard total: {calculateStandardPrice().toFixed(2)} CHF
</div>
</>
) : (
<>
<div style={{ fontSize: '18px', fontWeight: 500, marginBottom: '8px' }}>
Total: {calculateStandardPrice().toFixed(2)} CHF
</div>
<div style={{ fontSize: '14px', color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: '6px' }}>
Wholesale total: {calculateWholesalePrice().toFixed(2)} CHF 🔒
</div>
</>
)}
</div>
<button className="cta" onClick={handleJoinDrop}>
@@ -841,10 +1061,28 @@ export default function Drop() {
onClick={(e) => e.stopPropagation()}
>
<h2 style={{ marginTop: 0, marginBottom: '20px', color: '#0a7931' }}>
Payment Confirmed!
Payment confirmed
</h2>
<p style={{ marginBottom: '24px', color: 'var(--muted)' }}>
Your payment has been successfully processed. Your order is confirmed and will be included in the drop.
<p style={{ marginBottom: '16px', color: 'var(--text)' }}>
Your order has been successfully processed and is now reserved in this drop.
</p>
<div style={{ marginBottom: '24px' }}>
<p style={{ marginBottom: '12px', fontWeight: '600', color: 'var(--text)' }}>
What happens next:
</p>
<ul style={{
margin: 0,
paddingLeft: '20px',
color: 'var(--muted)',
lineHeight: '1.8'
}}>
<li>Your order will be processed within 24 hours</li>
<li>Shipped via express delivery</li>
<li>You'll receive a shipping confirmation and tracking link by email</li>
</ul>
</div>
<p style={{ marginBottom: '24px', color: 'var(--muted)', fontStyle: 'italic' }}>
Thank you for being part of the collective.
</p>
<div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
<button