This commit is contained in:
root
2025-12-20 19:00:42 +01:00
parent 9871289bfb
commit e1a0966dee
23 changed files with 1878 additions and 48 deletions

View File

@@ -0,0 +1,316 @@
'use client'
import { useState, useEffect } from 'react'
interface User {
id: number
username: string
email: string
}
interface AuthModalProps {
isOpen: boolean
onClose: () => void
onLogin: (user: User) => void
}
export default function AuthModal({ isOpen, onClose, onLogin }: AuthModalProps) {
const [isLogin, setIsLogin] = useState(true)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [email, setEmail] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
useEffect(() => {
if (isOpen) {
// Reset form when modal opens
setUsername('')
setPassword('')
setEmail('')
setError('')
setIsLogin(true)
}
}, [isOpen])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
const endpoint = isLogin ? '/api/auth/login' : '/api/auth/register'
const body = isLogin
? { username, password }
: { username, password, email }
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
credentials: 'include', // Important for cookies
})
const data = await response.json()
if (!response.ok) {
setError(data.error || 'An error occurred')
setLoading(false)
return
}
// Success - call onLogin callback and close modal
onLogin(data.user)
onClose()
} catch (error) {
console.error('Auth error:', error)
setError('An unexpected error occurred')
} finally {
setLoading(false)
}
}
if (!isOpen) return null
return (
<div
style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(0, 0, 0, 0.7)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 1000,
padding: '20px',
}}
onClick={onClose}
>
<div
style={{
background: 'var(--card)',
borderRadius: '16px',
padding: '32px',
maxWidth: '400px',
width: '100%',
boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)',
}}
onClick={(e) => e.stopPropagation()}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
<h2 style={{ margin: 0 }}>
{isLogin ? 'Login' : 'Register'}
</h2>
<button
onClick={onClose}
style={{
background: 'transparent',
border: 'none',
fontSize: '24px',
cursor: 'pointer',
color: 'var(--muted)',
padding: 0,
width: '32px',
height: '32px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
×
</button>
</div>
<form onSubmit={handleSubmit}>
{!isLogin && (
<div style={{ marginBottom: '16px' }}>
<label
htmlFor="email"
style={{
display: 'block',
marginBottom: '8px',
fontSize: '14px',
color: 'var(--text)',
}}
>
Email
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
style={{
width: '100%',
padding: '12px',
borderRadius: '8px',
border: '1px solid var(--border)',
background: 'var(--bg-soft)',
color: 'var(--text)',
fontSize: '14px',
}}
placeholder="your@email.com"
/>
</div>
)}
<div style={{ marginBottom: '16px' }}>
<label
htmlFor="username"
style={{
display: 'block',
marginBottom: '8px',
fontSize: '14px',
color: 'var(--text)',
}}
>
Username
</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
minLength={isLogin ? undefined : 3}
style={{
width: '100%',
padding: '12px',
borderRadius: '8px',
border: '1px solid var(--border)',
background: 'var(--bg-soft)',
color: 'var(--text)',
fontSize: '14px',
}}
placeholder="username"
/>
</div>
<div style={{ marginBottom: '20px' }}>
<label
htmlFor="password"
style={{
display: 'block',
marginBottom: '8px',
fontSize: '14px',
color: 'var(--text)',
}}
>
Password
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={isLogin ? undefined : 6}
style={{
width: '100%',
padding: '12px',
borderRadius: '8px',
border: '1px solid var(--border)',
background: 'var(--bg-soft)',
color: 'var(--text)',
fontSize: '14px',
}}
placeholder="password"
/>
</div>
{error && (
<div
style={{
padding: '12px',
background: 'rgba(255, 0, 0, 0.1)',
border: '1px solid rgba(255, 0, 0, 0.3)',
borderRadius: '8px',
color: '#ff4444',
fontSize: '14px',
marginBottom: '16px',
}}
>
{error}
</div>
)}
<button
type="submit"
disabled={loading}
className="cta"
style={{
width: '100%',
padding: '12px',
cursor: loading ? 'not-allowed' : 'pointer',
opacity: loading ? 0.6 : 1,
}}
>
{loading
? 'Processing...'
: isLogin
? 'Login'
: 'Register'}
</button>
</form>
<div
style={{
marginTop: '20px',
textAlign: 'center',
fontSize: '14px',
color: 'var(--muted)',
}}
>
{isLogin ? (
<>
Don't have an account?{' '}
<button
onClick={() => {
setIsLogin(false)
setError('')
}}
style={{
background: 'transparent',
border: 'none',
color: 'var(--accent)',
cursor: 'pointer',
textDecoration: 'underline',
padding: 0,
}}
>
Register
</button>
</>
) : (
<>
Already have an account?{' '}
<button
onClick={() => {
setIsLogin(true)
setError('')
}}
style={{
background: 'transparent',
border: 'none',
color: 'var(--accent)',
cursor: 'pointer',
textDecoration: 'underline',
padding: 0,
}}
>
Login
</button>
</>
)}
</div>
</div>
</div>
)
}

