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

View File

@@ -13,6 +13,7 @@ export default function Nav() {
const [user, setUser] = useState<User | null>(null)
const [showAuthModal, setShowAuthModal] = useState(false)
const [loading, setLoading] = useState(true)
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
useEffect(() => {
checkAuth()
@@ -54,15 +55,26 @@ export default function Nav() {
return (
<>
<nav>
<div className="brand">
<a href="/" style={{ display: 'inline-block', textDecoration: 'none' }}>
<img src="/header.jpg" alt="420Deals.ch" style={{ height: '40px', width: 'auto' }} />
</a>
</div>
<div className="links">
<a href="#drop">Drop</a>
<a href="#past">Past Drops</a>
<a href="#community">Community</a>
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
<div className="brand">
<a href="/" style={{ display: 'inline-block', textDecoration: 'none' }}>
<img src="/header.jpg" alt="420Deals.ch" style={{ height: '40px', width: 'auto' }} />
</a>
</div>
<button
className="mobile-menu-toggle"
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
aria-label="Toggle menu"
>
<span style={{ display: mobileMenuOpen ? 'none' : 'block' }}></span>
<span style={{ display: mobileMenuOpen ? 'block' : 'none' }}></span>
</button>
</div>
<div className={`links ${mobileMenuOpen ? 'mobile-open' : ''}`}>
<a href="#drop" onClick={() => setMobileMenuOpen(false)}>Drop</a>
<a href="#past" onClick={() => setMobileMenuOpen(false)}>Past Drops</a>
<a href="#community" onClick={() => setMobileMenuOpen(false)}>Community</a>
{!loading && (
user ? (
<>
@@ -71,6 +83,7 @@ export default function Nav() {
</span>
<a
href="/orders"
onClick={() => setMobileMenuOpen(false)}
style={{
background: 'transparent',
border: '1px solid var(--border)',
@@ -89,7 +102,10 @@ export default function Nav() {
Orders
</a>
<button
onClick={handleLogout}
onClick={() => {
handleLogout()
setMobileMenuOpen(false)
}}
style={{
background: 'transparent',
border: '1px solid #e57373',
@@ -109,7 +125,10 @@ export default function Nav() {
</>
) : (
<button
onClick={() => setShowAuthModal(true)}
onClick={() => {
setShowAuthModal(true)
setMobileMenuOpen(false)
}}
style={{
padding: '8px 16px',
fontSize: '14px',
@@ -129,6 +148,7 @@ export default function Nav() {
</button>
)
)}
</div>
</div>
</nav>

View File

@@ -11,6 +11,7 @@ interface PastDrop {
unit: string
ppu: number
image_url: string | null
images?: string[] // Array of image URLs (up to 4)
created_at: string
soldOutInHours: number
}
@@ -26,11 +27,21 @@ export default function PastDrops({ limit, showMoreLink = false }: PastDropsProp
useEffect(() => {
fetchPastDrops()
// Poll past drops every 30 seconds
const interval = setInterval(() => {
fetchPastDrops()
}, 30000) // 30 seconds
return () => clearInterval(interval)
}, [])
const fetchPastDrops = async () => {
try {
const response = await fetch('/api/drops/past')
const response = await fetch('/api/drops/past', {
// Add cache control to prevent stale data
cache: 'no-store',
})
if (response.ok) {
const data = await response.json()
setDrops(data)
@@ -98,49 +109,59 @@ export default function PastDrops({ limit, showMoreLink = false }: PastDropsProp
return (
<>
<div className="past">
{displayedDrops.map((drop) => (
<div key={drop.id} className="card">
{drop.image_url ? (
<div style={{ marginBottom: '12px' }}>
<Image
src={drop.image_url}
alt={drop.item}
width={300}
height={300}
{displayedDrops.map((drop) => {
// Get images array (prioritize new images array, fallback to legacy image_url)
const images = drop.images && drop.images.length > 0
? drop.images
: (drop.image_url ? [drop.image_url] : [])
return (
<div key={drop.id} className="card">
{images.length > 0 ? (
<div style={{ marginBottom: '12px', display: 'grid', gridTemplateColumns: images.length > 1 ? '1fr 1fr' : '1fr', gap: '4px' }}>
{images.slice(0, 4).map((imgUrl, index) => (
<Image
key={index}
src={imgUrl}
alt={`${drop.item} - Image ${index + 1}`}
width={300}
height={300}
style={{
width: '100%',
height: '200px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
))}
</div>
) : (
<div
style={{
width: '100%',
height: '200px',
background: 'var(--bg-soft)',
borderRadius: '12px',
objectFit: 'cover',
marginBottom: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--muted)',
}}
/>
</div>
) : (
<div
style={{
width: '100%',
height: '200px',
background: 'var(--bg-soft)',
borderRadius: '12px',
marginBottom: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--muted)',
}}
>
No Image
</div>
)}
<strong>{drop.item}</strong>
<br />
<span className="meta">{formatSoldOutTime(drop.soldOutInHours)}</span>
<br />
<span className="meta" style={{ fontSize: '13px', marginTop: '4px', display: 'block' }}>
{formatQuantity(drop.size, drop.unit)} · {formatDateAndTime(drop.created_at)}
</span>
</div>
))}
>
No Image
</div>
)}
<strong>{drop.item}</strong>
<br />
<span className="meta">{formatSoldOutTime(drop.soldOutInHours)}</span>
<br />
<span className="meta" style={{ fontSize: '13px', marginTop: '4px', display: 'block' }}>
{formatQuantity(drop.size, drop.unit)} · {formatDateAndTime(drop.created_at)}
</span>
</div>
)
})}
</div>
{showMoreLink && hasMore && (
<div style={{ textAlign: 'center', marginTop: '30px' }}>

View File

@@ -46,14 +46,7 @@ export default function UnlockBar() {
}
if (loading) {
return (
<div className="unlock-bar">
🔒 Wholesale prices locked <strong>Loading...</strong>
<br />
<small>3 verified sign-ups unlock wholesale prices forever.</small>
<a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
</div>
)
return null
}
const status = referralStatus || {
@@ -67,7 +60,9 @@ export default function UnlockBar() {
if (status.isUnlocked) {
return (
<div className="unlock-bar" style={{ background: 'var(--accent)', color: '#000' }}>
Wholesale prices unlocked <strong>You have access to wholesale pricing!</strong>
<div>
Wholesale prices unlocked <strong>You have access to wholesale pricing!</strong>
</div>
</div>
)
}
@@ -75,10 +70,12 @@ export default function UnlockBar() {
return (
<>
<div className="unlock-bar">
🔒 Wholesale prices locked <strong>{status.referralCount} / {status.referralsNeeded} referrals completed</strong> · {status.referralsRemaining} to go
<br />
<small>{status.referralsNeeded} verified sign-ups unlock wholesale prices forever.</small>
<a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
<div>
🔒 Wholesale prices locked <strong>{status.referralCount} / {status.referralsNeeded} referrals completed</strong> · {status.referralsRemaining} to go
<br />
<small>{status.referralsNeeded} verified sign-ups unlock wholesale prices forever.</small>
<a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
</div>
</div>
<UnlockModal isOpen={showModal} onClose={() => setShowModal(false)} />
</>

View File

@@ -1,12 +1,19 @@
'use client'
import { useState, useEffect } from 'react'
import { useState, useEffect, Suspense } from 'react'
import AuthModal from './AuthModal'
interface UnlockModalProps {
isOpen: boolean
onClose: () => void
}
interface User {
id: number
username: string
email: string
}
interface ReferralStatus {
referralCount: number
isUnlocked: boolean
@@ -19,6 +26,7 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
const [referralLink, setReferralLink] = useState<string>('')
const [loading, setLoading] = useState(true)
const [copied, setCopied] = useState(false)
const [showAuthModal, setShowAuthModal] = useState(false)
useEffect(() => {
if (isOpen) {
@@ -63,6 +71,12 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
}
}
const handleLogin = async (user: User) => {
setShowAuthModal(false)
// Refresh referral data after login
await fetchReferralData()
}
if (!isOpen) return null
const status = referralStatus || {
@@ -192,11 +206,26 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
borderRadius: '8px',
marginBottom: '24px',
textAlign: 'center',
color: 'var(--muted)',
fontSize: '14px',
}}
>
Please log in to get your referral link
<p style={{ color: 'var(--muted)', fontSize: '14px', margin: '0 0 12px 0' }}>
Please log in to get your referral link
</p>
<button
onClick={() => setShowAuthModal(true)}
style={{
padding: '10px 20px',
background: 'var(--accent)',
color: '#000',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '14px',
fontWeight: 500,
}}
>
Login
</button>
</div>
)}
@@ -245,6 +274,15 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
</>
)}
</div>
{/* Auth Modal */}
<Suspense fallback={null}>
<AuthModal
isOpen={showAuthModal}
onClose={() => setShowAuthModal(false)}
onLogin={handleLogin}
/>
</Suspense>
</div>
)
}