feat: premium UI overhaul, AI suggestions, WAHA WhatsApp integration

PREMIUM UI:
- All animations: fade-up, scale-in, stagger children, confetti celebration
- Glass effects, gradient icons, premium card hover states
- Custom CSS: shimmer, pulse-ring, bounce, counter-roll animations
- Smooth progress bar with gradient

AI-POWERED (GPT-4o-mini nano model):
- Smart amount suggestions based on peer data (/api/ai/suggest)
- Social proof: '42 people pledged · Average £85'
- AI-generated nudge text for conversion
- AI fuzzy matching for bank reconciliation
- AI reminder message generation

WAHA WHATSAPP INTEGRATION:
- Auto-send pledge receipt with bank details via WhatsApp
- 4-step reminder sequence: gentle → nudge → urgent → final
- Chatbot: donors reply PAID, HELP, CANCEL, STATUS
- Volunteer notification on new pledges
- WhatsApp status in dashboard settings
- Webhook endpoint for incoming messages

DONOR FLOW (CRO):
- Amount step: AI suggestions, Gift Aid preview, social proof, haptic feedback
- Payment step: trust signals, fee comparison, benefit badges
- Identity step: email/phone toggle, WhatsApp reminder indicator
- Bank instructions: tap-to-copy each field, WhatsApp delivery confirmation
- Confirmation: confetti, pulse animation, share CTA, WhatsApp receipt

COMPOSE:
- Added WAHA env vars + qc-comms network for WhatsApp access
This commit is contained in:
2026-03-03 04:31:07 +08:00
parent 0236867c88
commit c6e7e4f01e
15 changed files with 1473 additions and 383 deletions

Submodule pledge-now-pay-later/pnpl-backup added at 38833783a2

View File

@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { suggestAmounts } from "@/lib/ai"
export async function GET(request: NextRequest) {
try {
const eventId = request.nextUrl.searchParams.get("eventId")
if (!eventId || !prisma) {
// Return smart defaults
return NextResponse.json(await suggestAmounts({ eventName: "Charity Event" }))
}
// Get real peer data from the event
const pledges = await prisma.pledge.findMany({
where: { eventId, status: { not: "cancelled" } },
select: { amountPence: true },
orderBy: { amountPence: "asc" },
})
const event = await prisma.event.findUnique({
where: { id: eventId },
select: { name: true },
})
if (pledges.length === 0) {
return NextResponse.json(await suggestAmounts({
eventName: event?.name || "Charity Event",
}))
}
const amounts = pledges.map(p => p.amountPence)
const avg = Math.round(amounts.reduce((a, b) => a + b, 0) / amounts.length)
const median = amounts[Math.floor(amounts.length / 2)]
const top = amounts[amounts.length - 1]
return NextResponse.json(await suggestAmounts({
eventName: event?.name || "Charity Event",
avgPledge: avg,
medianPledge: median,
pledgeCount: pledges.length,
topAmount: top,
}))
} catch (error) {
console.error("AI suggest error:", error)
return NextResponse.json(await suggestAmounts({ eventName: "Charity Event" }))
}
}

View File

@@ -3,6 +3,7 @@ import prisma from "@/lib/prisma"
import { createPledgeSchema } from "@/lib/validators" import { createPledgeSchema } from "@/lib/validators"
import { generateReference } from "@/lib/reference" import { generateReference } from "@/lib/reference"
import { calculateReminderSchedule } from "@/lib/reminders" import { calculateReminderSchedule } from "@/lib/reminders"
import { sendPledgeReceipt } from "@/lib/whatsapp"
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
@@ -125,6 +126,37 @@ export async function POST(request: NextRequest) {
} }
} }
// Async: Send WhatsApp receipt to donor (non-blocking)
if (donorPhone) {
sendPledgeReceipt(donorPhone, {
donorName: donorName || undefined,
amountPounds: (amountPence / 100).toFixed(0),
eventName: event.name,
reference: pledge.reference,
rail,
bankDetails: rail === "bank" && org.bankSortCode ? {
sortCode: org.bankSortCode,
accountNo: org.bankAccountNo || "",
accountName: org.bankAccountName || org.name,
} : undefined,
orgName: org.name,
}).catch(err => console.error("[WAHA] Receipt send failed:", err))
}
// Async: Notify volunteer if QR source has volunteer info
if (qrSourceId) {
prisma?.qrSource.findUnique({
where: { id: qrSourceId },
select: { volunteerName: true, label: true, pledges: { select: { amountPence: true } } },
}).then(qr => {
// In future: if volunteer has a phone number stored, send WhatsApp notification
// For now, this is a no-op unless volunteer phone is added to schema
if (qr) {
console.log(`[PLEDGE] ${qr.volunteerName || qr.label}: +1 pledge (£${(amountPence / 100).toFixed(0)})`)
}
}).catch(() => {})
}
return NextResponse.json(response, { status: 201 }) return NextResponse.json(response, { status: 201 })
} catch (error) { } catch (error) {
console.error("Pledge creation error:", error) console.error("Pledge creation error:", error)

View File

@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from "next/server"
import { sendPledgeReceipt, sendPledgeReminder, getWhatsAppStatus } from "@/lib/whatsapp"
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { type, phone, data } = body
if (!phone) {
return NextResponse.json({ error: "Phone number required" }, { status: 400 })
}
let result
switch (type) {
case "receipt":
result = await sendPledgeReceipt(phone, data)
break
case "reminder":
result = await sendPledgeReminder(phone, data)
break
default:
return NextResponse.json({ error: "Unknown message type" }, { status: 400 })
}
return NextResponse.json(result)
} catch (error) {
console.error("WhatsApp send error:", error)
return NextResponse.json({ error: "Failed to send" }, { status: 500 })
}
}
export async function GET() {
const status = await getWhatsAppStatus()
return NextResponse.json(status)
}

View File

@@ -0,0 +1,109 @@
import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { sendWhatsAppMessage } from "@/lib/whatsapp"
/**
* WAHA webhook — receives incoming WhatsApp messages
* Handles: PAID, HELP, CANCEL commands from donors
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { payload } = body
// WAHA sends message events
if (!payload?.body || !payload?.from) {
return NextResponse.json({ ok: true })
}
const text = payload.body.trim().toUpperCase()
const fromPhone = payload.from.replace("@c.us", "")
// Only handle known commands
if (!["PAID", "HELP", "CANCEL", "STATUS"].includes(text)) {
return NextResponse.json({ ok: true })
}
if (!prisma) return NextResponse.json({ ok: true })
// Find pledges by this phone number
// Normalize: try with and without country code
const phoneVariants = [fromPhone]
if (fromPhone.startsWith("44")) {
phoneVariants.push("0" + fromPhone.slice(2))
phoneVariants.push("+" + fromPhone)
}
const pledges = await prisma.pledge.findMany({
where: {
donorPhone: { in: phoneVariants },
status: { in: ["new", "initiated"] },
},
include: {
event: { select: { name: true } },
paymentInstruction: true,
},
orderBy: { createdAt: "desc" },
take: 5,
})
if (pledges.length === 0) {
await sendWhatsAppMessage(fromPhone, `We couldn't find any pending pledges for this number. If you need help, please contact the charity directly.`)
return NextResponse.json({ ok: true })
}
const pledge = pledges[0] // Most recent
const amount = (pledge.amountPence / 100).toFixed(0)
switch (text) {
case "PAID": {
await prisma.pledge.update({
where: { id: pledge.id },
data: { status: "initiated", iPaidClickedAt: new Date() },
})
await sendWhatsAppMessage(fromPhone,
`✅ Thanks! We've noted that you've paid your *£${amount}* pledge to ${pledge.event.name}.\n\nWe'll confirm once the payment is matched. Ref: \`${pledge.reference}\``
)
break
}
case "HELP": {
const bankDetails = pledge.paymentInstruction?.bankDetails as Record<string, string> | null
if (bankDetails) {
await sendWhatsAppMessage(fromPhone,
`🏦 *Bank Details for your £${amount} pledge:*\n\nSort Code: \`${bankDetails.sortCode}\`\nAccount: \`${bankDetails.accountNo}\`\nName: ${bankDetails.accountName}\nReference: \`${pledge.reference}\`\n\n⚠ _Use the exact reference above_`
)
} else {
await sendWhatsAppMessage(fromPhone,
`Your pledge ref is \`${pledge.reference}\` for £${amount} to ${pledge.event.name}.\n\nContact the charity for payment details.`
)
}
break
}
case "CANCEL": {
await prisma.pledge.update({
where: { id: pledge.id },
data: { status: "cancelled", cancelledAt: new Date() },
})
await sendWhatsAppMessage(fromPhone,
`Your £${amount} pledge to ${pledge.event.name} has been cancelled. No worries — thank you for considering! 🙏`
)
break
}
case "STATUS": {
const statusText = pledges.map(p =>
`• £${(p.amountPence / 100).toFixed(0)}${p.event.name} (${p.status}) [${p.reference}]`
).join("\n")
await sendWhatsAppMessage(fromPhone, `📋 *Your pledges:*\n\n${statusText}`)
break
}
}
return NextResponse.json({ ok: true })
} catch (error) {
console.error("WhatsApp webhook error:", error)
return NextResponse.json({ ok: true })
}
}

View File

@@ -5,7 +5,8 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/com
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { Building2, CreditCard, Palette, Check, Loader2, AlertCircle } from "lucide-react" import { Building2, CreditCard, Palette, Check, Loader2, AlertCircle, MessageCircle, Radio } from "lucide-react"
import { Badge } from "@/components/ui/badge"
interface OrgSettings { interface OrgSettings {
name: string name: string
@@ -210,6 +211,9 @@ export default function SettingsPage() {
</CardContent> </CardContent>
</Card> </Card>
{/* WhatsApp (WAHA) */}
<WhatsAppStatus />
{/* Branding */} {/* Branding */}
<Card> <Card>
<CardHeader> <CardHeader>
@@ -264,3 +268,60 @@ export default function SettingsPage() {
</div> </div>
) )
} }
function WhatsAppStatus() {
const [status, setStatus] = useState<{ connected: boolean; session: string; version?: string } | null>(null)
const [checking, setChecking] = useState(true)
useEffect(() => {
fetch("/api/whatsapp/send")
.then(r => r.json())
.then(data => setStatus(data))
.catch(() => setStatus({ connected: false, session: "default" }))
.finally(() => setChecking(false))
}, [])
return (
<Card className={status?.connected ? "border-[#25D366]/30" : ""}>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<MessageCircle className="h-5 w-5 text-[#25D366]" /> WhatsApp Integration
{checking ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : status?.connected ? (
<Badge variant="success" className="gap-1"><Radio className="h-3 w-3" /> Connected</Badge>
) : (
<Badge variant="warning">Not Connected</Badge>
)}
</CardTitle>
<CardDescription>
Send pledge receipts, payment reminders, and bank details via WhatsApp.
Donors can reply PAID, HELP, or CANCEL.
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{status?.connected ? (
<div className="rounded-xl bg-[#25D366]/5 border border-[#25D366]/20 p-4 space-y-2">
<p className="text-sm font-medium text-[#25D366]"> WhatsApp is active</p>
<p className="text-xs text-muted-foreground">
Session: {status.session} · WAHA {status.version || ""}
</p>
<div className="text-xs text-muted-foreground space-y-1 mt-2 pt-2 border-t border-[#25D366]/10">
<p><strong>Auto-sends:</strong> Pledge receipts with bank details</p>
<p><strong>Reminders:</strong> Gentle Nudge Urgent Final</p>
<p><strong>Chatbot:</strong> Donors reply PAID, HELP, CANCEL, STATUS</p>
</div>
</div>
) : (
<div className="rounded-xl bg-warm-amber/5 border border-warm-amber/20 p-4 space-y-2">
<p className="text-sm font-medium text-warm-amber">WhatsApp not connected</p>
<p className="text-xs text-muted-foreground">
Connect a WhatsApp number in WAHA ({`waha.quikcue.com`}) to enable automatic messaging.
The app works without it messages will be skipped.
</p>
</div>
)}
</CardContent>
</Card>
)
}