View File

@@ -2,6 +2,7 @@
import { useState, useEffect } from 'react'
import Image from 'next/image'
import AuthModal from './AuthModal'
interface DropData {
id: number
@@ -14,15 +15,43 @@ interface DropData {
created_at: string
}
interface User {
id: number
username: string
email: string
}
export default function Drop() {
const [drop, setDrop] = useState<DropData | null>(null)
const [loading, setLoading] = useState(true)
const [selectedSize, setSelectedSize] = useState(50)
const [showConfirmModal, setShowConfirmModal] = useState(false)
const [showAuthModal, setShowAuthModal] = useState(false)
const [processing, setProcessing] = useState(false)
const [user, setUser] = useState<User | null>(null)
const [checkingAuth, setCheckingAuth] = useState(true)
useEffect(() => {
fetchActiveDrop()
checkAuth()
}, [])
const checkAuth = async () => {
try {
const response = await fetch('/api/auth/session', {
credentials: 'include',
})
if (response.ok) {
const data = await response.json()
setUser(data.user)
}
} catch (error) {
console.error('Error checking auth:', error)
} finally {
setCheckingAuth(false)
}
}
const fetchActiveDrop = async () => {
try {
const response = await fetch('/api/drops/active')
@@ -65,6 +94,85 @@ export default function Drop() {
return sizes.filter((size) => size <= remainingInGrams)
}
const handleJoinDrop = () => {
// Check if user is logged in
if (!user) {
setShowAuthModal(true)
return
}
setShowConfirmModal(true)
}
const handleLogin = (loggedInUser: User) => {
setUser(loggedInUser)
setShowAuthModal(false)
// After login, show the confirmation modal
setShowConfirmModal(true)
}
const handleConfirmPurchase = async () => {
if (!drop) return
setProcessing(true)
try {
// Create NOWPayments invoice and sale record
const response = await fetch('/api/payments/create-invoice', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Important for cookies
body: JSON.stringify({
drop_id: drop.id,
size: selectedSize, // Size in grams
}),
})
if (!response.ok) {
const error = await response.json()
if (response.status === 401) {
// User not authenticated - show login modal
setShowConfirmModal(false)
setShowAuthModal(true)
setProcessing(false)
return
}
alert(`Error: ${error.error || 'Failed to create payment invoice'}`)
setProcessing(false)
return
}
const data = await response.json()
// Close modal
setShowConfirmModal(false)
// Redirect to NOWPayments invoice
if (data.invoice_url) {
window.location.href = data.invoice_url
} else {
alert('Payment invoice created but no redirect URL received')
await fetchActiveDrop()
}
} catch (error) {
console.error('Error creating payment invoice:', error)
alert('Failed to create payment invoice. Please try again.')
setProcessing(false)
}
}
const handleCancelPurchase = () => {
setShowConfirmModal(false)
}
const calculatePrice = () => {
if (!drop) return 0
if (drop.unit === 'kg') {
return (selectedSize / 1000) * drop.ppu
}
return selectedSize * drop.ppu
}
if (loading) {
return (
<div className="drop">
@@ -137,7 +245,7 @@ export default function Drop() {
<span style={{ width: `${progressPercentage}%` }}></span>
</div>
<div className="meta">
{drop.fill}
{drop.unit === 'kg' ? drop.fill.toFixed(2) : Math.round(drop.fill)}
{drop.unit} of {drop.size}
{drop.unit} reserved
</div>
@@ -156,7 +264,9 @@ export default function Drop() {
))}
</div>
<button className="cta">Join Drop</button>
<button className="cta" onClick={handleJoinDrop}>
Join Drop
</button>
</>
)}
@@ -174,6 +284,129 @@ export default function Drop() {
</div>
)}
</div>
{/* Confirmation Modal */}
{showConfirmModal && drop && (
<div
style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(0, 0, 0, 0.7)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 1000,
padding: '20px',
}}
onClick={handleCancelPurchase}
>
<div
style={{
background: 'var(--card)',
borderRadius: '16px',
padding: '32px',
maxWidth: '500px',
width: '100%',
boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)',
}}
onClick={(e) => e.stopPropagation()}
>
<h2 style={{ marginTop: 0, marginBottom: '20px' }}>
Confirm Purchase
</h2>
<div style={{ marginBottom: '24px' }}>
<p style={{ marginBottom: '12px', color: 'var(--muted)' }}>
<strong>Item:</strong> {drop.item}
</p>
<p style={{ marginBottom: '12px', color: 'var(--muted)' }}>
<strong>Quantity:</strong> {selectedSize}g
</p>
<p style={{ marginBottom: '12px', color: 'var(--muted)' }}>
<strong>Price per {drop.unit}:</strong> {drop.ppu.toFixed(2)} CHF
</p>
<div
style={{
padding: '16px',
background: 'var(--bg-soft)',
borderRadius: '8px',
marginTop: '16px',
}}
>
<p style={{ margin: 0, fontSize: '18px', fontWeight: 'bold' }}>
Total: {calculatePrice().toFixed(2)} CHF
</p>
<p
style={{
margin: '4px 0 0 0',
fontSize: '14px',
color: 'var(--muted)',
}}
>
incl. 2.5% VAT
</p>
</div>
</div>
<div
style={{
display: 'flex',
gap: '12px',
justifyContent: 'flex-end',
}}
>
<button
onClick={handleCancelPurchase}
disabled={processing}
style={{
padding: '12px 24px',
background: '#dc2626',
border: 'none',
borderRadius: '14px',
cursor: processing ? 'not-allowed' : 'pointer',
color: '#fff',
fontSize: '15px',
fontWeight: 500,
opacity: processing ? 0.6 : 1,
lineHeight: '1.5',
boxSizing: 'border-box',
display: 'inline-block',
}}
>
Cancel
</button>
<button
onClick={handleConfirmPurchase}
disabled={processing}
style={{
padding: '12px 24px',
background: 'var(--accent)',
color: '#000',
border: 'none',
borderRadius: '14px',
cursor: processing ? 'not-allowed' : 'pointer',
fontSize: '15px',
fontWeight: 500,
opacity: processing ? 0.6 : 1,
lineHeight: '1.5',
boxSizing: 'border-box',
display: 'inline-block',
}}
>
{processing ? 'Processing...' : 'Confirm Purchase'}
</button>
</div>
</div>
</div>
)}
{/* Auth Modal */}
<AuthModal
isOpen={showAuthModal}
onClose={() => setShowAuthModal(false)}
onLogin={handleLogin}
/>
</div>
)
}

