predikt/oracle/web/pages/charity.tsx

1827 lines
61 KiB
TypeScript

import { charities } from 'common/charity'
import {
formatMoney,
formatMoneyAuto,
formatMoneyWithDecimals,
} from 'common/util/format'
import { sortBy } from 'lodash'
import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import { Col } from 'web/components/layout/col'
import { Page } from 'web/components/layout/page'
import { Row } from 'web/components/layout/row'
import { SEO } from 'web/components/SEO'
import { useAPIGetter } from 'web/hooks/use-api-getter'
import { useUser } from 'web/hooks/use-user'
import { useAdmin } from 'web/hooks/use-admin'
import { api, APIError } from 'web/lib/api/api'
import { Select } from 'web/components/widgets/select'
import { SelectDropdown } from 'web/components/widgets/select-dropdown'
import { Button } from 'web/components/buttons/button'
import { Input } from 'web/components/widgets/input'
import { Avatar } from 'web/components/widgets/avatar'
import { UserLink } from 'web/components/widgets/user-link'
import { RelativeTimestamp } from 'web/components/relative-timestamp'
import { LoadingIndicator } from 'web/components/widgets/loading-indicator'
import { ManaCoin } from 'web/public/custom-components/manaCoin'
import { InfoTooltip } from 'web/components/widgets/info-tooltip'
import { Modal, MODAL_CLASS } from 'web/components/layout/modal'
import { SpinningWheel } from 'web/components/charity/spinning-wheel'
import { FullscreenConfetti } from 'web/components/widgets/fullscreen-confetti'
import toast from 'react-hot-toast'
import clsx from 'clsx'
import { track } from 'web/lib/service/analytics'
import { FaHeart } from 'react-icons/fa6'
import {
TbTicket,
TbShieldHalfFilled,
TbRotateClockwise,
TbHourglass,
TbChartBar,
TbTrophy,
TbScale,
TbCircleCheck,
} from 'react-icons/tb'
import {
calculateTicketsFromMana,
getCurrentGiveawayTicketPrice,
MAX_CHARITY_GIVEAWAY_PRIZE_DELTA_USD,
} from 'common/charity-giveaway'
import { CharityChampionCard } from 'web/components/shop/charity-champion-card'
import { HovercardBackgroundPreview } from 'web/pages/shop'
import { FORMER_CHARITY_CHAMPION_ENTITLEMENT_ID } from 'common/shop/items'
function formatEntries(entries: number): string {
if (entries >= 1000) {
return entries.toLocaleString(undefined, { maximumFractionDigits: 1 })
} else if (entries >= 1) {
return entries.toLocaleString(undefined, { maximumFractionDigits: 2 })
} else {
return entries.toLocaleString(undefined, { maximumFractionDigits: 4 })
}
}
// Horse charities to exclude from the giveaway
const EXCLUDED_CHARITY_IDS = [
'new-vocations',
'stable-recovery',
'thoroughbred-retirement-foundation',
'the-thoroughbred-aftercare-alliance',
'old-friends',
'new-york-racetrack-chaplaincy',
'belmont-child-care-association',
'thoroughbred-charities-of-america',
'the-jockey-club-safety-net-foundation',
'grayson-jockey-club-research-foundation',
'mareworthy',
]
// Color palette for the pie chart
const COLORS = [
'#6366f1', // indigo
'#8b5cf6', // violet
'#ec4899', // pink
'#f43f5e', // rose
'#f97316', // orange
'#eab308', // yellow
'#22c55e', // green
'#14b8a6', // teal
'#06b6d4', // cyan
'#3b82f6', // blue
'#a855f7', // purple
'#d946ef', // fuchsia
]
export default function CharityGiveawayPage(props: { giveawayNum?: number }) {
const { giveawayNum } = props
const user = useUser()
const isAdmin = useAdmin()
const router = useRouter()
const { data, refresh } = useAPIGetter(
'get-charity-giveaway',
giveawayNum ? { giveawayNum } : {}
)
const { data: giveawayListData } = useAPIGetter(
'get-charity-giveaway-list',
{}
)
const [selectedCharityId, setSelectedCharityId] = useState<string>('')
const [hoveredCharityId, setHoveredCharityId] = useState<string | null>(null)
const [manaAmount, setManaAmount] = useState<number>(100)
const [isSubmitting, setIsSubmitting] = useState(false)
const [salesRefreshKey, setSalesRefreshKey] = useState(0)
const [showCreateGiveawayModal, setShowCreateGiveawayModal] = useState(false)
const [newCloseTime, setNewCloseTime] = useState('')
const [newPrizeAmount, setNewPrizeAmount] = useState('1000')
const [isCreatingGiveaway, setIsCreatingGiveaway] = useState(false)
const [showAdjustPrizeModal, setShowAdjustPrizeModal] = useState(false)
const [adjustPrizeAmount, setAdjustPrizeAmount] = useState('')
const [isAdjustingPrize, setIsAdjustingPrize] = useState(false)
// Winner reveal state
const [isSelectingWinner, setIsSelectingWinner] = useState(false)
const [showSpinningWheel, setShowSpinningWheel] = useState(false)
const [showConfetti, setShowConfetti] = useState(false)
const [pendingWinningCharity, setPendingWinningCharity] = useState<
string | null
>(null)
const previewCharityId = hoveredCharityId || selectedCharityId
const giveaway = data ? data.giveaway : undefined
const charityStats = data ? data.charityStats : []
const totalTickets = data ? data.totalTickets : 0
const winningCharity = data ? data.winningCharity : undefined
const winner = data ? data.winner : undefined
const blockHash = data ? data.nonce : undefined // nonce now contains Bitcoin block hash
const yourEntry = data?.yourEntry
const totalManaSpent = charityStats.reduce(
(sum, s) => sum + s.totalManaSpent,
0
)
// Calculate time remaining
const [timeRemaining, setTimeRemaining] = useState<string>('')
const [timeRemainingDetailed, setTimeRemainingDetailed] = useState<string>('')
useEffect(() => {
if (!giveaway) return
const updateTime = () => {
const now = Date.now()
const diff = giveaway.closeTime - now
if (diff <= 0) {
setTimeRemaining('Ended')
setTimeRemainingDetailed('Drawing complete')
return
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24))
const hours = Math.floor(
(diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
)
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
if (days > 0) {
setTimeRemaining(`${days}d ${hours}h`)
setTimeRemainingDetailed(`${days} days, ${hours} hours remaining`)
} else if (hours > 0) {
setTimeRemaining(`${hours}h ${minutes}m`)
setTimeRemainingDetailed(`${hours} hours, ${minutes} minutes remaining`)
} else {
setTimeRemaining(`${minutes}m`)
setTimeRemainingDetailed(`${minutes} minutes remaining`)
}
}
updateTime()
const interval = setInterval(updateTime, 60000)
return () => clearInterval(interval)
}, [giveaway?.closeTime])
const prizeAmountUsd = giveaway?.prizeAmountUsd ?? 0
const numTickets = useMemo(() => {
if (manaAmount <= 0) return 0
return calculateTicketsFromMana(totalTickets, manaAmount, prizeAmountUsd)
}, [totalTickets, manaAmount, prizeAmountUsd])
const currentPrice = getCurrentGiveawayTicketPrice(
totalTickets,
prizeAmountUsd
)
const isClosed = giveaway && giveaway.closeTime <= Date.now()
const hasWinner = !!giveaway?.winningTicketId
const giveawayList = giveawayListData?.giveaways ?? []
const activeGiveaway = giveawayList.find((g) => g.closeTime > Date.now())
// Check if user has already seen the reveal animation
const [hasSeenReveal, setHasSeenReveal] = useState(false)
// Initialize hasSeenReveal from localStorage once giveaway is loaded
useEffect(() => {
if (giveaway && typeof window !== 'undefined') {
const seen =
localStorage.getItem(`giveaway-reveal-${giveaway.giveawayNum}`) ===
'true'
setHasSeenReveal(seen)
}
}, [giveaway?.giveawayNum])
// Auto-show spinning wheel if there's a winner and user hasn't seen it
useEffect(() => {
if (
hasWinner &&
winningCharity &&
!hasSeenReveal &&
charityStats.length > 0 &&
giveaway
) {
// Small delay to ensure localStorage check has completed
const timer = setTimeout(() => {
const seen =
localStorage.getItem(`giveaway-reveal-${giveaway.giveawayNum}`) ===
'true'
if (!seen) {
setShowSpinningWheel(true)
setPendingWinningCharity(winningCharity)
}
}, 100)
return () => clearTimeout(timer)
}
}, [
hasWinner,
winningCharity,
hasSeenReveal,
charityStats.length,
giveaway?.giveawayNum,
])
const handleSelectWinner = async () => {
if (!giveaway || isSelectingWinner) return
setIsSelectingWinner(true)
try {
const result = await api('select-charity-giveaway-winner', {
giveawayNum: giveaway.giveawayNum,
})
toast.success('Winner selected!')
track('charity giveaway winner selected', {
giveawayNum: giveaway.giveawayNum,
charityId: result.charityId,
charityName: charities.find((c) => c.id === result.charityId)?.name,
})
// Refresh data to get the winner details
await refresh()
// Start the spinning wheel animation
setPendingWinningCharity(result.charityId)
setShowSpinningWheel(true)
} catch (e) {
const msg = e instanceof APIError ? e.message : 'Failed to select winner'
toast.error(msg)
} finally {
setIsSelectingWinner(false)
}
}
const handleOpenAdjustPrize = () => {
if (!giveaway) return
setAdjustPrizeAmount(String(giveaway.prizeAmountUsd))
setShowAdjustPrizeModal(true)
}
const handleAdjustPrize = async () => {
if (!giveaway || isAdjustingPrize) return
const amount = Number(adjustPrizeAmount)
if (!Number.isFinite(amount) || amount <= 0) {
toast.error('Please enter a valid prize amount')
return
}
setIsAdjustingPrize(true)
try {
await api('admin-update-charity-giveaway-prize', {
giveawayNum: giveaway.giveawayNum,
prizeAmountUsd: amount,
})
toast.success('Prize amount updated')
setShowAdjustPrizeModal(false)
refresh()
} catch (e) {
const msg =
e instanceof APIError ? e.message : 'Failed to update prize amount'
toast.error(msg)
} finally {
setIsAdjustingPrize(false)
}
}
const handleCreateGiveaway = async () => {
if (isCreatingGiveaway) return
const closeTimestamp = Date.parse(newCloseTime)
if (!Number.isFinite(closeTimestamp)) {
toast.error('Please enter a valid close date/time')
return
}
const prizeAmount = Number(newPrizeAmount)
if (!Number.isFinite(prizeAmount) || prizeAmount <= 0) {
toast.error('Please enter a valid prize amount')
return
}
setIsCreatingGiveaway(true)
try {
await api('admin-create-charity-giveaway', {
closeTime: closeTimestamp,
prizeAmountUsd: prizeAmount,
})
toast.success('New giveaway created!')
setShowCreateGiveawayModal(false)
setNewPrizeAmount('1000')
setNewCloseTime('')
refresh()
} catch (e) {
const msg =
e instanceof APIError ? e.message : 'Failed to create giveaway'
toast.error(msg)
} finally {
setIsCreatingGiveaway(false)
}
}
const handleWheelComplete = () => {
setShowConfetti(true)
// Mark as seen in localStorage
if (giveaway) {
localStorage.setItem(`giveaway-reveal-${giveaway.giveawayNum}`, 'true')
setHasSeenReveal(true)
}
// Hide confetti after a few seconds
setTimeout(() => setShowConfetti(false), 5000)
}
const handleBuyTickets = async () => {
if (!giveaway || !selectedCharityId || numTickets <= 0) return
setIsSubmitting(true)
try {
const result = await api('buy-charity-giveaway-tickets', {
giveawayNum: giveaway.giveawayNum,
charityId: selectedCharityId,
numTickets,
})
toast.success(
`Converted ${formatMoney(result.manaSpent)} into ${formatEntries(
result.numTickets
)} entries!`
)
track('charity giveaway purchase', {
giveawayNum: giveaway.giveawayNum,
charityId: selectedCharityId,
charityName: charities.find((c) => c.id === selectedCharityId)?.name,
numTickets: result.numTickets,
manaSpent: result.manaSpent,
ticketId: result.ticketId,
})
refresh()
setSalesRefreshKey((k) => k + 1)
} catch (e) {
const msg =
e instanceof APIError ? e.message : 'Failed to convert entries'
toast.error(msg)
} finally {
setIsSubmitting(false)
}
}
if (data === undefined) {
return (
<Page trackPageView={'charity giveaway'}>
<Col className="items-center justify-center py-20">
<LoadingIndicator />
</Col>
</Page>
)
}
if (!giveaway) {
return (
<Page trackPageView={'charity giveaway'}>
<SEO
title="Predikt Charity Giveaway"
description="Enter the Predikt Charity Giveaway to help your favorite charity win a cash donation from Predikt."
url="/charity"
/>
<Col className="mx-auto w-full max-w-3xl items-center justify-center gap-6 px-4 py-20">
<TbTicket className="text-ink-300 h-16 w-16" aria-hidden />
<h1 className="text-ink-900 text-2xl font-semibold">
No Active Giveaway
</h1>
<p className="text-ink-500 text-center">
There's no giveaway running at the moment.
<br />
Check back soon for the next drawing!
</p>
{isAdmin && (
<Button
color="indigo"
onClick={() => setShowCreateGiveawayModal(true)}
>
Create New Giveaway
</Button>
)}
</Col>
<CreateGiveawayModal
open={showCreateGiveawayModal}
setOpen={setShowCreateGiveawayModal}
newCloseTime={newCloseTime}
setNewCloseTime={setNewCloseTime}
newPrizeAmount={newPrizeAmount}
setNewPrizeAmount={setNewPrizeAmount}
isCreatingGiveaway={isCreatingGiveaway}
onCreate={handleCreateGiveaway}
/>
</Page>
)
}
return (
<Page trackPageView={'charity giveaway'}>
<SEO
title={
giveaway.giveawayNum
? `Predikt Charity Giveaway #${giveaway.giveawayNum}`
: 'Predikt Charity Giveaway'
}
description={`Help your favorite charity win $${giveaway.prizeAmountUsd.toLocaleString()} from Predikt. Convert coins into entries to boost their odds.`}
url={giveawayNum ? `/charity/${giveaway.giveawayNum}` : '/charity'}
/>
<Col className="mx-auto w-full max-w-3xl gap-8 px-4 py-8 sm:px-6">
{/* Header */}
<Col className="gap-4">
{/* Mobile stacks the title above the controls; sm+ is one row. */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<Row className="items-center gap-3">
<FaHeart className="h-8 w-8 text-emerald-500" />
<h1 className="text-ink-900 text-3xl font-bold tracking-tight">
Predikt Charity Giveaway
</h1>
</Row>
<div className="flex flex-wrap items-center gap-2 sm:ml-auto">
{giveawayList.length > 1 && (
<SelectDropdown
aria-label="Select charity giveaway"
value={giveaway.giveawayNum}
options={giveawayList.map((g) => ({
value: g.giveawayNum,
label: `Giveaway #${g.giveawayNum}`,
}))}
onChange={(nextNum) => {
if (
activeGiveaway &&
nextNum === activeGiveaway.giveawayNum
) {
router.push('/charity')
} else {
router.push(`/charity/${nextNum}`)
}
}}
/>
)}
{isAdmin && (
<Button
color="gray-outline"
size="sm"
onClick={handleOpenAdjustPrize}
>
Adjust prize
</Button>
)}
{isAdmin &&
isClosed &&
(!activeGiveaway ||
activeGiveaway.giveawayNum === giveaway.giveawayNum) && (
<Button
color="indigo"
size="sm"
onClick={() => setShowCreateGiveawayModal(true)}
>
Create New Giveaway
</Button>
)}
</div>
</div>
<p className="text-ink-600 text-lg leading-relaxed">
Predikt is giving ${giveaway.prizeAmountUsd.toLocaleString()} to
charity—you decide which one. Convert coins into entries to boost a
charity's odds, and when the giveaway ends, we'll draw one lucky
entry to determine the winning charity.
</p>
</Col>
{/* Stats Row */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<StatCard
label="Prize Pool"
value={`$${giveaway.prizeAmountUsd.toLocaleString()}`}
color="teal"
/>
<StatCard
label="Time Left"
value={timeRemaining}
sublabel={
isClosed
? timeRemainingDetailed
: `Ends ${new Date(giveaway.closeTime).toLocaleDateString(
undefined,
{
month: 'short',
day: 'numeric',
year: 'numeric',
}
)}`
}
color={isClosed ? 'red' : 'amber'}
/>
<StatCard
label="Total Entries"
value={Math.round(totalTickets).toLocaleString()}
color="indigo"
/>
<StatCard
label="Coins Spent"
value={formatMoney(totalManaSpent)}
color="violet"
/>
</div>
{/* Pie Chart - hide when winner is being displayed */}
{!hasWinner && (
<GiveawayPieChart
charityStats={charityStats}
totalTickets={totalTickets}
hoveredCharityId={hoveredCharityId}
onHoverCharity={setHoveredCharityId}
onSelectCharity={setSelectedCharityId}
myEntries={yourEntry?.totalTickets}
/>
)}
{/* Purchase Form */}
{!isClosed && user && !isAdmin && (
<PurchaseForm
selectedCharityId={selectedCharityId}
setSelectedCharityId={setSelectedCharityId}
previewCharityId={previewCharityId}
hoveredCharityId={hoveredCharityId}
manaAmount={manaAmount}
setManaAmount={setManaAmount}
numTickets={numTickets}
currentPrice={currentPrice}
isSubmitting={isSubmitting}
handleBuyTickets={handleBuyTickets}
/>
)}
{!isClosed && user && isAdmin && (
<div className="rounded-xl border border-amber-200 bg-amber-50 p-5 text-center dark:border-amber-800 dark:bg-amber-950/30">
<TbShieldHalfFilled className="text-ink-700 mx-auto mb-1 h-7 w-7" aria-hidden />
<h3 className="text-ink-900 font-semibold">
Admins can't participate
</h3>
<p className="text-ink-600 mt-1 text-sm">
To keep the giveaway fair, Predikt admins aren't eligible to get
entries.
</p>
</div>
)}
{!isClosed && !user && (
<SignInPrompt previewCharityId={previewCharityId} />
)}
{/* Winner Reveal Section */}
{isClosed && showSpinningWheel && pendingWinningCharity && (
<div className="bg-canvas-0 border-canvas-50 overflow-hidden rounded-xl border p-8 shadow-sm">
<SpinningWheel
charityStats={charityStats}
totalTickets={totalTickets}
winningCharityId={pendingWinningCharity}
onComplete={handleWheelComplete}
autoStart={true}
showLegend={true}
winner={winner}
/>
</div>
)}
{/* Winner Display (after animation or if already seen) */}
{isClosed && hasWinner && winningCharity && !showSpinningWheel && (
<WinnerCard
winningCharity={winningCharity}
winner={winner}
prizeAmount={giveaway.prizeAmountUsd}
charityStats={charityStats}
totalTickets={totalTickets}
onReplay={() => {
setShowSpinningWheel(true)
setPendingWinningCharity(winningCharity)
}}
/>
)}
{/* Admin Select Winner Button */}
{isClosed && !hasWinner && isAdmin && (
<div className="bg-canvas-0 border-canvas-50 overflow-hidden rounded-xl border p-6 shadow-sm">
<Col className="items-center gap-4">
<TbRotateClockwise className="text-ink-700 h-10 w-10" aria-hidden />
<h3 className="text-ink-900 text-lg font-semibold">
Ready to Draw Winner
</h3>
<p className="text-ink-600 text-center text-sm">
The giveaway has closed. Click below to randomly select the
winning charity.
</p>
<Button
color="indigo"
size="lg"
onClick={handleSelectWinner}
loading={isSelectingWinner}
disabled={isSelectingWinner}
>
<TbTicket className="mr-2 inline h-5 w-5" aria-hidden />
Draw Winning Entry
</Button>
</Col>
</div>
)}
{/* Waiting for winner (non-admin view) */}
{isClosed && !hasWinner && !isAdmin && (
<div className="rounded-xl border border-amber-200 bg-amber-50 p-6 text-center dark:border-amber-800 dark:bg-amber-950/30">
<TbHourglass className="text-ink-700 mx-auto mb-2 h-7 w-7" aria-hidden />
<h3 className="text-ink-900 font-semibold">Giveaway Closed</h3>
<p className="text-ink-600 mt-1 text-sm">
The winning entry will be drawn soon. Check back!
</p>
</div>
)}
{/* Confetti */}
{showConfetti && <FullscreenConfetti />}
{/* Charity Champion Trophy + Champion's Legacy hovercard residual */}
{(() => {
const legacyEntitlement = user?.entitlements?.find(
(e) => e.entitlementId === FORMER_CHARITY_CHAMPION_ENTITLEMENT_ID
)
return (
<div className="grid gap-3 sm:grid-cols-2">
<CharityChampionCard
data={data}
isLoading={!data}
user={user}
entitlements={user?.entitlements}
onEntitlementsChange={() => refresh()}
/>
<ChampionLegacyCard
user={user}
isOwned={!!legacyEntitlement}
isEnabled={legacyEntitlement?.enabled ?? false}
onChange={() => refresh()}
/>
</div>
)
})()}
{/* Sales History */}
<SalesHistory
giveawayNum={giveaway.giveawayNum}
refreshKey={salesRefreshKey}
/>
{/* Provably Fair Banner */}
{giveaway && (
<ProvablyFairBanner
giveawayNum={giveaway.giveawayNum}
closeTime={giveaway.closeTime}
blockHash={blockHash}
hasWinner={hasWinner}
/>
)}
<CreateGiveawayModal
open={showCreateGiveawayModal}
setOpen={setShowCreateGiveawayModal}
newCloseTime={newCloseTime}
setNewCloseTime={setNewCloseTime}
newPrizeAmount={newPrizeAmount}
setNewPrizeAmount={setNewPrizeAmount}
isCreatingGiveaway={isCreatingGiveaway}
onCreate={handleCreateGiveaway}
/>
<AdjustPrizeModal
open={showAdjustPrizeModal}
setOpen={setShowAdjustPrizeModal}
giveawayNum={giveaway.giveawayNum}
currentPrizeAmount={giveaway.prizeAmountUsd}
adjustPrizeAmount={adjustPrizeAmount}
setAdjustPrizeAmount={setAdjustPrizeAmount}
isAdjustingPrize={isAdjustingPrize}
onAdjust={handleAdjustPrize}
/>
</Col>
</Page>
)
}
function ChampionLegacyCard(props: {
user: ReturnType<typeof useUser>
isOwned: boolean
isEnabled: boolean
onChange: () => void
}) {
const { user, isOwned, isEnabled, onChange } = props
const [toggling, setToggling] = useState(false)
const handleToggle = async () => {
const newEnabled = !isEnabled
setToggling(true)
try {
const result = await api('shop-toggle', {
itemId: 'former-charity-champion',
enabled: newEnabled,
})
if (result.success) {
toast.success(
newEnabled
? "Champion's Legacy enabled"
: "Champion's Legacy disabled"
)
onChange()
}
} catch (e: any) {
toast.error(e.message || 'Failed to toggle')
} finally {
setToggling(false)
}
}
return (
<Col
className={clsx(
'bg-canvas-0 border-canvas-50 gap-2 rounded-xl border p-3 shadow-sm',
!isOwned && 'opacity-80'
)}
>
<span className="text-sm font-semibold text-amber-700 dark:text-amber-400">
Champion's Legacy
</span>
<HovercardBackgroundPreview user={user} background="champions-legacy" />
<p className="text-ink-500 text-xs">
{isOwned
? 'Permanent hovercard background — yours from holding the trophy. Visible in the shop once owned.'
: 'Permanent hovercard background — kept for life once you claim the trophy, even after being dethroned.'}
</p>
<Row className="items-center justify-center gap-2 pt-1">
{isOwned ? (
<label className="relative inline-flex cursor-pointer items-center">
<input
type="checkbox"
checked={isEnabled}
onChange={handleToggle}
disabled={toggling}
className="peer sr-only"
/>
<div className="peer h-6 w-11 rounded-full bg-ink-300 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white after:transition-all peer-checked:bg-amber-500 peer-checked:after:translate-x-full" />
<span className="text-ink-700 ml-2 text-sm">
{isEnabled ? 'Enabled' : 'Disabled'}
</span>
</label>
) : (
<span className="text-ink-400 text-xs italic">
Locked — claim the trophy to unlock
</span>
)}
</Row>
</Col>
)
}
function StatCard(props: {
label: string
value: string
sublabel?: string
color: 'teal' | 'amber' | 'red' | 'indigo' | 'violet'
}) {
const { label, value, sublabel, color } = props
const colorClasses = {
teal: 'text-teal-600 dark:text-teal-400',
amber: 'text-amber-600 dark:text-amber-400',
red: 'text-red-500 dark:text-red-400',
indigo: 'text-primary-600 dark:text-primary-400',
violet: 'text-primary-600 dark:text-primary-400',
}
return (
<div className="bg-canvas-0 border-canvas-50 flex flex-col rounded-xl border p-4 shadow-sm">
<div className="text-ink-500 text-xs font-medium uppercase tracking-wider">
{label}
</div>
<div
className={clsx(
'mt-1 text-xl font-bold sm:text-2xl',
colorClasses[color]
)}
>
{value}
</div>
{sublabel && (
<div className="text-ink-400 mt-0.5 text-xs">{sublabel}</div>
)}
</div>
)
}
function PurchaseForm(props: {
selectedCharityId: string
setSelectedCharityId: (id: string) => void
previewCharityId: string
hoveredCharityId: string | null
manaAmount: number
setManaAmount: (amount: number) => void
numTickets: number
currentPrice: number
isSubmitting: boolean
handleBuyTickets: () => void
}) {
const {
selectedCharityId,
setSelectedCharityId,
previewCharityId,
hoveredCharityId,
manaAmount,
setManaAmount,
numTickets,
currentPrice,
isSubmitting,
handleBuyTickets,
} = props
const previewCharity = previewCharityId
? charities.find((c) => c.id === previewCharityId)
: null
const isHovering = hoveredCharityId === previewCharityId && !selectedCharityId
return (
<div className="bg-canvas-0 border-canvas-50 overflow-hidden rounded-xl border shadow-sm">
<div className="border-canvas-50 bg-canvas-50 border-b px-5 py-4">
<h3 className="text-ink-900 font-semibold">Get Entries</h3>
<p className="text-ink-500 mt-0.5 text-sm">
Support a charity and enter the drawing
</p>
</div>
<Col className="gap-5 p-5">
{/* Charity Selection */}
<Col className="gap-2">
<label className="text-ink-700 text-sm font-medium">
Choose a charity
</label>
<Select
value={selectedCharityId}
onChange={(e) => setSelectedCharityId(e.target.value)}
className="w-full rounded-lg"
>
<option value="">Select charity...</option>
{sortBy(
charities.filter((c) => !EXCLUDED_CHARITY_IDS.includes(c.id)),
'name'
).map((charity) => (
<option key={charity.id} value={charity.id}>
{charity.name}
</option>
))}
</Select>
</Col>
{/* Charity Preview */}
{previewCharity && (
<div
className={clsx(
'overflow-hidden rounded-lg border transition-all',
isHovering
? 'border-primary-300 bg-primary-50 dark:border-primary-700 dark:bg-primary-950/30'
: 'border-canvas-100 bg-canvas-50'
)}
>
<Row className="gap-3 p-3">
{previewCharity.photo && (
<img
src={previewCharity.photo}
alt={previewCharity.name}
className="h-12 w-12 flex-shrink-0 rounded-lg object-cover"
/>
)}
<Col className="min-w-0 flex-1 gap-0.5">
<div className="text-ink-900 text-sm font-medium">
{previewCharity.name}
</div>
<div className="text-ink-500 line-clamp-2 text-xs leading-relaxed">
{previewCharity.preview}
</div>
</Col>
</Row>
</div>
)}
{/* Amount Input */}
{selectedCharityId && (
<>
<Col className="gap-2">
<Row className="items-center gap-1">
<label className="text-ink-700 text-sm font-medium">
Amount to convert
</label>
<InfoTooltip
text={`Current rate: ${formatMoneyWithDecimals(
currentPrice
)} per entry. Entries follow a bonding curve — earlier entries cost less coins.`}
size="sm"
/>
</Row>
<Row className="items-center gap-2">
<Row className="bg-canvas-50 border-canvas-100 flex-1 items-center gap-1.5 rounded-lg border px-3 py-2">
<ManaCoin />
<Input
type="number"
min={1}
step={1}
value={manaAmount || ''}
onChange={(e) => {
const val = e.target.value
if (val === '') {
setManaAmount(0)
} else {
setManaAmount(Math.floor(parseInt(val) || 0))
}
}}
className="!border-0 !bg-transparent !p-0 !ring-0"
/>
</Row>
</Row>
<Row className="flex-wrap gap-1.5">
{[100, 1000, 10000, 100000].map((n) => (
<button
key={n}
onClick={() => setManaAmount(n)}
className={clsx(
'rounded-md px-3 py-1.5 text-xs font-medium transition-colors',
manaAmount === n
? 'bg-primary-100 text-primary-700 dark:bg-primary-900/50 dark:text-primary-300'
: 'text-ink-600 hover:bg-canvas-100'
)}
>
{formatMoney(n)}
</button>
))}
</Row>
</Col>
{/* Buy Button */}
<Button
color="indigo"
size="lg"
onClick={handleBuyTickets}
loading={isSubmitting}
disabled={!selectedCharityId || numTickets <= 0 || isSubmitting}
className="w-full justify-center rounded-lg py-3 font-semibold"
>
Convert {formatMoney(manaAmount)} into {formatEntries(numTickets)}{' '}
entries
</Button>
</>
)}
</Col>
</div>
)
}
function SignInPrompt(props: { previewCharityId: string }) {
const { previewCharityId } = props
const previewCharity = previewCharityId
? charities.find((c) => c.id === previewCharityId)
: null
return (
<div className="bg-canvas-0 border-canvas-50 overflow-hidden rounded-xl border shadow-sm">
<div className="border-canvas-50 bg-canvas-50 border-b px-5 py-4">
<h3 className="text-ink-900 font-semibold">Get Entries</h3>
<p className="text-ink-500 mt-0.5 text-sm">
Support a charity and enter the drawing
</p>
</div>
<Col className="items-center gap-4 p-6">
{previewCharity ? (
<Row className="w-full gap-3 rounded-lg border border-primary-200 bg-primary-50 p-3 dark:border-primary-700 dark:bg-primary-950/30">
{previewCharity.photo && (
<img
src={previewCharity.photo}
alt={previewCharity.name}
className="h-12 w-12 flex-shrink-0 rounded-lg object-cover"
/>
)}
<Col className="min-w-0 flex-1 gap-0.5">
<div className="text-ink-900 text-sm font-medium">
{previewCharity.name}
</div>
<div className="text-ink-500 line-clamp-2 text-xs">
{previewCharity.preview}
</div>
</Col>
</Row>
) : (
<TbTicket className="text-ink-300 h-10 w-10" aria-hidden />
)}
<p className="text-ink-600 text-center text-sm">
Sign in to get entries and support your favorite charity
</p>
<Button color="indigo" className="w-full justify-center">
Sign in to participate
</Button>
</Col>
</div>
)
}
function GiveawayPieChart(props: {
charityStats: {
charityId: string
totalTickets: number
totalManaSpent: number
}[]
totalTickets: number
hoveredCharityId: string | null
onHoverCharity: (charityId: string | null) => void
onSelectCharity: (charityId: string) => void
myEntries?: number
}) {
const {
charityStats,
totalTickets,
hoveredCharityId,
onHoverCharity,
onSelectCharity,
myEntries,
} = props
if (charityStats.length === 0) {
return (
<div className="bg-canvas-0 border-canvas-50 flex flex-col items-center justify-center rounded-xl border p-12 shadow-sm">
<TbChartBar className="text-ink-200 mb-3 h-12 w-12" aria-hidden />
<p className="text-ink-900 font-medium">No entries yet</p>
<p className="text-ink-500 mt-1 text-sm">
Be the first to participate!
</p>
</div>
)
}
const sortedStats = sortBy(charityStats, (s) => -s.totalTickets)
const segments = sortedStats.map((stat, i) => {
const charity = charities.find((c) => c.id === stat.charityId)
return {
charityId: stat.charityId,
label: charity?.name ?? stat.charityId,
value: stat.totalTickets,
color: COLORS[i % COLORS.length],
}
})
const radius = 15
const circumference = 2 * Math.PI * radius
const segmentAngles: {
charityId: string
startAngle: number
endAngle: number
}[] = []
let currentAngle = 0
for (const segment of segments) {
const angle = (segment.value / totalTickets) * 360
segmentAngles.push({
charityId: segment.charityId,
startAngle: currentAngle,
endAngle: currentAngle + angle,
})
currentAngle += angle
}
const handleChartMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
const svg = e.currentTarget
const rect = svg.getBoundingClientRect()
const x = e.clientX - rect.left - rect.width / 2
const y = e.clientY - rect.top - rect.height / 2
const distance = Math.sqrt(x * x + y * y)
const maxRadius = rect.width / 2
const innerRadius = maxRadius * 0.5
const outerRadius = maxRadius * 0.95
if (distance < innerRadius || distance > outerRadius) {
return
}
let angle = Math.atan2(y, x) * (180 / Math.PI) + 90
if (angle < 0) angle += 360
for (const seg of segmentAngles) {
if (angle >= seg.startAngle && angle < seg.endAngle) {
if (hoveredCharityId !== seg.charityId) {
onHoverCharity(seg.charityId)
}
return
}
}
}
return (
<div className="bg-canvas-0 border-canvas-50 overflow-hidden rounded-xl border shadow-sm">
<div className="border-canvas-50 border-b px-5 py-4">
<Row className="items-start justify-between">
<div>
<h3 className="text-ink-900 font-semibold">Entry Distribution</h3>
<p className="text-ink-500 mt-0.5 text-sm">Breakdown by charity</p>
</div>
{myEntries != null && myEntries > 0 && (
<div className="bg-primary-50 text-primary-700 rounded-full px-3 py-1 text-sm font-medium">
You: {formatEntries(myEntries)}{' '}
{myEntries === 1 ? 'entry' : 'entries'}
</div>
)}
</Row>
</div>
<div className="p-5">
<Row className="flex-wrap items-center justify-center gap-8">
{/* Chart */}
<div className="relative" onMouseLeave={() => onHoverCharity(null)}>
<svg
width="200"
height="200"
viewBox="0 0 40 40"
className="-rotate-90 transform"
onMouseMove={handleChartMouseMove}
>
{/* Background circle */}
<circle
cx="20"
cy="20"
r={radius}
fill="transparent"
className="stroke-canvas-100"
strokeWidth="5"
/>
{/* Segments */}
{(() => {
let accumulatedOffset = 0
return segments.map((segment, index) => {
const isHovered = hoveredCharityId === segment.charityId
const strokeDasharray = `${
(segment.value / totalTickets) * circumference
} ${circumference}`
const strokeDashoffset = -accumulatedOffset
accumulatedOffset +=
(segment.value / totalTickets) * circumference
return (
<circle
key={index}
cx="20"
cy="20"
r={radius}
fill="transparent"
stroke={segment.color}
strokeWidth={isHovered ? 7 : 5}
strokeDasharray={strokeDasharray}
strokeDashoffset={strokeDashoffset}
className="cursor-pointer transition-all duration-200"
style={{
opacity: hoveredCharityId && !isHovered ? 0.3 : 1,
filter: isHovered
? 'drop-shadow(0 4px 6px rgba(0,0,0,0.15))'
: 'none',
}}
onClick={() => onSelectCharity(segment.charityId)}
/>
)
})
})()}
</svg>
<div className="absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 transform flex-col items-center justify-center">
<div className="text-ink-900 text-xl font-bold">
{Math.round(totalTickets).toLocaleString()}
</div>
<div className="text-ink-400 text-xs font-medium uppercase tracking-wide">
entries
</div>
</div>
</div>
{/* Legend */}
<Col className="gap-1">
{segments.slice(0, 8).map((segment, index) => {
const percentage = ((segment.value / totalTickets) * 100).toFixed(
1
)
const isHovered = hoveredCharityId === segment.charityId
return (
<Row
key={index}
className={clsx(
'cursor-pointer items-center gap-2.5 rounded-lg px-3 py-1.5 transition-all duration-150',
isHovered ? 'bg-canvas-100 shadow-sm' : 'hover:bg-canvas-50'
)}
onMouseEnter={() => onHoverCharity(segment.charityId)}
onMouseLeave={() => onHoverCharity(null)}
onClick={() => onSelectCharity(segment.charityId)}
>
<span
className={clsx(
'flex-shrink-0 rounded-full transition-all duration-150',
isHovered ? 'h-3 w-3' : 'h-2.5 w-2.5'
)}
style={{ backgroundColor: segment.color }}
/>
<span
className={clsx(
'max-w-[160px] truncate text-sm transition-all duration-150',
isHovered ? 'text-ink-900 font-medium' : 'text-ink-700'
)}
>
{segment.label}
</span>
<span
className={clsx(
'ml-auto whitespace-nowrap text-sm tabular-nums transition-all duration-150',
isHovered ? 'text-ink-700' : 'text-ink-400'
)}
>
{percentage}%
</span>
</Row>
)
})}
{segments.length > 8 && (
<div className="text-ink-400 px-3 py-1 text-xs">
+{segments.length - 8} more
</div>
)}
</Col>
</Row>
</div>
</div>
)
}
function SalesHistory(props: { giveawayNum: number; refreshKey: number }) {
const { giveawayNum, refreshKey } = props
const { data, refresh } = useAPIGetter('get-charity-giveaway-sales', {
giveawayNum,
limit: 50,
})
// Refresh sales when refreshKey changes
useEffect(() => {
if (refreshKey > 0) {
refresh()
}
}, [refreshKey])
const sales = data?.sales ?? []
if (sales.length === 0) {
return null
}
return (
<div className="bg-canvas-0 border-canvas-50 overflow-hidden rounded-xl border shadow-sm">
<div className="border-canvas-50 border-b px-5 py-4">
<h3 className="text-ink-900 font-semibold">Recent Activity</h3>
<p className="text-ink-500 mt-0.5 text-sm">Latest entry conversions</p>
</div>
<div className="overflow-x-auto">
<table className="min-w-full">
<thead>
<tr className="border-canvas-50 bg-canvas-50 border-b">
<th className="text-ink-500 px-5 py-3 text-left text-xs font-medium uppercase tracking-wider">
User
</th>
<th className="text-ink-500 px-5 py-3 text-left text-xs font-medium uppercase tracking-wider">
Charity
</th>
<th className="text-ink-500 px-5 py-3 text-right text-xs font-medium uppercase tracking-wider">
Entries
</th>
<th className="text-ink-500 px-5 py-3 text-right text-xs font-medium uppercase tracking-wider">
Cost
</th>
<th className="text-ink-500 px-5 py-3 text-right text-xs font-medium uppercase tracking-wider">
Time
</th>
</tr>
</thead>
<tbody className="divide-canvas-50 divide-y">
{sales.map((sale) => {
const charity = charities.find((c) => c.id === sale.charityId)
return (
<SaleRow
key={sale.id}
sale={sale}
charityName={charity?.name ?? sale.charityId}
/>
)
})}
</tbody>
</table>
</div>
</div>
)
}
function SaleRow(props: {
sale: {
id: string
userId: string
charityId: string
numTickets: number
manaSpent: number
createdTime: number
}
charityName: string
}) {
const { sale, charityName } = props
const { data: userData } = useAPIGetter('user/by-id/:id', { id: sale.userId })
return (
<tr className="hover:bg-canvas-50 transition-colors">
<td className="px-5 py-4">
{userData ? (
<Row className="items-center gap-2.5">
<Avatar
username={userData.username}
avatarUrl={userData.avatarUrl}
size="xs"
/>
<UserLink user={userData} className="text-sm font-medium" />
</Row>
) : (
<div className="bg-canvas-100 h-4 w-24 animate-pulse rounded" />
)}
</td>
<td className="text-ink-600 max-w-[180px] truncate px-5 py-4 text-sm">
{charityName}
</td>
<td className="text-ink-900 px-5 py-4 text-right text-sm font-medium tabular-nums">
{formatEntries(sale.numTickets)}
</td>
<td className="text-ink-600 px-5 py-4 text-right text-sm tabular-nums">
{formatMoneyAuto(sale.manaSpent)}
</td>
<td className="text-ink-400 px-5 py-4 text-right text-sm">
<RelativeTimestamp time={sale.createdTime} />
</td>
</tr>
)
}
function WinnerCard(props: {
winningCharity: string
winner?: { id: string; username: string; name: string; avatarUrl: string }
prizeAmount: number
charityStats: { charityId: string; totalTickets: number }[]
totalTickets: number
onReplay: () => void
}) {
const {
winningCharity,
winner,
prizeAmount,
charityStats,
totalTickets,
onReplay,
} = props
const charity = charities.find((c) => c.id === winningCharity)
const charityTickets =
charityStats.find((s) => s.charityId === winningCharity)?.totalTickets ?? 0
const percentage =
totalTickets > 0 ? (charityTickets / totalTickets) * 100 : 0
return (
<div className="overflow-hidden rounded-xl border border-amber-200 bg-gradient-to-br from-amber-50 via-yellow-50 to-orange-50 p-6 shadow-lg dark:border-amber-800 dark:from-amber-950/30 dark:via-yellow-950/30 dark:to-orange-950/30">
<Col className="items-center gap-4">
<TbTrophy className="h-12 w-12 text-amber-500" aria-hidden />
<h2 className="text-ink-900 text-2xl font-bold">Winner!</h2>
{charity && (
<Row className="w-full max-w-md items-center gap-4 rounded-xl border border-amber-200 bg-white/80 p-4 dark:border-amber-700 dark:bg-ink-900/50">
{charity.photo && (
<img
src={charity.photo}
alt={charity.name}
className="h-16 w-16 flex-shrink-0 rounded-lg object-cover shadow"
/>
)}
<Col className="min-w-0 flex-1 gap-1">
<div className="text-ink-900 text-lg font-bold">
{charity.name}
</div>
<div className="text-ink-500 line-clamp-2 text-sm">
{charity.preview}
</div>
<div className="text-ink-600 mt-1 text-sm">
<span className="font-semibold text-amber-600 dark:text-amber-400">
{percentage.toFixed(1)}%
</span>{' '}
of entries ({formatEntries(charityTickets)})
</div>
</Col>
</Row>
)}
<div className="text-center">
<p className="text-ink-900 text-lg">
<span className="font-bold text-teal-600 dark:text-teal-400">
${prizeAmount.toLocaleString()}
</span>{' '}
will be donated!
</p>
{winner && (
<Row className="text-ink-600 mt-2 items-center justify-center gap-2 text-sm">
<span>Winning entry converted by</span>
<Avatar
username={winner.username}
avatarUrl={winner.avatarUrl}
size="xs"
/>
<UserLink user={winner} className="text-ink-900 font-medium" />
</Row>
)}
</div>
<button
onClick={onReplay}
className="text-ink-500 hover:text-ink-700 mt-2 text-sm underline transition-colors"
>
<TbRotateClockwise className="mr-1 inline h-4 w-4" aria-hidden />
Watch the spin again
</button>
</Col>
</div>
)
}
function ProvablyFairBanner(props: {
giveawayNum: number
closeTime: number
blockHash?: string
hasWinner: boolean
}) {
const { giveawayNum, closeTime, blockHash, hasWinner } = props
const [isModalOpen, setIsModalOpen] = useState(false)
const [isCheckingBlock, setIsCheckingBlock] = useState(false)
const [blockInfo, setBlockInfo] = useState<{
height: number
hash: string
} | null>(null)
const isClosed = closeTime <= Date.now()
const isLegacyGiveaway = giveawayNum === 1
const handleCheckBlock = async () => {
setIsCheckingBlock(true)
try {
const result = await api('check-bitcoin-block', { closeTime })
if (result.available) {
setBlockInfo({ height: result.blockHeight, hash: result.blockHash })
} else {
toast.error('Bitcoin block not yet mined. Please try again later.')
}
} catch (e) {
toast.error('Failed to check Bitcoin block')
} finally {
setIsCheckingBlock(false)
}
}
const displayHash = blockHash || blockInfo?.hash
const displayHeight = blockInfo?.height
return (
<>
<Row className="items-center justify-center">
<button
onClick={() => setIsModalOpen(true)}
className="dark:from-primary-400/15 dark:via-purple-400/15 dark:to-pink-400/15 inline-flex items-center gap-2 rounded-full bg-gradient-to-r from-primary-500/10 via-purple-500/10 to-pink-500/10 px-4 py-2 ring-1 ring-primary-500/20 transition-all hover:ring-primary-500/40 dark:ring-primary-400/25 dark:hover:ring-primary-400/40"
>
<TbScale className="h-4 w-4 text-primary-600 dark:text-primary-400" aria-hidden />
<span className="bg-gradient-to-r from-primary-600 via-purple-600 to-pink-600 bg-clip-text text-sm font-semibold text-transparent dark:from-primary-400 dark:via-purple-400 dark:to-pink-400">
Provably fair
</span>
</button>
</Row>
<Modal open={isModalOpen} setOpen={setIsModalOpen} size="md">
<Col className={clsx(MODAL_CLASS, 'gap-4')}>
<Row className="items-center gap-3">
<TbScale className="text-ink-700 h-7 w-7" aria-hidden />
<h2 className="text-ink-900 text-xl font-bold">Provably Fair</h2>
</Row>
{isLegacyGiveaway ? (
<>
<p className="text-ink-700 text-sm">
This giveaway used our original method: a secret nonce combined
with timestamps of the last 10 purchases.
</p>
{hasWinner && blockHash && (
<Col className="bg-canvas-50 gap-2 rounded-lg p-3">
<span className="text-ink-600 text-sm font-medium">
Nonce
</span>
<code className="bg-canvas-100 text-ink-900 break-all rounded px-2 py-1 font-mono text-xs">
{blockHash}
</code>
</Col>
)}
{hasWinner && (
<p className="inline-flex items-center gap-1 text-sm text-green-700 dark:text-green-400">
<TbCircleCheck className="h-4 w-4 shrink-0" aria-hidden />
Winner selected using the original method.
</p>
)}
</>
) : (
<>
<p className="text-ink-700 text-sm">
Winner determined by the first Bitcoin block mined after{' '}
<span className="font-semibold">
{new Date(closeTime).toLocaleString()}
</span>
. The block hash seeds a deterministic RNG. Verify on any block
explorer.
</p>
{displayHash && (
<Col className="bg-canvas-50 gap-2 rounded-lg p-3">
<Row className="items-center justify-between">
<span className="text-ink-600 text-sm font-medium">
Block{displayHeight ? ` #${displayHeight}` : ''}
</span>
<Row className="gap-2">
<a
href={`https://mempool.space/block/${displayHash}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary-600 text-xs hover:underline"
>
mempool.space
</a>
<a
href={`https://blockstream.info/block/${displayHash}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary-600 text-xs hover:underline"
>
blockstream
</a>
</Row>
</Row>
<code className="bg-canvas-100 text-ink-900 break-all rounded px-2 py-1 font-mono text-xs">
{displayHash}
</code>
</Col>
)}
{hasWinner && blockHash ? (
<p className="inline-flex items-center gap-1 text-sm text-green-700 dark:text-green-400">
<TbCircleCheck className="h-4 w-4 shrink-0" aria-hidden />
Winner selected using the block hash above.
</p>
) : isClosed && !hasWinner ? (
<Col className="gap-2">
<p className="inline-flex items-center gap-1 text-sm text-amber-700 dark:text-amber-400">
<TbHourglass className="h-4 w-4 shrink-0" aria-hidden />
Giveaway closed. Awaiting winner selection.
</p>
{!displayHash && (
<Button
color="indigo"
size="xs"
onClick={handleCheckBlock}
loading={isCheckingBlock}
disabled={isCheckingBlock}
>
Check for Bitcoin Block
</Button>
)}
</Col>
) : (
<p className="inline-flex items-center gap-1 text-sm text-amber-700 dark:text-amber-400">
<TbHourglass className="h-4 w-4 shrink-0" aria-hidden />
Awaiting close time to determine block.
</p>
)}
</>
)}
</Col>
</Modal>
</>
)
}
const ADJUST_PRIZE_CONFIRM_PHRASE = 'update prize'
function AdjustPrizeModal(props: {
open: boolean
setOpen: (open: boolean) => void
giveawayNum: number
currentPrizeAmount: number
adjustPrizeAmount: string
setAdjustPrizeAmount: (value: string) => void
isAdjustingPrize: boolean
onAdjust: () => void
}) {
const {
open,
setOpen,
giveawayNum,
currentPrizeAmount,
adjustPrizeAmount,
setAdjustPrizeAmount,
isAdjustingPrize,
onAdjust,
} = props
const [confirmText, setConfirmText] = useState('')
useEffect(() => {
if (open) setConfirmText('')
}, [open])
const parsed = Number(adjustPrizeAmount)
const delta =
Number.isFinite(parsed) && parsed > 0 ? parsed - currentPrizeAmount : 0
const exceedsCap = Math.abs(delta) > MAX_CHARITY_GIVEAWAY_PRIZE_DELTA_USD
const isAmountValid =
Number.isFinite(parsed) &&
parsed > 0 &&
parsed !== currentPrizeAmount &&
!exceedsCap
const isConfirmed = confirmText.trim() === ADJUST_PRIZE_CONFIRM_PHRASE
const adjustBy = (amount: number) => {
const next = (Number(adjustPrizeAmount) || 0) + amount
setAdjustPrizeAmount(String(Math.max(0, next)))
}
return (
<Modal open={open} setOpen={setOpen} size="md">
<Col className={clsx(MODAL_CLASS, 'gap-5')}>
<Col className="gap-1">
<h3 className="text-ink-900 text-lg font-semibold">
Adjust prize pool
</h3>
<p className="text-ink-500 text-sm">
Edit the prize amount for Giveaway #{giveawayNum}. Current:{' '}
<span className="text-ink-700 font-medium">
${currentPrizeAmount.toLocaleString()}
</span>
</p>
</Col>
<Col className="gap-2">
<label className="text-ink-700 text-sm font-medium">
New prize amount (USD)
</label>
<Input
type="number"
min="0"
step="0.01"
value={adjustPrizeAmount}
onChange={(e) => setAdjustPrizeAmount(e.target.value)}
/>
<Row className="flex-wrap gap-1.5">
{[-100, -10, +10, +100, +1000].map((n) => (
<button
key={n}
onClick={() => adjustBy(n)}
className="text-ink-600 hover:bg-canvas-100 rounded-md px-3 py-1.5 text-xs font-medium transition-colors"
>
{n > 0 ? `+$${n}` : `-$${Math.abs(n)}`}
</button>
))}
</Row>
{delta !== 0 && (
<p
className={clsx(
'text-xs',
exceedsCap ? 'text-red-600 dark:text-red-400' : 'text-ink-500'
)}
>
Change: {delta > 0 ? '+' : ''}${delta.toLocaleString()}
{exceedsCap &&
` — exceeds the $${MAX_CHARITY_GIVEAWAY_PRIZE_DELTA_USD.toLocaleString()} per-adjustment cap. Make multiple smaller changes.`}
</p>
)}
</Col>
<Col className="gap-2">
<label className="text-ink-700 text-sm font-medium">
Type{' '}
<span className="bg-canvas-100 text-ink-900 rounded px-1.5 py-0.5 font-mono text-xs">
{ADJUST_PRIZE_CONFIRM_PHRASE}
</span>{' '}
to confirm
</label>
<Input
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
placeholder={ADJUST_PRIZE_CONFIRM_PHRASE}
autoComplete="off"
/>
</Col>
<Row className="justify-end gap-2">
<Button color="gray-outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
color="indigo"
loading={isAdjustingPrize}
disabled={isAdjustingPrize || !isAmountValid || !isConfirmed}
onClick={onAdjust}
>
Save
</Button>
</Row>
</Col>
</Modal>
)
}
function CreateGiveawayModal(props: {
open: boolean
setOpen: (open: boolean) => void
newCloseTime: string
setNewCloseTime: (value: string) => void
newPrizeAmount: string
setNewPrizeAmount: (value: string) => void
isCreatingGiveaway: boolean
onCreate: () => void
}) {
const {
open,
setOpen,
newCloseTime,
setNewCloseTime,
newPrizeAmount,
setNewPrizeAmount,
isCreatingGiveaway,
onCreate,
} = props
return (
<Modal open={open} setOpen={setOpen} size="md">
<Col className={clsx(MODAL_CLASS, 'gap-5')}>
<Col className="gap-1">
<h3 className="text-ink-900 text-lg font-semibold">
Create New Charity Giveaway
</h3>
<p className="text-ink-500 text-sm">
Set a close date/time and prize pool amount.
</p>
</Col>
<Col className="gap-2">
<label className="text-ink-700 text-sm font-medium">Close time</label>
<Input
type="datetime-local"
value={newCloseTime}
onChange={(e) => setNewCloseTime(e.target.value)}
/>
</Col>
<Col className="gap-2">
<label className="text-ink-700 text-sm font-medium">
Prize pool (USD)
</label>
<Input
type="number"
min="0"
step="0.01"
value={newPrizeAmount}
onChange={(e) => setNewPrizeAmount(e.target.value)}
/>
</Col>
<Row className="justify-end gap-2">
<Button color="gray-outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
color="indigo"
loading={isCreatingGiveaway}
disabled={isCreatingGiveaway}
onClick={onCreate}
>
Create giveaway
</Button>
</Row>
</Col>
</Modal>
)
}