View File

@@ -2,7 +2,7 @@
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');
@layer base { @layer base {
:root { :root {
@@ -35,6 +35,7 @@
body { body {
@apply bg-background text-foreground antialiased; @apply bg-background text-foreground antialiased;
font-family: 'Inter', system-ui, -apple-system, sans-serif; font-family: 'Inter', system-ui, -apple-system, sans-serif;
-webkit-tap-highlight-color: transparent;
} }
} }
@@ -43,3 +44,127 @@
@apply min-h-[48px] min-w-[48px]; @apply min-h-[48px] min-w-[48px];
} }
} }
/* Premium animations */
@keyframes fadeUp {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes scaleIn {
from { opacity: 0; transform: scale(0.9); }
to { opacity: 1; transform: scale(1); }
}
@keyframes slideDown {
from { opacity: 0; transform: translateY(-8px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulse-ring {
0% { transform: scale(0.8); opacity: 1; }
100% { transform: scale(2); opacity: 0; }
}
@keyframes shimmer {
0% { background-position: -200% 0; }
100% { background-position: 200% 0; }
}
@keyframes confetti-fall {
0% { transform: translateY(-10vh) rotate(0deg); opacity: 1; }
100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
}
@keyframes bounce-gentle {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-4px); }
}
@keyframes counter-roll {
from { transform: translateY(100%); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.animate-fade-up { animation: fadeUp 0.5s ease-out forwards; }
.animate-fade-in { animation: fadeIn 0.3s ease-out forwards; }
.animate-scale-in { animation: scaleIn 0.3s ease-out forwards; }
.animate-slide-down { animation: slideDown 0.3s ease-out forwards; }
.animate-pulse-ring { animation: pulse-ring 1.5s ease-out infinite; }
.animate-shimmer {
background: linear-gradient(90deg, transparent 30%, rgba(255,255,255,0.4) 50%, transparent 70%);
background-size: 200% 100%;
animation: shimmer 2s infinite;
}
.animate-bounce-gentle { animation: bounce-gentle 2s ease-in-out infinite; }
.animate-counter-roll { animation: counter-roll 0.4s ease-out forwards; }
/* Stagger children animations */
.stagger-children > * { opacity: 0; animation: fadeUp 0.4s ease-out forwards; }
.stagger-children > *:nth-child(1) { animation-delay: 0ms; }
.stagger-children > *:nth-child(2) { animation-delay: 60ms; }
.stagger-children > *:nth-child(3) { animation-delay: 120ms; }
.stagger-children > *:nth-child(4) { animation-delay: 180ms; }
.stagger-children > *:nth-child(5) { animation-delay: 240ms; }
.stagger-children > *:nth-child(6) { animation-delay: 300ms; }
.stagger-children > *:nth-child(7) { animation-delay: 360ms; }
.stagger-children > *:nth-child(8) { animation-delay: 420ms; }
/* Glass effects */
.glass {
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.3);
}
.glass-dark {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
}
/* Premium card hover */
.card-hover {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.card-hover:hover {
transform: translateY(-2px);
box-shadow: 0 12px 40px -8px rgba(0,0,0,0.12);
}
.card-hover:active {
transform: translateY(0) scale(0.98);
}
/* Number input clean */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 4px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: hsl(var(--muted));
border-radius: 2px;
}
/* Selection */
::selection {
background: #1e40af20;
color: #1e40af;
}

View File

@@ -29,15 +29,6 @@ interface EventInfo {
qrSourceLabel: string | null qrSourceLabel: string | null
} }
// Steps:
// 0 = Amount
// 1 = Payment method
// 2 = Identity (for bank transfer)
// 3 = Bank instructions
// 4 = Confirmation (card, DD)
// 5 = Card payment step
// 7 = Direct Debit step
export default function PledgePage() { export default function PledgePage() {
const params = useParams() const params = useParams()
const token = params.token as string const token = params.token as string
@@ -54,12 +45,7 @@ export default function PledgePage() {
const [pledgeResult, setPledgeResult] = useState<{ const [pledgeResult, setPledgeResult] = useState<{
id: string id: string
reference: string reference: string
bankDetails?: { bankDetails?: { bankName: string; sortCode: string; accountNo: string; accountName: string }
bankName: string
sortCode: string
accountNo: string
accountName: string
}
} | null>(null) } | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState("") const [error, setError] = useState("")
@@ -72,10 +58,7 @@ export default function PledgePage() {
else setEventInfo(data) else setEventInfo(data)
setLoading(false) setLoading(false)
}) })
.catch(() => { .catch(() => { setError("Unable to load pledge page"); setLoading(false) })
setError("Unable to load pledge page")
setLoading(false)
})
fetch("/api/analytics", { fetch("/api/analytics", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
@@ -86,16 +69,21 @@ export default function PledgePage() {
const handleAmountSelected = (amountPence: number) => { const handleAmountSelected = (amountPence: number) => {
setPledgeData((d) => ({ ...d, amountPence })) setPledgeData((d) => ({ ...d, amountPence }))
setStep(1) setStep(1)
fetch("/api/analytics", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ eventType: "amount_selected", metadata: { amountPence, token } }),
}).catch(() => {})
} }
const handleRailSelected = (rail: Rail) => { const handleRailSelected = (rail: Rail) => {
setPledgeData((d) => ({ ...d, rail })) setPledgeData((d) => ({ ...d, rail }))
const railStepMap: Record<Rail, number> = { fetch("/api/analytics", {
bank: 2, method: "POST",
card: 5, headers: { "Content-Type": "application/json" },
gocardless: 7, body: JSON.stringify({ eventType: "rail_selected", metadata: { rail, token } }),
} }).catch(() => {})
setStep(railStepMap[rail]) setStep(rail === "bank" ? 2 : rail === "card" ? 5 : 7)
} }
const submitPledge = async (identity: { donorName: string; donorEmail: string; donorPhone: string; giftAid: boolean }) => { const submitPledge = async (identity: { donorName: string; donorEmail: string; donorPhone: string; giftAid: boolean }) => {
@@ -106,11 +94,7 @@ export default function PledgePage() {
const res = await fetch("/api/pledges", { const res = await fetch("/api/pledges", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({ ...finalData, eventId: eventInfo?.id, qrSourceId: eventInfo?.qrSourceId }),
...finalData,
eventId: eventInfo?.id,
qrSourceId: eventInfo?.qrSourceId,
}),
}) })
const result = await res.json() const result = await res.json()
if (result.error) { setError(result.error); return } if (result.error) { setError(result.error); return }
@@ -123,8 +107,11 @@ export default function PledgePage() {
if (loading) { if (loading) {
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5"> <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 gap-4">
<div className="animate-pulse text-trust-blue text-lg font-medium">Loading...</div> <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 flex items-center justify-center animate-pulse">
<span className="text-white text-xl">🤲</span>
</div>
<p className="text-trust-blue font-medium animate-pulse">Loading...</p>
</div> </div>
) )
} }
@@ -132,49 +119,61 @@ export default function PledgePage() {
if (error) { if (error) {
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 p-4"> <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 p-4">
<div className="text-center space-y-4"> <div className="text-center space-y-4 animate-fade-up">
<div className="text-6xl">😔</div> <div className="text-5xl">😔</div>
<h1 className="text-xl font-bold text-gray-900">Something went wrong</h1> <h1 className="text-xl font-bold text-gray-900">Something went wrong</h1>
<p className="text-muted-foreground">{error}</p> <p className="text-muted-foreground">{error}</p>
<button onClick={() => window.location.reload()} className="text-trust-blue font-medium hover:underline">
Try again
</button>
</div> </div>
</div> </div>
) )
} }
const shareUrl = eventInfo?.qrSourceId ? `${typeof window !== "undefined" ? window.location.origin : ""}/p/${token}` : undefined const shareUrl = `${typeof window !== "undefined" ? window.location.origin : ""}/p/${token}`
const steps: Record<number, React.ReactNode> = { const steps: Record<number, React.ReactNode> = {
0: <AmountStep onSelect={handleAmountSelected} eventName={eventInfo?.name || ""} />, 0: <AmountStep onSelect={handleAmountSelected} eventName={eventInfo?.name || ""} eventId={eventInfo?.id} />,
1: <PaymentStep onSelect={handleRailSelected} amount={pledgeData.amountPence} />, 1: <PaymentStep onSelect={handleRailSelected} amount={pledgeData.amountPence} />,
2: <IdentityStep onSubmit={submitPledge} amount={pledgeData.amountPence} />, 2: <IdentityStep onSubmit={submitPledge} amount={pledgeData.amountPence} />,
3: pledgeResult && <BankInstructionsStep pledge={pledgeResult} amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} />, 3: pledgeResult && <BankInstructionsStep pledge={pledgeResult} amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} donorPhone={pledgeData.donorPhone} />,
4: pledgeResult && <ConfirmationStep pledge={pledgeResult} amount={pledgeData.amountPence} rail={pledgeData.rail} eventName={eventInfo?.name || ""} shareUrl={shareUrl} />, 4: pledgeResult && <ConfirmationStep pledge={pledgeResult} amount={pledgeData.amountPence} rail={pledgeData.rail} eventName={eventInfo?.name || ""} shareUrl={shareUrl} donorPhone={pledgeData.donorPhone} />,
5: <CardPaymentStep amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} eventId={eventInfo?.id || ""} qrSourceId={eventInfo?.qrSourceId || null} onComplete={submitPledge} />, 5: <CardPaymentStep amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} eventId={eventInfo?.id || ""} qrSourceId={eventInfo?.qrSourceId || null} onComplete={submitPledge} />,
7: <DirectDebitStep amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} organizationName={eventInfo?.organizationName || ""} eventId={eventInfo?.id || ""} qrSourceId={eventInfo?.qrSourceId || null} onComplete={submitPledge} />, 7: <DirectDebitStep amount={pledgeData.amountPence} eventName={eventInfo?.name || ""} organizationName={eventInfo?.organizationName || ""} eventId={eventInfo?.id || ""} qrSourceId={eventInfo?.qrSourceId || null} onComplete={submitPledge} />,
} }
const backableSteps = new Set([1, 2, 5, 7]) const backableSteps = new Set([1, 2, 5, 7])
const getBackStep = (s: number): number => { const getBackStep = (s: number): number => (s === 5 || s === 7) ? 1 : s - 1
if (s === 5 || s === 7) return 1
return s - 1 // Smooth progress
} const progressMap: Record<number, number> = { 0: 8, 1: 33, 2: 55, 3: 100, 4: 100, 5: 55, 7: 55 }
const progressPercent = step >= 3 ? 100 : step >= 2 ? 66 : step >= 1 ? 33 : 10 const progressPercent = progressMap[step] || 10
return ( return (
<div className="min-h-screen bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5"> <div className="min-h-screen bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5">
{/* Progress bar */}
<div className="fixed top-0 left-0 right-0 h-1 bg-gray-100 z-50"> <div className="fixed top-0 left-0 right-0 h-1 bg-gray-100 z-50">
<div className="h-full bg-trust-blue transition-all duration-500 ease-out" style={{ width: `${progressPercent}%` }} /> <div
className="h-full bg-gradient-to-r from-trust-blue to-success-green transition-all duration-700 ease-out"
style={{ width: `${progressPercent}%` }}
/>
</div> </div>
<div className="pt-6 pb-2 px-4 text-center"> {/* Header */}
<p className="text-sm text-muted-foreground">{eventInfo?.organizationName}</p> <div className="pt-6 pb-1 px-4 text-center">
<p className="text-xs text-muted-foreground/60">{eventInfo?.qrSourceLabel || ""}</p> <p className="text-xs font-medium text-muted-foreground">{eventInfo?.organizationName}</p>
{eventInfo?.qrSourceLabel && (
<p className="text-[10px] text-muted-foreground/60">{eventInfo.qrSourceLabel}</p>
)}
</div> </div>
<div className="px-4 pb-8">{steps[step]}</div> {/* Content */}
<div className="px-4 pb-20">{steps[step]}</div>
{/* Back button */}
{backableSteps.has(step) && ( {backableSteps.has(step) && (
<div className="fixed bottom-6 left-4"> <div className="fixed bottom-0 left-0 right-0 pb-6 pt-4 px-4 bg-gradient-to-t from-white via-white/80 to-transparent">
<button <button
onClick={() => setStep(getBackStep(step))} onClick={() => setStep(getBackStep(step))}
className="text-sm text-muted-foreground hover:text-foreground transition-colors tap-target flex items-center gap-1" className="text-sm text-muted-foreground hover:text-foreground transition-colors tap-target flex items-center gap-1"

View File

@@ -1,23 +1,48 @@
"use client" "use client"
import { useState } from "react" import { useState, useEffect, useRef } from "react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input" import { Heart, Sparkles, TrendingUp } from "lucide-react"
const PRESETS = [1000, 2000, 5000, 10000, 25000, 50000] // pence
interface Props { interface Props {
onSelect: (amountPence: number) => void onSelect: (amountPence: number) => void
eventName: string eventName: string
eventId?: string
} }
export function AmountStep({ onSelect, eventName }: Props) { interface AiSuggestion {
amounts: number[]
nudge: string
socialProof: string
}
const FALLBACK_AMOUNTS = [2000, 5000, 10000, 25000, 50000, 100000]
export function AmountStep({ onSelect, eventName, eventId }: Props) {
const [custom, setCustom] = useState("") const [custom, setCustom] = useState("")
const [selected, setSelected] = useState<number | null>(null) const [selected, setSelected] = useState<number | null>(null)
const [suggestions, setSuggestions] = useState<AiSuggestion | null>(null)
const [hovering, setHovering] = useState<number | null>(null)
const inputRef = useRef<HTMLInputElement>(null)
// Fetch AI-powered suggestions
useEffect(() => {
const url = eventId ? `/api/ai/suggest?eventId=${eventId}` : "/api/ai/suggest"
fetch(url)
.then(r => r.json())
.then(data => {
if (data.amounts?.length) setSuggestions(data)
})
.catch(() => {})
}, [eventId])
const amounts = suggestions?.amounts || FALLBACK_AMOUNTS
const handlePreset = (amount: number) => { const handlePreset = (amount: number) => {
setSelected(amount) setSelected(amount)
setCustom("") setCustom("")
// Haptic feedback on mobile
if (navigator.vibrate) navigator.vibrate(10)
} }
const handleCustomChange = (value: string) => { const handleCustomChange = (value: string) => {
@@ -31,66 +56,133 @@ export function AmountStep({ onSelect, eventName }: Props) {
if (amount >= 100) onSelect(amount) if (amount >= 100) onSelect(amount)
} }
const isValid = selected || (custom && parseFloat(custom) >= 1) const activeAmount = selected || (custom ? Math.round(parseFloat(custom) * 100) : 0)
const isValid = activeAmount >= 100
const giftAidBonus = Math.round(activeAmount * 0.25)
return ( return (
<div className="max-w-md mx-auto pt-4 space-y-8"> <div className="max-w-md mx-auto pt-2 space-y-6 animate-fade-up">
<div className="text-center space-y-2"> {/* Hero */}
<h1 className="text-3xl font-extrabold text-gray-900"> <div className="text-center space-y-3">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 shadow-lg shadow-trust-blue/30">
<Heart className="h-7 w-7 text-white" />
</div>
<h1 className="text-3xl font-black text-gray-900 tracking-tight">
Make a Pledge Make a Pledge
</h1> </h1>
<p className="text-muted-foreground"> <p className="text-base text-muted-foreground">
for <span className="font-semibold text-foreground">{eventName}</span> for <span className="font-semibold text-foreground">{eventName}</span>
</p> </p>
</div> </div>
{/* Presets */} {/* Social proof */}
<div className="grid grid-cols-3 gap-3"> {suggestions?.socialProof && (
{PRESETS.map((amount) => ( <div className="flex items-center justify-center gap-2 animate-fade-in">
<div className="flex -space-x-2">
{[...Array(3)].map((_, i) => (
<div key={i} className="w-6 h-6 rounded-full bg-gradient-to-br from-trust-blue to-blue-400 border-2 border-white flex items-center justify-center">
<span className="text-[8px] text-white font-bold">{["A", "S", "M"][i]}</span>
</div>
))}
</div>
<p className="text-sm text-muted-foreground">
<TrendingUp className="h-3.5 w-3.5 inline mr-1 text-success-green" />
{suggestions.socialProof}
</p>
</div>
)}
{/* Amount grid */}
<div className="grid grid-cols-3 gap-2.5 stagger-children">
{amounts.map((amount) => {
const isSelected = selected === amount
const isHovering = hovering === amount
const pounds = amount / 100
return (
<button <button
key={amount} key={amount}
onClick={() => handlePreset(amount)} onClick={() => handlePreset(amount)}
onMouseEnter={() => setHovering(amount)}
onMouseLeave={() => setHovering(null)}
className={` className={`
tap-target rounded-2xl border-2 py-4 text-center font-bold text-lg transition-all relative tap-target rounded-2xl border-2 py-4 text-center font-bold transition-all duration-200
${selected === amount ${isSelected
? "border-trust-blue bg-trust-blue text-white shadow-lg shadow-trust-blue/25 scale-[1.02]" ? "border-trust-blue bg-trust-blue text-white shadow-xl shadow-trust-blue/30 scale-[1.03]"
: "border-gray-200 bg-white text-gray-900 hover:border-trust-blue/50 active:scale-[0.98]" : isHovering
? "border-trust-blue/40 bg-trust-blue/5 text-gray-900"
: "border-gray-200 bg-white text-gray-900 hover:border-trust-blue/30"
} }
`} `}
> >
£{amount / 100} <span className="text-xl">£{pounds >= 1000 ? `${pounds / 1000}k` : pounds}</span>
{/* Gift Aid indicator */}
{isSelected && (
<div className="absolute -top-2 -right-2 bg-success-green text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full animate-scale-in shadow-sm">
+£{Math.round(amount * 0.25 / 100)}
</div>
)}
</button> </button>
))} )
})}
</div> </div>
{/* Custom */} {/* AI nudge */}
{suggestions?.nudge && (
<p className="text-center text-sm text-muted-foreground/80 italic flex items-center justify-center gap-1.5 animate-fade-in" style={{ animationDelay: "400ms" }}>
<Sparkles className="h-3.5 w-3.5 text-warm-amber" />
{suggestions.nudge}
</p>
)}
{/* Custom amount — premium input */}
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">Or enter a custom amount</label> <button
<div className="relative"> onClick={() => inputRef.current?.focus()}
<span className="absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-gray-400">£</span> className="text-xs font-medium text-muted-foreground hover:text-trust-blue transition-colors cursor-pointer"
<Input >
Or enter your own amount
</button>
<div className="relative group">
<span className="absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-black text-gray-300 group-focus-within:text-trust-blue transition-colors">£</span>
<input
ref={inputRef}
type="text" type="text"
inputMode="decimal" inputMode="decimal"
placeholder="0.00" placeholder="0"
value={custom} value={custom}
onChange={(e) => handleCustomChange(e.target.value)} onChange={(e) => handleCustomChange(e.target.value)}
className="pl-10 h-16 text-2xl font-bold text-center rounded-2xl" className="w-full pl-10 pr-4 h-16 text-2xl font-black text-center rounded-2xl border-2 border-gray-200 bg-white focus:border-trust-blue focus:ring-4 focus:ring-trust-blue/10 outline-none transition-all"
/> />
</div> </div>
</div> </div>
{/* Live Gift Aid preview */}
{isValid && (
<div className="rounded-2xl bg-gradient-to-r from-success-green/5 to-success-green/10 border border-success-green/20 p-4 text-center animate-scale-in">
<p className="text-sm">
<span className="font-bold text-success-green">With Gift Aid:</span>{" "}
your £{(activeAmount / 100).toFixed(0)} becomes{" "}
<span className="font-black text-success-green text-lg">
£{((activeAmount + giftAidBonus) / 100).toFixed(0)}
</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">HMRC adds 25% at zero cost to you</p>
</div>
)}
{/* Continue */} {/* Continue */}
<Button <Button
size="xl" size="xl"
className="w-full" className={`w-full transition-all duration-300 ${isValid ? "opacity-100 translate-y-0" : "opacity-50 translate-y-1"}`}
disabled={!isValid} disabled={!isValid}
onClick={handleContinue} onClick={handleContinue}
> >
Continue {isValid ? `Pledge £${(activeAmount / 100).toFixed(activeAmount % 100 === 0 ? 0 : 2)}` : "Choose an amount"}
</Button> </Button>
<p className="text-center text-xs text-muted-foreground"> <p className="text-center text-xs text-muted-foreground">
You won&apos;t be charged now. Choose how to pay next. No payment now choose how to pay on the next step
</p> </p>
</div> </div>
) )

View File

@@ -1,9 +1,9 @@
"use client" "use client"
import { useState } from "react" import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card" import { Card, CardContent } from "@/components/ui/card"
import { Check, Copy, ExternalLink, MessageCircle, Share2 } from "lucide-react" import { Check, Copy, MessageCircle, Share2, Sparkles, ExternalLink } from "lucide-react"
interface Props { interface Props {
pledge: { pledge: {
@@ -18,26 +18,52 @@ interface Props {
} }
amount: number amount: number
eventName: string eventName: string
donorPhone?: string
} }
export function BankInstructionsStep({ pledge, amount, eventName }: Props) { export function BankInstructionsStep({ pledge, amount, eventName, donorPhone }: Props) {
const [copied, setCopied] = useState(false) const [copiedField, setCopiedField] = useState<string | null>(null)
const [markedPaid, setMarkedPaid] = useState(false) const [markedPaid, setMarkedPaid] = useState(false)
const [whatsappSent, setWhatsappSent] = useState(false)
const copyReference = async () => { const bd = pledge.bankDetails
await navigator.clipboard.writeText(pledge.reference)
setCopied(true) // Send bank details to WhatsApp
setTimeout(() => setCopied(false), 3000) useEffect(() => {
if (!donorPhone || whatsappSent) return
fetch("/api/whatsapp/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "receipt",
phone: donorPhone,
data: {
amountPounds: (amount / 100).toFixed(0),
eventName,
reference: pledge.reference,
rail: "bank",
bankDetails: bd ? { sortCode: bd.sortCode, accountNo: bd.accountNo, accountName: bd.accountName } : undefined,
},
}),
}).then(() => setWhatsappSent(true)).catch(() => {})
}, [donorPhone, whatsappSent, amount, eventName, pledge.reference, bd])
const copyField = async (value: string, field: string) => {
await navigator.clipboard.writeText(value)
setCopiedField(field)
if (navigator.vibrate) navigator.vibrate(10)
setTimeout(() => setCopiedField(null), 2000)
// Track // Track
fetch("/api/analytics", { fetch("/api/analytics", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ eventType: "instruction_copy_clicked", pledgeId: pledge.id }), body: JSON.stringify({ eventType: "instruction_copy_clicked", pledgeId: pledge.id, metadata: { field } }),
}).catch(() => {}) }).catch(() => {})
} }
const handleIPaid = async () => { const handleIPaid = async () => {
setMarkedPaid(true) setMarkedPaid(true)
if (navigator.vibrate) navigator.vibrate([10, 50, 10])
fetch(`/api/pledges/${pledge.id}/mark-initiated`, { method: "POST" }).catch(() => {}) fetch(`/api/pledges/${pledge.id}/mark-initiated`, { method: "POST" }).catch(() => {})
fetch("/api/analytics", { fetch("/api/analytics", {
method: "POST", method: "POST",
@@ -46,23 +72,32 @@ export function BankInstructionsStep({ pledge, amount, eventName }: Props) {
}).catch(() => {}) }).catch(() => {})
} }
const bd = pledge.bankDetails // Post-payment view
if (markedPaid) { if (markedPaid) {
return ( return (
<div className="max-w-md mx-auto pt-8 text-center space-y-6"> <div className="max-w-md mx-auto pt-8 text-center space-y-6 animate-fade-up">
<div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-success-green/10"> <div className="relative inline-flex items-center justify-center">
<Check className="h-10 w-10 text-success-green" /> <div className="absolute w-20 h-20 rounded-full bg-success-green/20 animate-pulse-ring" />
<div className="relative w-20 h-20 rounded-full bg-gradient-to-br from-success-green to-emerald-500 flex items-center justify-center shadow-xl shadow-success-green/30">
<Check className="h-10 w-10 text-white" strokeWidth={3} />
</div> </div>
<h1 className="text-2xl font-extrabold text-gray-900">Thank you!</h1> </div>
<h1 className="text-2xl font-black text-gray-900">Thank you!</h1>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
We&apos;ll confirm once your payment of <span className="font-bold text-foreground">£{(amount / 100).toFixed(2)}</span> is received. We&apos;ll confirm once your <span className="font-bold text-foreground">£{(amount / 100).toFixed(0)}</span> is received.
</p> </p>
{whatsappSent && (
<div className="rounded-xl bg-[#25D366]/10 border border-[#25D366]/20 p-3 text-sm text-[#25D366] font-medium flex items-center justify-center gap-2 animate-fade-in">
<MessageCircle className="h-4 w-4" /> Details sent to your WhatsApp
</div>
)}
<Card className="text-left"> <Card className="text-left">
<CardContent className="pt-4 space-y-2 text-sm"> <CardContent className="pt-4 space-y-2 text-sm">
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-muted-foreground">Reference</span> <span className="text-muted-foreground">Reference</span>
<span className="font-mono font-bold">{pledge.reference}</span> <span className="font-mono font-bold text-trust-blue">{pledge.reference}</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-muted-foreground">Event</span> <span className="text-muted-foreground">Event</span>
@@ -70,26 +105,26 @@ export function BankInstructionsStep({ pledge, amount, eventName }: Props) {
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
{/* Share CTA */}
<div className="rounded-2xl bg-warm-amber/5 border border-warm-amber/20 p-4 space-y-3 text-center"> {/* Share */}
<p className="text-sm font-semibold text-gray-900">🤲 Know someone who&apos;d donate too?</p> <div className="rounded-2xl bg-gradient-to-br from-warm-amber/5 to-orange-50 border border-warm-amber/20 p-5 space-y-3">
<div className="flex items-center justify-center gap-2">
<Sparkles className="h-4 w-4 text-warm-amber" />
<p className="text-sm font-bold text-gray-900">Know someone who&apos;d donate too?</p>
</div>
<div className="flex gap-2"> <div className="flex gap-2">
<Button <Button
onClick={() => { onClick={() => {
const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}! 🤲\nPledge here: ${window.location.origin}` const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}! 🤲\nPledge here: ${window.location.href}`
window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank") window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank")
}} }}
className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white" className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white shadow-lg shadow-[#25D366]/25"
size="sm" size="sm"
> >
<MessageCircle className="h-4 w-4 mr-1" /> WhatsApp <MessageCircle className="h-4 w-4 mr-1" /> WhatsApp
</Button> </Button>
<Button <Button
onClick={async () => { onClick={() => navigator.share?.({ title: eventName, text: `Pledge to ${eventName}`, url: window.location.href })}
if (navigator.share) {
await navigator.share({ title: eventName, text: `Pledge to ${eventName}`, url: window.location.origin })
}
}}
variant="outline" variant="outline"
size="sm" size="sm"
className="flex-1" className="flex-1"
@@ -100,94 +135,108 @@ export function BankInstructionsStep({ pledge, amount, eventName }: Props) {
</div> </div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Need help? Contact the charity directly. Payments usually arrive within 2 hours. We&apos;ll email you once confirmed.
</p> </p>
</div> </div>
) )
} }
return ( // Copy-able field component
<div className="max-w-md mx-auto pt-4 space-y-6"> const CopyField = ({ label, value, fieldKey, mono }: { label: string; value: string; fieldKey: string; mono?: boolean }) => (
<div className="text-center space-y-2"> <button
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-trust-blue/10 mb-2"> onClick={() => copyField(value, fieldKey)}
<span className="text-3xl">🏦</span> className="flex items-center justify-between w-full py-2.5 px-0 group"
>
<div className="text-left">
<p className="text-[10px] text-muted-foreground uppercase tracking-wider font-medium">{label}</p>
<p className={`font-bold text-lg ${mono ? "font-mono" : ""} text-gray-900`}>{value}</p>
</div> </div>
<h1 className="text-2xl font-extrabold text-gray-900"> <div className={`rounded-lg px-2.5 py-1.5 text-xs font-medium transition-all ${
Transfer £{(amount / 100).toFixed(2)} copiedField === fieldKey
? "bg-success-green text-white"
: "bg-gray-100 text-gray-500 group-hover:bg-trust-blue/10 group-hover:text-trust-blue"
}`}>
{copiedField === fieldKey ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
</div>
</button>
)
return (
<div className="max-w-md mx-auto pt-2 space-y-5 animate-fade-up">
<div className="text-center space-y-2">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 shadow-lg shadow-trust-blue/30">
<span className="text-2xl">🏦</span>
</div>
<h1 className="text-2xl font-black text-gray-900 tracking-tight">
Transfer £{(amount / 100).toFixed(0)}
</h1> </h1>
<p className="text-muted-foreground"> <p className="text-sm text-muted-foreground">
Use these details in your banking app Tap any field to copy · Use your banking app
</p> </p>
</div> </div>
{/* Bank details card */} {whatsappSent && (
<div className="rounded-xl bg-[#25D366]/10 border border-[#25D366]/20 p-2.5 text-xs text-[#25D366] font-medium flex items-center justify-center gap-2 animate-fade-in">
<MessageCircle className="h-3.5 w-3.5" /> Bank details also sent to your WhatsApp
</div>
)}
{/* Bank details — tap to copy each field */}
{bd && ( {bd && (
<Card> <Card className="overflow-hidden">
<CardContent className="pt-6 space-y-4"> <div className="h-1 bg-gradient-to-r from-trust-blue to-blue-400" />
<div className="grid grid-cols-2 gap-4 text-sm"> <CardContent className="pt-4 divide-y">
<div> <CopyField label="Sort Code" value={bd.sortCode} fieldKey="sortCode" mono />
<p className="text-muted-foreground text-xs uppercase tracking-wider">Sort Code</p> <CopyField label="Account Number" value={bd.accountNo} fieldKey="accountNo" mono />
<p className="font-mono font-bold text-lg">{bd.sortCode}</p> <CopyField label="Account Name" value={bd.accountName} fieldKey="accountName" />
</div>
<div>
<p className="text-muted-foreground text-xs uppercase tracking-wider">Account No</p>
<p className="font-mono font-bold text-lg">{bd.accountNo}</p>
</div>
</div>
<div className="text-sm">
<p className="text-muted-foreground text-xs uppercase tracking-wider">Account Name</p>
<p className="font-semibold">{bd.accountName}</p>
</div>
</CardContent> </CardContent>
</Card> </Card>
)} )}
{/* Reference - THE KEY */} {/* THE reference — the most important thing */}
<div className="rounded-2xl border-2 border-trust-blue bg-trust-blue/5 p-6 text-center space-y-3"> <div className="rounded-2xl border-2 border-trust-blue bg-gradient-to-br from-trust-blue/5 to-blue-50 p-5 text-center space-y-3">
<p className="text-xs font-semibold text-trust-blue uppercase tracking-wider"> <p className="text-xs font-bold text-trust-blue uppercase tracking-widest">
Payment Reference use exactly: Payment Reference
</p> </p>
<p className="text-3xl font-mono font-extrabold text-trust-blue tracking-wider"> <button
onClick={() => copyField(pledge.reference, "reference")}
className="group"
>
<p className="text-3xl font-mono font-black text-trust-blue tracking-wider group-hover:scale-105 transition-transform">
{pledge.reference} {pledge.reference}
</p> </p>
</button>
<Button <Button
onClick={copyReference} onClick={() => copyField(pledge.reference, "reference")}
variant={copied ? "success" : "default"} variant={copiedField === "reference" ? "success" : "default"}
size="lg"
className="w-full" className="w-full"
> >
{copied ? ( {copiedField === "reference" ? (
<> <><Check className="h-5 w-5 mr-2" /> Copied!</>
<Check className="h-5 w-5 mr-2" /> Copied!
</>
) : ( ) : (
<> <><Copy className="h-5 w-5 mr-2" /> Copy Reference</>
<Copy className="h-5 w-5 mr-2" /> Copy Reference
</>
)} )}
</Button> </Button>
<p className="text-[11px] text-trust-blue/70">
Use this exact reference so we can match your payment
</p>
</div> </div>
{/* Suggestion */} {/* Open banking app hint */}
<div className="rounded-2xl bg-warm-amber/5 border border-warm-amber/20 p-4 text-center"> <div className="rounded-xl bg-warm-amber/5 border border-warm-amber/20 p-3 text-center">
<p className="text-sm font-medium text-warm-amber"> <p className="text-xs font-medium text-warm-amber flex items-center justify-center gap-1.5">
<ExternalLink className="h-4 w-4 inline mr-1" /> <ExternalLink className="h-3.5 w-3.5" />
Open your banking app now and search for &quot;new payment&quot; Open your banking app New payment Paste the details
</p> </p>
</div> </div>
{/* I've paid */} {/* I've paid */}
<Button <Button size="xl" variant="success" className="w-full" onClick={handleIPaid}>
size="xl"
variant="success"
className="w-full"
onClick={handleIPaid}
>
I&apos;ve Sent the Payment I&apos;ve Sent the Payment
</Button> </Button>
<p className="text-center text-xs text-muted-foreground"> <p className="text-center text-xs text-muted-foreground">
Payments usually take 1-2 hours to arrive. We&apos;ll confirm once received. Payments usually arrive within 2 hours. No rush transfer at your convenience.
</p> </p>
</div> </div>
) )

View File

@@ -1,8 +1,9 @@
"use client" "use client"
import { Check, Share2, MessageCircle } from "lucide-react" import { useEffect, useState, useCallback } from "react"
import { Card, CardContent } from "@/components/ui/card" import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Check, Share2, MessageCircle, Copy, Sparkles } from "lucide-react"
interface Props { interface Props {
pledge: { id: string; reference: string } pledge: { id: string; reference: string }
@@ -10,9 +11,49 @@ interface Props {
rail: string rail: string
eventName: string eventName: string
shareUrl?: string shareUrl?: string
donorPhone?: string
} }
export function ConfirmationStep({ pledge, amount, rail, eventName, shareUrl }: Props) { // Mini confetti
function Confetti() {
const [pieces, setPieces] = useState<Array<{ x: number; color: string; delay: number; size: number }>>([])
useEffect(() => {
setPieces(
Array.from({ length: 40 }, () => ({
x: Math.random() * 100,
color: ["#1e40af", "#16a34a", "#f59e0b", "#ec4899", "#8b5cf6"][Math.floor(Math.random() * 5)],
delay: Math.random() * 2,
size: 4 + Math.random() * 8,
}))
)
}, [])
return (
<div className="fixed inset-0 pointer-events-none overflow-hidden z-50">
{pieces.map((p, i) => (
<div
key={i}
className="absolute top-0"
style={{
left: `${p.x}%`,
width: p.size,
height: p.size,
backgroundColor: p.color,
borderRadius: Math.random() > 0.5 ? "50%" : "2px",
animation: `confetti-fall ${2 + Math.random() * 2}s ease-in forwards`,
animationDelay: `${p.delay}s`,
}}
/>
))}
</div>
)
}
export function ConfirmationStep({ pledge, amount, rail, eventName, shareUrl, donorPhone }: Props) {
const [copied, setCopied] = useState(false)
const [whatsappSent, setWhatsappSent] = useState(false)
const railLabels: Record<string, string> = { const railLabels: Record<string, string> = {
bank: "Bank Transfer", bank: "Bank Transfer",
gocardless: "Direct Debit", gocardless: "Direct Debit",
@@ -21,10 +62,38 @@ export function ConfirmationStep({ pledge, amount, rail, eventName, shareUrl }:
const nextStepMessages: Record<string, string> = { const nextStepMessages: Record<string, string> = {
bank: "We've sent you payment instructions. Transfer at your convenience — we'll confirm once received.", bank: "We've sent you payment instructions. Transfer at your convenience — we'll confirm once received.",
gocardless: "Your Direct Debit mandate has been set up. The payment of £" + (amount / 100).toFixed(2) + " will be collected automatically in 3-5 working days. You'll receive email confirmation from GoCardless. Protected by the Direct Debit Guarantee.", gocardless: `Your Direct Debit mandate is set up. £${(amount / 100).toFixed(2)} will be collected automatically in 3-5 working days. Protected by the Direct Debit Guarantee.`,
card: "Your card payment has been processed. You'll receive a confirmation email shortly.", card: "Your card payment has been processed. Confirmation email is on its way.",
} }
// Send WhatsApp receipt if phone provided
const sendWhatsAppReceipt = useCallback(async () => {
if (!donorPhone || whatsappSent) return
try {
await fetch("/api/whatsapp/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "receipt",
phone: donorPhone,
data: {
amountPounds: (amount / 100).toFixed(0),
eventName,
reference: pledge.reference,
rail,
},
}),
})
setWhatsappSent(true)
} catch {
// Silent fail — not critical
}
}, [donorPhone, whatsappSent, amount, eventName, pledge.reference, rail])
useEffect(() => {
sendWhatsAppReceipt()
}, [sendWhatsAppReceipt])
const handleWhatsAppShare = () => { const handleWhatsAppShare = () => {
const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}! 🤲\n\nYou can pledge too: ${shareUrl || window.location.origin}` const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}! 🤲\n\nYou can pledge too: ${shareUrl || window.location.origin}`
window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank") window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank")
@@ -39,89 +108,101 @@ export function ConfirmationStep({ pledge, amount, rail, eventName, shareUrl }:
} }
} }
const copyRef = async () => {
await navigator.clipboard.writeText(pledge.reference)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
return ( return (
<div className="max-w-md mx-auto pt-8 text-center space-y-6"> <>
<div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-success-green/10"> <Confetti />
<Check className="h-10 w-10 text-success-green" /> <div className="max-w-md mx-auto pt-6 text-center space-y-6 animate-fade-up">
{/* Success icon with pulse */}
<div className="relative inline-flex items-center justify-center">
<div className="absolute w-20 h-20 rounded-full bg-success-green/20 animate-pulse-ring" />
<div className="relative w-20 h-20 rounded-full bg-gradient-to-br from-success-green to-emerald-500 flex items-center justify-center shadow-xl shadow-success-green/30">
<Check className="h-10 w-10 text-white" strokeWidth={3} />
</div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<h1 className="text-2xl font-extrabold text-gray-900"> <h1 className="text-2xl font-black text-gray-900">
{rail === "gocardless" ? "Mandate Set Up!" : rail === "card" ? "Payment Complete!" : "Pledge Received!"} {rail === "card" ? "Payment Complete!" : rail === "gocardless" ? "Mandate Set Up!" : "Pledge Received!"}
</h1> </h1>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
Thank you for your generous {rail === "card" ? "donation" : "pledge"} to{" "} Thank you for your generous support of{" "}
<span className="font-semibold text-foreground">{eventName}</span> <span className="font-semibold text-foreground">{eventName}</span>
</p> </p>
</div> </div>
<Card> {/* Details card */}
<CardContent className="pt-6 space-y-3 text-sm"> <Card className="text-left overflow-hidden">
<div className="flex justify-between"> <div className="h-1 bg-gradient-to-r from-trust-blue via-success-green to-warm-amber" />
<CardContent className="pt-5 space-y-3 text-sm">
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Amount</span> <span className="text-muted-foreground">Amount</span>
<span className="font-bold">£{(amount / 100).toFixed(2)}</span> <span className="font-black text-lg">£{(amount / 100).toFixed(2)}</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between items-center">
<span className="text-muted-foreground">Payment Method</span> <span className="text-muted-foreground">Method</span>
<span>{railLabels[rail] || rail}</span> <span className="font-medium">{railLabels[rail] || rail}</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between items-center">
<span className="text-muted-foreground">Reference</span> <span className="text-muted-foreground">Reference</span>
<span className="font-mono font-bold">{pledge.reference}</span> <button onClick={copyRef} className="font-mono font-bold text-trust-blue flex items-center gap-1.5 hover:underline">
{pledge.reference}
{copied ? <Check className="h-3.5 w-3.5 text-success-green" /> : <Copy className="h-3.5 w-3.5" />}
</button>
</div> </div>
{rail === "gocardless" && (
<div className="flex justify-between">
<span className="text-muted-foreground">Collection</span>
<span className="text-sm">3-5 working days</span>
</div>
)}
{rail === "card" && ( {rail === "card" && (
<div className="flex justify-between"> <div className="flex justify-between items-center pt-1 border-t">
<span className="text-muted-foreground">Status</span> <span className="text-muted-foreground">Status</span>
<span className="text-success-green font-semibold">Paid </span> <span className="text-success-green font-bold flex items-center gap-1">
<Check className="h-4 w-4" /> Paid
</span>
</div> </div>
)} )}
</CardContent> </CardContent>
</Card> </Card>
{/* What happens next */} {/* What happens next */}
<div className="rounded-2xl bg-trust-blue/5 border border-trust-blue/20 p-4 space-y-2"> <div className="rounded-2xl bg-trust-blue/5 border border-trust-blue/10 p-4 text-left">
<p className="text-sm font-medium text-trust-blue">What happens next?</p> <p className="text-sm font-semibold text-trust-blue mb-1">What happens next?</p>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">{nextStepMessages[rail] || nextStepMessages.bank}</p>
{nextStepMessages[rail] || nextStepMessages.bank}
</p>
</div> </div>
{/* Share / encourage others */} {whatsappSent && (
<div className="rounded-2xl bg-warm-amber/5 border border-warm-amber/20 p-5 space-y-3"> <div className="rounded-xl bg-[#25D366]/10 border border-[#25D366]/20 p-3 text-sm text-[#25D366] font-medium flex items-center justify-center gap-2 animate-fade-in">
<p className="text-sm font-semibold text-gray-900"> <MessageCircle className="h-4 w-4" /> Receipt sent to your WhatsApp
🤲 Spread the word every pledge counts! </div>
)}
{/* Share */}
<div className="rounded-2xl bg-gradient-to-br from-warm-amber/5 to-orange-50 border border-warm-amber/20 p-5 space-y-3">
<div className="flex items-center justify-center gap-2">
<Sparkles className="h-4 w-4 text-warm-amber" />
<p className="text-sm font-bold text-gray-900">
Double your impact share with friends
</p> </p>
</div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Share with friends and family so they can pledge too. Every share can inspire another pledge
</p> </p>
<div className="flex gap-2"> <div className="flex gap-2">
<Button <Button onClick={handleWhatsAppShare} className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white shadow-lg shadow-[#25D366]/25">
onClick={handleWhatsAppShare} <MessageCircle className="h-4 w-4 mr-2" /> WhatsApp
className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white"
>
<MessageCircle className="h-4 w-4 mr-2" />
WhatsApp
</Button> </Button>
<Button <Button onClick={handleShare} variant="outline" className="flex-1">
onClick={handleShare} <Share2 className="h-4 w-4 mr-2" /> Share
variant="outline"
className="flex-1"
>
<Share2 className="h-4 w-4 mr-2" />
Share
</Button> </Button>
</div> </div>
</div> </div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground pb-4">
Need help? Contact the charity directly. Ref: {pledge.reference} Need help? Contact the charity directly · Ref: {pledge.reference}
</p> </p>
</div> </div>
</>
) )
} }

View File

@@ -1,10 +1,8 @@
"use client" "use client"
import { useState } from "react" import { useState, useRef, useEffect } from "react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input" import { Gift, Shield, Sparkles, Phone, Mail } from "lucide-react"
import { Label } from "@/components/ui/label"
import { Gift, Shield } from "lucide-react"
interface Props { interface Props {
onSubmit: (data: { onSubmit: (data: {
@@ -22,10 +20,15 @@ export function IdentityStep({ onSubmit, amount }: Props) {
const [phone, setPhone] = useState("") const [phone, setPhone] = useState("")
const [giftAid, setGiftAid] = useState(false) const [giftAid, setGiftAid] = useState(false)
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const [contactMode, setContactMode] = useState<"email" | "phone">("email")
const nameRef = useRef<HTMLInputElement>(null)
const hasContact = email.includes("@") || phone.length >= 10 useEffect(() => { nameRef.current?.focus() }, [])
const hasContact = contactMode === "email" ? email.includes("@") : phone.length >= 10
const isValid = hasContact const isValid = hasContact
const giftAidBonus = Math.round(amount * 0.25) const giftAidBonus = Math.round(amount * 0.25)
const totalWithAid = amount + giftAidBonus
const handleSubmit = async () => { const handleSubmit = async () => {
if (!isValid) return if (!isValid) return
@@ -38,123 +41,168 @@ export function IdentityStep({ onSubmit, amount }: Props) {
} }
return ( return (
<div className="max-w-md mx-auto pt-4 space-y-6"> <div className="max-w-md mx-auto pt-2 space-y-5 animate-fade-up">
<div className="text-center space-y-2"> <div className="text-center space-y-2">
<h1 className="text-2xl font-extrabold text-gray-900"> <h1 className="text-2xl font-black text-gray-900 tracking-tight">
Almost there! Almost there!
</h1> </h1>
<p className="text-muted-foreground"> <p className="text-muted-foreground text-sm">
We need a way to send you payment details We just need a way to send you payment details
</p> </p>
</div> </div>
<div className="space-y-4"> {/* Minimal form */}
<div className="space-y-2"> <div className="space-y-3">
<Label htmlFor="name">Full Name <span className="text-muted-foreground font-normal">(for Gift Aid)</span></Label> {/* Name */}
<Input <div className="relative">
id="name" <input
placeholder="Your full name" ref={nameRef}
type="text"
placeholder="Your name"
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
autoComplete="name" autoComplete="name"
className="w-full h-14 px-4 rounded-2xl border-2 border-gray-200 bg-white text-base font-medium placeholder:text-gray-300 focus:border-trust-blue focus:ring-4 focus:ring-trust-blue/10 outline-none transition-all"
/> />
{name && (
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-success-green animate-scale-in"></div>
)}
</div> </div>
<div className="space-y-2"> {/* Contact mode toggle */}
<Label htmlFor="email">Email</Label> <div className="flex rounded-xl bg-gray-100 p-1">
<Input <button
id="email" onClick={() => setContactMode("email")}
className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-all ${
contactMode === "email" ? "bg-white shadow-sm text-gray-900" : "text-gray-500"
}`}
>
<Mail className="h-4 w-4" /> Email
</button>
<button
onClick={() => setContactMode("phone")}
className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-all ${
contactMode === "phone" ? "bg-white shadow-sm text-gray-900" : "text-gray-500"
}`}
>
<Phone className="h-4 w-4" /> Mobile
</button>
</div>
{/* Contact input */}
{contactMode === "email" ? (
<div className="relative animate-fade-in">
<Mail className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-300" />
<input
type="email" type="email"
placeholder="your@email.com" placeholder="your@email.com"
value={email} value={email}
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
autoComplete="email" autoComplete="email"
inputMode="email" inputMode="email"
className="w-full h-14 pl-12 pr-4 rounded-2xl border-2 border-gray-200 bg-white text-base font-medium placeholder:text-gray-300 focus:border-trust-blue focus:ring-4 focus:ring-trust-blue/10 outline-none transition-all"
/> />
<p className="text-xs text-muted-foreground">
We&apos;ll send your payment instructions and receipt here
</p>
</div> </div>
) : (
<div className="relative flex items-center"> <div className="relative animate-fade-in">
<div className="flex-grow border-t border-gray-200" /> <Phone className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-300" />
<span className="flex-shrink mx-3 text-xs text-muted-foreground">or</span> <input
<div className="flex-grow border-t border-gray-200" />
</div>
<div className="space-y-2">
<Label htmlFor="phone">Mobile Number</Label>
<Input
id="phone"
type="tel" type="tel"
placeholder="07700 900000" placeholder="07700 900 000"
value={phone} value={phone}
onChange={(e) => setPhone(e.target.value)} onChange={(e) => setPhone(e.target.value)}
autoComplete="tel" autoComplete="tel"
inputMode="tel" inputMode="tel"
className="w-full h-14 pl-12 pr-4 rounded-2xl border-2 border-gray-200 bg-white text-base font-medium placeholder:text-gray-300 focus:border-trust-blue focus:ring-4 focus:ring-trust-blue/10 outline-none transition-all"
/> />
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground mt-1 ml-1">
We can send reminders via SMS if you prefer We&apos;ll send reminders via WhatsApp
</p> </p>
</div> </div>
)}
</div>
{/* Gift Aid — prominent UK-specific */} {/* Gift Aid — the hero */}
<div <button
onClick={() => setGiftAid(!giftAid)} onClick={() => setGiftAid(!giftAid)}
className={`rounded-2xl border-2 p-5 cursor-pointer transition-all ${ className={`w-full text-left rounded-2xl border-2 p-5 transition-all duration-300 card-hover ${
giftAid giftAid
? "border-success-green bg-success-green/5 shadow-md shadow-success-green/10" ? "border-success-green bg-gradient-to-br from-success-green/5 to-emerald-50 shadow-lg shadow-success-green/10"
: "border-gray-200 bg-white hover:border-success-green/50" : "border-gray-200 bg-white hover:border-success-green/40"
}`} }`}
> >
<div className="flex items-start gap-4"> <div className="flex items-start gap-4">
<div className={`rounded-xl p-2.5 ${giftAid ? "bg-success-green/10" : "bg-gray-100"}`}> <div className={`rounded-xl p-3 transition-all ${giftAid ? "bg-success-green shadow-lg shadow-success-green/30" : "bg-gray-100"}`}>
<Gift className={`h-6 w-6 ${giftAid ? "text-success-green" : "text-gray-400"}`} /> <Gift className={`h-6 w-6 transition-colors ${giftAid ? "text-white" : "text-gray-400"}`} />
</div> </div>
<div className="flex-1"> <div className="flex-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<input <span className="font-bold text-gray-900">
type="checkbox" {giftAid ? "Gift Aid added!" : "Add Gift Aid"}
checked={giftAid} </span>
onChange={() => {}} {giftAid ? (
className="h-5 w-5 rounded border-gray-300 text-success-green focus:ring-success-green" <span className="text-xs font-bold px-2.5 py-0.5 rounded-full bg-success-green text-white animate-scale-in flex items-center gap-1">
/> <Sparkles className="h-3 w-3" /> +£{(giftAidBonus / 100).toFixed(0)} free
<span className="font-bold text-gray-900">Add Gift Aid</span> </span>
{giftAid && ( ) : (
<span className="text-xs font-bold px-2 py-0.5 rounded-full bg-success-green text-white"> <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-success-green/10 text-success-green">
+£{(giftAidBonus / 100).toFixed(0)} free +25%
</span> </span>
)} )}
</div> </div>
<p className="text-sm text-muted-foreground mt-1">
Boost your £{(amount / 100).toFixed(0)} pledge to{" "} {giftAid ? (
<span className="font-bold text-success-green">£{((amount + giftAidBonus) / 100).toFixed(0)}</span> at no extra cost. <div className="mt-2 space-y-2 animate-fade-in">
HMRC adds 25% the charity claims it back. <div className="flex items-center justify-between bg-white rounded-xl p-3 border border-success-green/20">
<div>
<p className="text-xs text-muted-foreground">Your pledge</p>
<p className="font-bold">£{(amount / 100).toFixed(0)}</p>
</div>
<div className="text-success-green font-bold text-xl">+</div>
<div>
<p className="text-xs text-muted-foreground">HMRC adds</p>
<p className="font-bold text-success-green">£{(giftAidBonus / 100).toFixed(0)}</p>
</div>
<div className="text-success-green font-bold text-xl">=</div>
<div>
<p className="text-xs text-muted-foreground">Charity gets</p>
<p className="font-black text-success-green text-lg">£{(totalWithAid / 100).toFixed(0)}</p>
</div>
</div>
<p className="text-[11px] text-muted-foreground leading-relaxed">
I confirm I am a UK taxpayer and understand that if I pay less Income Tax and/or Capital Gains Tax than the amount of Gift Aid claimed on all my donations in that tax year, it is my responsibility to pay any difference.
</p> </p>
{giftAid && ( </div>
<p className="text-xs text-muted-foreground mt-2 italic"> ) : (
I confirm I am a UK taxpayer and understand that if I pay less Income Tax and/or <p className="text-sm text-muted-foreground mt-1">
Capital Gains Tax than the amount of Gift Aid claimed on all my donations in that Boost your £{(amount / 100).toFixed(0)} to{" "}
tax year it is my responsibility to pay any difference. <span className="font-bold text-success-green">£{(totalWithAid / 100).toFixed(0)}</span> at zero cost. HMRC adds 25%.
</p> </p>
)} )}
</div> </div>
</div> </div>
</div> </button>
</div>
{/* Submit */}
<Button <Button
size="xl" size="xl"
className="w-full" className={`w-full transition-all duration-300 ${isValid ? "opacity-100" : "opacity-50"}`}
disabled={!isValid || submitting} disabled={!isValid || submitting}
onClick={handleSubmit} onClick={handleSubmit}
> >
{submitting ? "Submitting..." : "Complete Pledge ✓"} {submitting ? (
<span className="flex items-center gap-2">
<span className="h-5 w-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
Submitting...
</span>
) : (
"Complete Pledge ✓"
)}
</Button> </Button>
<div className="flex items-center justify-center gap-2 text-xs text-muted-foreground"> <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
<Shield className="h-3 w-3" /> <Shield className="h-3 w-3" />
<span>Your data is kept secure and only used for this pledge</span> <span>Your data is encrypted and only used for this pledge</span>
</div> </div>
</div> </div>
) )

View File

@@ -1,6 +1,6 @@
"use client" "use client"
import { Building2, CreditCard, Landmark } from "lucide-react" import { Building2, CreditCard, Landmark, Shield, CheckCircle2 } from "lucide-react"
interface Props { interface Props {
onSelect: (rail: "bank" | "gocardless" | "card") => void onSelect: (rail: "bank" | "gocardless" | "card") => void
@@ -8,90 +8,115 @@ interface Props {
} }
export function PaymentStep({ onSelect, amount }: Props) { export function PaymentStep({ onSelect, amount }: Props) {
const pounds = (amount / 100).toFixed(2) const pounds = (amount / 100).toFixed(0)
const giftAidTotal = ((amount + amount * 0.25) / 100).toFixed(0)
const options = [ const options = [
{ {
id: "bank" as const, id: "bank" as const,
icon: Building2, icon: Building2,
title: "Bank Transfer", title: "Bank Transfer",
subtitle: "Zero fees — 100% goes to charity", subtitle: "100% goes to charity — zero fees",
tag: "Recommended", tag: "Recommended",
tagColor: "bg-success-green text-white", tagClass: "bg-success-green text-white",
detail: "Use your banking app to transfer directly. We'll give you the details.", detail: "We'll give you the bank details. Transfer in your own time.",
fee: "No fees", fee: "Free",
feeColor: "text-success-green", feeClass: "text-success-green font-bold",
iconBg: "from-emerald-500 to-green-600",
highlight: true,
benefits: ["Zero fees", "Most charities prefer this"],
}, },
{ {
id: "gocardless" as const, id: "gocardless" as const,
icon: Landmark, icon: Landmark,
title: "Direct Debit", title: "Direct Debit",
subtitle: "Automatic collection — set and forget", subtitle: "Automatic collection — set and forget",
tag: "Set up once", tag: "Hassle-free",
tagColor: "bg-trust-blue/10 text-trust-blue", tagClass: "bg-trust-blue/10 text-trust-blue",
detail: "We'll collect via GoCardless. Protected by the Direct Debit Guarantee.", detail: "GoCardless collects it for you. Protected by the DD Guarantee.",
fee: "1% + 20p", fee: "1% + 20p",
feeColor: "text-muted-foreground", feeClass: "text-muted-foreground",
iconBg: "from-trust-blue to-blue-600",
highlight: false,
benefits: ["No action needed", "DD Guarantee"],
}, },
{ {
id: "card" as const, id: "card" as const,
icon: CreditCard, icon: CreditCard,
title: "Debit or Credit Card", title: "Card Payment",
subtitle: "Pay instantly by Visa, Mastercard, or Amex", subtitle: "Visa, Mastercard, Amex — instant",
tag: "Instant", tag: "Instant",
tagColor: "bg-purple-100 text-purple-700", tagClass: "bg-purple-100 text-purple-700",
detail: "Secure payment powered by Stripe. Receipt emailed immediately.", detail: "Powered by Stripe. Receipt emailed instantly.",
fee: "1.4% + 20p", fee: "1.4% + 20p",
feeColor: "text-muted-foreground", feeClass: "text-muted-foreground",
iconBg: "from-purple-500 to-violet-600",
highlight: false,
benefits: ["Instant confirmation", "All major cards"],
}, },
] ]
return ( return (
<div className="max-w-md mx-auto pt-4 space-y-6"> <div className="max-w-md mx-auto pt-2 space-y-6 animate-fade-up">
<div className="text-center space-y-2"> <div className="text-center space-y-2">
<h1 className="text-2xl font-extrabold text-gray-900"> <h1 className="text-2xl font-black text-gray-900 tracking-tight">
How would you like to pay? How would you like to pay?
</h1> </h1>
<p className="text-lg text-muted-foreground"> <p className="text-base text-muted-foreground">
Your pledge: <span className="font-bold text-foreground">£{pounds}</span> Your pledge: <span className="font-bold text-foreground">£{pounds}</span>
<span className="text-success-green text-xs ml-1">(£{giftAidTotal} with Gift Aid)</span>
</p> </p>
</div> </div>
<div className="space-y-3"> <div className="space-y-3 stagger-children">
{options.map((opt) => ( {options.map((opt) => (
<button <button
key={opt.id} key={opt.id}
onClick={() => onSelect(opt.id)} onClick={() => onSelect(opt.id)}
className="w-full text-left tap-target rounded-2xl border-2 border-gray-200 bg-white p-5 hover:border-trust-blue/50 active:scale-[0.99] transition-all group" className={`
w-full text-left rounded-2xl border-2 bg-white p-5 transition-all duration-200 group card-hover
${opt.highlight
? "border-success-green/40 shadow-sm shadow-success-green/10 hover:border-success-green hover:shadow-lg hover:shadow-success-green/15"
: "border-gray-200 hover:border-trust-blue/40 hover:shadow-lg hover:shadow-trust-blue/10"
}
`}
> >
<div className="flex items-start gap-4"> <div className="flex items-start gap-4">
<div className="rounded-xl bg-trust-blue/5 p-3 group-hover:bg-trust-blue/10 transition-colors"> <div className={`rounded-xl bg-gradient-to-br ${opt.iconBg} p-3 shadow-lg shadow-trust-blue/10 group-hover:scale-105 transition-transform`}>
<opt.icon className="h-6 w-6 text-trust-blue" /> <opt.icon className="h-5 w-5 text-white" />
</div> </div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="font-bold text-gray-900">{opt.title}</span> <span className="font-bold text-gray-900">{opt.title}</span>
<span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${opt.tagColor}`}> <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${opt.tagClass}`}>
{opt.tag} {opt.tag}
</span> </span>
</div> </div>
<p className="text-sm text-muted-foreground mt-0.5">{opt.subtitle}</p> <p className="text-sm text-muted-foreground mt-0.5">{opt.subtitle}</p>
<p className="text-xs text-muted-foreground/70 mt-1">{opt.detail}</p> <div className="flex items-center gap-3 mt-2">
<p className={`text-xs font-medium mt-1 ${opt.feeColor}`}> {opt.benefits.map((b, i) => (
Fee: {opt.fee} <span key={i} className="text-[11px] text-muted-foreground inline-flex items-center gap-1">
</p> <CheckCircle2 className="h-3 w-3 text-success-green" />
{b}
</span>
))}
</div>
<div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
<span className={`text-xs ${opt.feeClass}`}>Fee: {opt.fee}</span>
<span className="text-xs text-trust-blue font-medium opacity-0 group-hover:opacity-100 transition-opacity">
Select
</span>
</div> </div>
<div className="text-muted-foreground/40 group-hover:text-trust-blue transition-colors text-xl">
</div> </div>
</div> </div>
</button> </button>
))} ))}
</div> </div>
<p className="text-center text-xs text-muted-foreground"> <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground animate-fade-in" style={{ animationDelay: "300ms" }}>
All payments are secure. Bank transfers mean 100% reaches the charity. <Shield className="h-3.5 w-3.5" />
</p> <span>All payments are encrypted and secure</span>
</div>
</div> </div>
) )
} }

View File

@@ -0,0 +1,186 @@
/**
* AI module — uses OpenAI GPT-4o-mini (nano model, ~$0.15/1M input tokens)
* Falls back to smart heuristics when no API key is set
*/
const OPENAI_KEY = process.env.OPENAI_API_KEY
const MODEL = "gpt-4o-mini"
interface ChatMessage {
role: "system" | "user" | "assistant"
content: string
}
async function chat(messages: ChatMessage[], maxTokens = 300): Promise<string> {
if (!OPENAI_KEY) return ""
try {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${OPENAI_KEY}`,
},
body: JSON.stringify({ model: MODEL, messages, max_tokens: maxTokens, temperature: 0.7 }),
})
const data = await res.json()
return data.choices?.[0]?.message?.content || ""
} catch {
return ""
}
}
/**
* Generate smart amount suggestions based on event context + peer data
*/
export async function suggestAmounts(context: {
eventName: string
avgPledge?: number
medianPledge?: number
pledgeCount?: number
topAmount?: number
currency?: string
}): Promise<{ amounts: number[]; nudge: string; socialProof: string }> {
const avg = context.avgPledge || 5000 // 50 quid default
const median = context.medianPledge || avg
// Smart anchoring: show amounts around the median, biased upward
const base = Math.round(median / 1000) * 1000 || 5000
const amounts = [
Math.max(1000, Math.round(base * 0.5 / 500) * 500),
base,
Math.round(base * 2 / 1000) * 1000,
Math.round(base * 5 / 1000) * 1000,
Math.round(base * 10 / 1000) * 1000,
Math.round(base * 20 / 1000) * 1000,
].filter((v, i, a) => a.indexOf(v) === i && v >= 500) // dedup, min £5
// Social proof text
let socialProof = ""
if (context.pledgeCount && context.pledgeCount > 3) {
socialProof = `${context.pledgeCount} people have pledged so far`
if (context.avgPledge) {
socialProof += ` · Average £${Math.round(context.avgPledge / 100)}`
}
}
// AI-generated nudge (or fallback)
let nudge = ""
if (OPENAI_KEY && context.pledgeCount && context.pledgeCount > 5) {
nudge = await chat([
{
role: "system",
content: "You write one short, warm, encouraging line (max 12 words) to nudge a charity donor to pledge generously. UK English. No emojis. No pressure.",
},
{
role: "user",
content: `Event: ${context.eventName}. ${context.pledgeCount} people pledged avg £${Math.round((context.avgPledge || 5000) / 100)}. Generate a nudge.`,
},
], 30)
}
if (!nudge) {
const nudges = [
"Every pound makes a real difference",
"Your generosity changes lives",
"Join others making an impact today",
"Be part of something meaningful",
]
nudge = nudges[Math.floor(Math.random() * nudges.length)]
}
return { amounts: amounts.slice(0, 6), nudge, socialProof }
}
/**
* Generate a personalized thank-you / reminder message
*/
export async function generateMessage(type: "thank_you" | "reminder_gentle" | "reminder_urgent" | "whatsapp_receipt", vars: {
donorName?: string
amount: string
eventName: string
reference: string
orgName?: string
daysSincePledge?: number
}): Promise<string> {
const name = vars.donorName?.split(" ")[0] || "there"
// Templates with AI enhancement
const templates: Record<string, string> = {
thank_you: `Thank you${name !== "there" ? `, ${name}` : ""}! Your £${vars.amount} pledge to ${vars.eventName} means the world. Ref: ${vars.reference}`,
reminder_gentle: `Hi ${name}, just a friendly nudge about your £${vars.amount} pledge to ${vars.eventName}. If you've already paid — thank you! Ref: ${vars.reference}`,
reminder_urgent: `Hi ${name}, your £${vars.amount} pledge to ${vars.eventName} is still pending after ${vars.daysSincePledge || "a few"} days. We'd love to close this out — every penny counts. Ref: ${vars.reference}`,
whatsapp_receipt: `🤲 *Pledge Confirmed!*\n\n💷 Amount: £${vars.amount}\n📋 Event: ${vars.eventName}\n🔖 Reference: \`${vars.reference}\`\n\n${name !== "there" ? `Thank you, ${name}!` : "Thank you!"} Your generosity makes a real difference.\n\n_Powered by Pledge Now, Pay Later_`,
}
let msg = templates[type] || templates.thank_you
// Try AI-enhanced version for reminders
if (OPENAI_KEY && (type === "reminder_gentle" || type === "reminder_urgent")) {
const aiMsg = await chat([
{
role: "system",
content: `You write short, warm ${type === "reminder_urgent" ? "but firm" : "and gentle"} payment reminder messages for a UK charity. Max 3 sentences. Include the reference number. UK English. Be human, not corporate.`,
},
{
role: "user",
content: `Donor: ${name}. Amount: £${vars.amount}. Event: ${vars.eventName}. Reference: ${vars.reference}. Days since pledge: ${vars.daysSincePledge || "?"}. Generate the message.`,
},
], 100)
if (aiMsg) msg = aiMsg
}
return msg
}
/**
* AI-powered fuzzy reference matching for bank reconciliation
*/
export async function smartMatch(bankDescription: string, candidates: Array<{ ref: string; amount: number; donor: string }>): Promise<{
matchedRef: string | null
confidence: number
reasoning: string
}> {
if (!OPENAI_KEY || candidates.length === 0) {
return { matchedRef: null, confidence: 0, reasoning: "No AI key or no candidates" }
}
const candidateList = candidates.map(c => `${c.ref}${(c.amount / 100).toFixed(2)}, ${c.donor || "anonymous"})`).join(", ")
const result = await chat([
{
role: "system",
content: 'You match bank transaction descriptions to pledge references. Return ONLY valid JSON: {"ref":"MATCHED_REF","confidence":0.0-1.0,"reasoning":"short reason"}. If no match, ref should be null.',
},
{
role: "user",
content: `Bank description: "${bankDescription}"\nPossible pledge refs: ${candidateList}\n\nWhich pledge reference does this bank transaction match?`,
},
], 80)
try {
const parsed = JSON.parse(result)
return {
matchedRef: parsed.ref || null,
confidence: parsed.confidence || 0,
reasoning: parsed.reasoning || "",
}
} catch {
return { matchedRef: null, confidence: 0, reasoning: "Parse error" }
}
}
/**
* Generate event description from a simple prompt
*/
export async function generateEventDescription(prompt: string): Promise<string> {
if (!OPENAI_KEY) return ""
return chat([
{
role: "system",
content: "You write concise, compelling charity event descriptions for a UK audience. Max 2 sentences. Warm and inviting.",
},
{ role: "user", content: prompt },
], 60)
}

View File

@@ -0,0 +1,200 @@
/**
* WAHA (WhatsApp HTTP API) integration
* Connects to waha.quikcue.com for sending WhatsApp messages
*
* WAHA runs as a Docker service in the same Swarm overlay network.
* From within the pnpl container, we reach it via the published port or service DNS.
*/
const WAHA_URL = process.env.WAHA_API_URL || "http://tasks.qc-comms_waha:3000"
const WAHA_KEY = process.env.WAHA_API_KEY || "qc-waha-api-7Fp3nR9xYm2K"
const WAHA_SESSION = process.env.WAHA_SESSION || "default"
interface WahaResponse {
id?: string
error?: string
message?: string
}
async function wahaFetch(path: string, body?: Record<string, unknown>): Promise<WahaResponse> {
try {
const res = await fetch(`${WAHA_URL}${path}`, {
method: body ? "POST" : "GET",
headers: {
"Content-Type": "application/json",
"X-Api-Key": WAHA_KEY,
},
...(body ? { body: JSON.stringify(body) } : {}),
signal: AbortSignal.timeout(10000),
})
return res.json()
} catch (err) {
console.error("[WAHA]", path, err)
return { error: String(err) }
}
}
/**
* Normalize UK phone to WhatsApp JID format
* 07700900000 → 447700900000@c.us
* +447700900000 → 447700900000@c.us
*/
function toJid(phone: string): string {
let clean = phone.replace(/[\s\-\(\)]/g, "")
if (clean.startsWith("+")) clean = clean.slice(1)
if (clean.startsWith("0")) clean = "44" + clean.slice(1) // UK
if (!clean.includes("@")) clean += "@c.us"
return clean
}
/**
* Check if WAHA session is connected and ready
*/
export async function isWhatsAppReady(): Promise<boolean> {
try {
const sessions = await wahaFetch("/api/sessions")
if (Array.isArray(sessions)) {
return sessions.some((s: { name: string; status: string }) =>
s.name === WAHA_SESSION && s.status === "WORKING"
)
}
return false
} catch {
return false
}
}
/**
* Send a text message via WhatsApp
*/
export async function sendWhatsAppMessage(
phone: string,
text: string
): Promise<{ success: boolean; messageId?: string; error?: string }> {
const jid = toJid(phone)
const result = await wahaFetch(`/api/sendText`, {
session: WAHA_SESSION,
chatId: jid,
text,
})
if (result.id) {
return { success: true, messageId: result.id }
}
return { success: false, error: result.error || result.message || "Unknown error" }
}
/**
* Send pledge receipt via WhatsApp
*/
export async function sendPledgeReceipt(phone: string, data: {
donorName?: string
amountPounds: string
eventName: string
reference: string
rail: string
bankDetails?: { sortCode: string; accountNo: string; accountName: string }
orgName?: string
}): Promise<{ success: boolean; error?: string }> {
const name = data.donorName?.split(" ")[0] || "there"
const railEmoji: Record<string, string> = { bank: "🏦", card: "💳", gocardless: "🏛️" }
const railLabel: Record<string, string> = { bank: "Bank Transfer", card: "Card", gocardless: "Direct Debit" }
let msg = `🤲 *Pledge Confirmed!*\n\n`
msg += `Thank you, ${name}!\n\n`
msg += `💷 *£${data.amountPounds}* pledged to *${data.eventName}*\n`
msg += `${railEmoji[data.rail] || "💰"} Via: ${railLabel[data.rail] || data.rail}\n`
msg += `🔖 Ref: \`${data.reference}\`\n`
if (data.rail === "bank" && data.bankDetails) {
msg += `\n━━━━━━━━━━━━━━━━━━\n`
msg += `*Transfer to:*\n`
msg += `Sort Code: \`${data.bankDetails.sortCode}\`\n`
msg += `Account: \`${data.bankDetails.accountNo}\`\n`
msg += `Name: ${data.bankDetails.accountName}\n`
msg += `Reference: \`${data.reference}\`\n`
msg += `━━━━━━━━━━━━━━━━━━\n`
msg += `\n⚠ _Use the exact reference above_\n`
}
if (data.rail === "gocardless") {
msg += `\n✅ Direct Debit will be collected in 3-5 working days.\n`
msg += `Protected by the Direct Debit Guarantee.\n`
}
if (data.rail === "card") {
msg += `\n✅ Payment processed — receipt sent to your email.\n`
}
msg += `\n_${data.orgName || "Powered by Pledge Now, Pay Later"}_`
return sendWhatsAppMessage(phone, msg)
}
/**
* Send a payment reminder via WhatsApp
*/
export async function sendPledgeReminder(phone: string, data: {
donorName?: string
amountPounds: string
eventName: string
reference: string
daysSincePledge: number
step: number // 0=gentle, 1=nudge, 2=urgent, 3=final
}): Promise<{ success: boolean; error?: string }> {
const name = data.donorName?.split(" ")[0] || "there"
const templates = [
// Step 0: Gentle
`Hi ${name} 👋\n\nJust a quick reminder about your *£${data.amountPounds}* pledge to ${data.eventName}.\n\nIf you've already paid — thank you! 🙏\nIf not, your ref is: \`${data.reference}\`\n\nReply *PAID* if you've sent it, or *HELP* if you need the bank details again.`,
// Step 1: Nudge
`Hi ${name},\n\nYour *£${data.amountPounds}* pledge to ${data.eventName} is still pending (${data.daysSincePledge} days).\n\nEvery pound makes a real difference. 🤲\n\nRef: \`${data.reference}\`\n\nReply *PAID* once transferred, or *CANCEL* to withdraw.`,
// Step 2: Urgent
`Hi ${name},\n\nWe're reaching out about your *£${data.amountPounds}* pledge from ${data.eventName}.\n\nIt's been ${data.daysSincePledge} days and we haven't received the payment yet.\n\nRef: \`${data.reference}\`\n\nReply *PAID*, *HELP*, or *CANCEL*.`,
// Step 3: Final
`Hi ${name},\n\nThis is our final message about your *£${data.amountPounds}* pledge to ${data.eventName}.\n\nWe completely understand if circumstances have changed. Reply:\n\n*PAID* — if you've sent it\n*CANCEL* — to withdraw the pledge\n*HELP* — to get bank details\n\nRef: \`${data.reference}\``,
]
const text = templates[Math.min(data.step, 3)]
return sendWhatsAppMessage(phone, text)
}
/**
* Notify volunteer when someone pledges at their table/QR
*/
export async function notifyVolunteer(phone: string, data: {
volunteerName: string
donorName?: string
amountPounds: string
eventName: string
totalPledges: number
totalAmount: string
}): Promise<{ success: boolean; error?: string }> {
let msg = `🎉 *New Pledge!*\n\n`
msg += `${data.donorName || "Someone"} just pledged *£${data.amountPounds}* at your table!\n\n`
msg += `📊 Your total: *${data.totalPledges} pledges* · *£${data.totalAmount}*\n`
msg += `\nKeep going, ${data.volunteerName}! 💪`
return sendWhatsAppMessage(phone, msg)
}
/**
* Check WAHA status for health checks
*/
export async function getWhatsAppStatus(): Promise<{
connected: boolean
session: string
version?: string
}> {
try {
const ready = await isWhatsAppReady()
const version = await wahaFetch("/api/version")
return {
connected: ready,
session: WAHA_SESSION,
version: (version as { version?: string }).version,
}
} catch {
return { connected: false, session: WAHA_SESSION }
}
}