View File

@@ -1,13 +1,120 @@
'use client'
import { useState, useEffect } from 'react'
import AuthModal from './AuthModal'
interface User {
id: number
username: string
email: string
}
export default function Nav() {
const [user, setUser] = useState<User | null>(null)
const [showAuthModal, setShowAuthModal] = useState(false)
const [loading, setLoading] = useState(true)
useEffect(() => {
checkAuth()
}, [])
const checkAuth = async () => {
try {
const response = await fetch('/api/auth/session', {
credentials: 'include',
})
if (response.ok) {
const data = await response.json()
setUser(data.user)
}
} catch (error) {
console.error('Error checking auth:', error)
} finally {
setLoading(false)
}
}
const handleLogin = (loggedInUser: User) => {
setUser(loggedInUser)
setShowAuthModal(false)
}
const handleLogout = async () => {
try {
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
})
setUser(null)
} catch (error) {
console.error('Error logging out:', error)
}
}
return (
<nav>
<div className="brand">420Deals.ch</div>
<div className="links">
<a href="#drop">Drop</a>
<a href="#past">Past Drops</a>
<a href="#community">Community</a>
</div>
</nav>
<>
<nav>
<div className="brand">420Deals.ch</div>
<div className="links">
<a href="#drop">Drop</a>
<a href="#past">Past Drops</a>
<a href="#community">Community</a>
{!loading && (
user ? (
<>
<span style={{ color: 'var(--muted)', fontSize: '14px', marginLeft: '48px' }}>
{user.username}
</span>
<button
onClick={handleLogout}
style={{
background: 'transparent',
border: '1px solid var(--border)',
color: 'var(--text)',
padding: '8px 16px',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '14px',
marginLeft: '12px',
lineHeight: '1',
boxSizing: 'border-box',
display: 'inline-block',
}}
>
Logout
</button>
</>
) : (
<button
onClick={() => setShowAuthModal(true)}
style={{
padding: '8px 16px',
fontSize: '14px',
background: 'var(--accent)',
color: '#000',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontWeight: 500,
marginLeft: '48px',
lineHeight: '1',
boxSizing: 'border-box',
display: 'inline-block',
}}
>
Login
</button>
)
)}
</div>
</nav>
<AuthModal
isOpen={showAuthModal}
onClose={() => setShowAuthModal(false)}
onLogin={handleLogin}
/>
</>
)
}

View File

@@ -1,44 +1,119 @@
'use client'
import { useState, useEffect } from 'react'
import Image from 'next/image'
interface PastDrop {
name: string
image: string
soldIn: string
id: number
item: string
size: number
fill: number
unit: string
ppu: number
image_url: string | null
created_at: string
soldOutInHours: number
}
const pastDrops: PastDrop[] = [
{
name: 'Swiss Gold',
image: 'https://images.unsplash.com/photo-1581091012184-5c7b4c101899',
soldIn: 'Sold out in 42h',
},
{
name: 'Lemon T1',
image: 'https://images.unsplash.com/photo-1512436991641-6745cdb1723f',
soldIn: 'Sold out in 19h',
},
{
name: 'Alpine Frost',
image: 'https://images.unsplash.com/photo-1600431521340-491eca880813',
soldIn: 'Sold out in 31h',
},
]
export default function PastDrops() {
const [drops, setDrops] = useState<PastDrop[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchPastDrops()
}, [])
const fetchPastDrops = async () => {
try {
const response = await fetch('/api/drops/past')
if (response.ok) {
const data = await response.json()
setDrops(data)
}
} catch (error) {
console.error('Error fetching past drops:', error)
} finally {
setLoading(false)
}
}
const formatSoldOutTime = (hours: number) => {
if (hours < 1) {
return 'Sold out in less than 1h'
} else if (hours === 1) {
return 'Sold out in 1h'
} else if (hours < 24) {
return `Sold out in ${hours}h`
} else {
const days = Math.floor(hours / 24)
const remainingHours = hours % 24
if (remainingHours === 0) {
return days === 1 ? 'Sold out in 1 day' : `Sold out in ${days} days`
} else {
return `Sold out in ${days}d ${remainingHours}h`
}
}
}
if (loading) {
return (
<div className="past">
<p style={{ color: 'var(--muted)', textAlign: 'center' }}>Loading past drops...</p>
</div>
)
}
if (drops.length === 0) {
return (
<div className="past">
<p style={{ color: 'var(--muted)', textAlign: 'center' }}>
No past drops yet. Check back soon!
</p>
</div>
)
}
return (
<div className="past">
{pastDrops.map((drop, index) => (
<div key={index} className="card">
<Image
src={drop.image}
alt={drop.name}
width={240}
height={240}
style={{ width: '100%', height: 'auto', borderRadius: '12px', marginBottom: '12px' }}
/>
<strong>{drop.name}</strong>
{drops.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}
style={{
width: '100%',
maxWidth: '300px',
height: '300px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
</div>
) : (
<div
style={{
width: '100%',
maxWidth: '300px',
height: '300px',
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">{drop.soldIn}</span>
<span className="meta">{formatSoldOutTime(drop.soldOutInHours)}</span>
</div>
))}
</div>