Files
calvana/pledge-now-pay-later/src/app/dashboard/settings/page.tsx
Omair Saleh e852250ce0 Landing page philosophy across ALL dashboard pages
Home:
- Empty state: 2-column with 'How it works' 5-step guide
- Has data: 7/5 grid — pledges left, education right
- Right column: status breakdown, sources, 'What to do next' contextual links, 'What the statuses mean' guide

Money:
- 8/4 two-column layout: table left, education right
- Right column: 'How matching works' 4-step guide, status explainer, collection tips, quick action buttons
- No more wasted right margin

Reports:
- 7/5 two-column layout: downloads left, education right
- Right column: 'For your treasurer' 3-step guide, Gift Aid FAQ, 'Understanding your numbers' explainer
- Activity log moved to right column

Settings:
- Removed max-w-2xl constraint, now uses full width
- 7/5 two-column: checklist left, education right
- Right column: 'What you're setting up' (5 items with Required badges), Privacy & data assurance, Common questions FAQ, 'Need help?' CTA
- Every setting explained in human language
2026-03-05 03:35:08 +08:00

946 lines
52 KiB
TypeScript

"use client"
import { useState, useEffect, useCallback } from "react"
import { useSession } from "next-auth/react"
import {
Check, Loader2, AlertCircle, MessageCircle, Radio, RefreshCw,
Smartphone, Wifi, WifiOff, UserPlus, Trash2, Copy,
Users, Crown, Eye, Building2, CreditCard, Palette, ChevronRight,
Zap, Pencil, Mail
} from "lucide-react"
/**
* /dashboard/settings — The Checklist Page
*
* DESIGN INSIGHT:
* Settings pages are boring because they're designed as REFERENCE PAGES —
* "here are all the knobs, turn them yourself."
*
* But Aaisha's mental model is a CHECKLIST:
* "Am I set up? What's left? Let me fix the one thing that's missing."
*
* So the page is a flat list of items. Each item has 3 visual states:
*
* ✓ CONFIGURED → collapsed to a single summary line
* "Bank account · Barclays · ****5678"
* Click [Edit] to expand the form.
*
* ○ NEEDS SETUP → expanded with instructions + form
* The first unconfigured item auto-expands.
* These are visually loud — they're the "todo."
*
* → EDITING → expanded form with Save/Cancel
* When you save, it auto-collapses back to the summary.
* Brief green flash confirms it worked.
*
* The result:
* - When everything's configured: page is SHORT. Just green checkmarks.
* - When something's missing: that section is the focus.
* - No "wall of forms" feeling.
*
* HEADER:
* Instead of a dark stats bar, a CONTEXTUAL SENTENCE:
* "You're all set" or "2 things left before you go live"
*/
interface OrgSettings {
name: string; bankName: string; bankSortCode: string; bankAccountNo: string
bankAccountName: string; refPrefix: string; primaryColor: string
gcAccessToken: string; gcEnvironment: string; orgType: string
stripeSecretKey: string; stripeWebhookSecret: string
emailProvider: string; emailApiKey: string; emailFromAddress: string; emailFromName: string
smsProvider: string; smsAccountSid: string; smsAuthToken: string; smsFromNumber: string
}
interface TeamMember {
id: string; email: string; name: string | null; role: string; createdAt: string
}
const ROLE_META: Record<string, { label: string; desc: string; icon: typeof Crown; color: string; bg: string }> = {
org_admin: { label: "Admin", desc: "Full access — settings, money, everything", icon: Crown, color: "text-[#1E40AF]", bg: "bg-[#1E40AF]/10" },
community_leader: { label: "Community Leader", desc: "Their own links and pledges. Can't change settings.", icon: Users, color: "text-[#F59E0B]", bg: "bg-[#F59E0B]/10" },
staff: { label: "Staff", desc: "Can view pledges and reports, read-only", icon: Eye, color: "text-gray-600", bg: "bg-gray-100" },
volunteer: { label: "Volunteer", desc: "Minimal access — they mostly use the live feed link", icon: Eye, color: "text-gray-400", bg: "bg-gray-50" },
}
export default function SettingsPage() {
const { data: session } = useSession()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const currentUser = session?.user as any
const [settings, setSettings] = useState<OrgSettings | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState<string | null>(null)
const [saved, setSaved] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
// Which section is expanded
const [open, setOpen] = useState<string | null>(null)
// Team
const [team, setTeam] = useState<TeamMember[]>([])
const [showInvite, setShowInvite] = useState(false)
const [inviteEmail, setInviteEmail] = useState("")
const [inviteName, setInviteName] = useState("")
const [inviteRole, setInviteRole] = useState("community_leader")
const [inviting, setInviting] = useState(false)
const [inviteResult, setInviteResult] = useState<{ email: string; tempPassword: string } | null>(null)
const [copiedCred, setCopiedCred] = useState(false)
// WhatsApp
const [waStatus, setWaStatus] = useState<string>("loading")
useEffect(() => {
Promise.all([
fetch("/api/settings").then(r => r.json()),
fetch("/api/team").then(r => r.json()).catch(() => ({ members: [] })),
]).then(([settingsData, teamData]) => {
if (settingsData.name) setSettings(settingsData)
if (teamData.members) setTeam(teamData.members)
})
.catch(() => setError("Failed to load settings"))
.finally(() => setLoading(false))
}, [])
// Auto-expand first unconfigured section
useEffect(() => {
if (!settings || open) return
const bankOk = !!(settings.bankSortCode && settings.bankAccountNo)
if (!bankOk) { setOpen("bank"); return }
// Everything essential is done — don't auto-expand
}, [settings, open])
const save = async (section: string, data: Record<string, string>) => {
setSaving(section); setError(null)
try {
const res = await fetch("/api/settings", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) })
if (res.ok) {
setSaved(section)
// Auto-collapse after save
setTimeout(() => { setOpen(null); setSaved(null) }, 1200)
} else setError("Failed to save")
} catch { setError("Failed to save") }
setSaving(null)
}
const toggle = (id: string) => setOpen(o => o === id ? null : id)
// Team actions
const inviteMember = async () => {
if (!inviteEmail.trim()) return
setInviting(true)
try {
const res = await fetch("/api/team", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: inviteEmail.trim(), name: inviteName.trim(), role: inviteRole }),
})
const data = await res.json()
if (res.ok) {
setTeam(prev => [...prev, { id: data.id, email: data.email, name: data.name, role: data.role, createdAt: new Date().toISOString() }])
setInviteResult({ email: data.email, tempPassword: data.tempPassword })
setInviteEmail(""); setInviteName("")
} else { setError(data.error || "Failed to invite") }
} catch { setError("Failed to invite") }
setInviting(false)
}
const changeRole = async (userId: string, role: string) => {
try {
await fetch("/api/team", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId, role }) })
setTeam(prev => prev.map(m => m.id === userId ? { ...m, role } : m))
} catch { setError("Failed to update role") }
}
const removeMember = async (userId: string) => {
if (!confirm("Remove this team member?")) return
try {
await fetch("/api/team", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId }) })
setTeam(prev => prev.filter(m => m.id !== userId))
} catch { setError("Failed to remove") }
}
const copyCredentials = (email: string, password: string) => {
navigator.clipboard.writeText(`Email: ${email}\nPassword: ${password}\nLogin: ${window.location.origin}/login`)
setCopiedCred(true); setTimeout(() => setCopiedCred(false), 2000)
}
if (loading) return <div className="flex items-center justify-center py-20"><Loader2 className="h-6 w-6 text-[#1E40AF] animate-spin" /></div>
if (!settings) return <div className="text-center py-20"><AlertCircle className="h-6 w-6 text-[#DC2626] mx-auto mb-2" /><p className="text-sm text-gray-500">Failed to load settings</p></div>
const update = (key: keyof OrgSettings, value: string) => setSettings(s => s ? { ...s, [key]: value } : s)
const isAdmin = currentUser?.role === "org_admin" || currentUser?.role === "super_admin"
// Readiness
const bankReady = !!(settings.bankSortCode && settings.bankAccountNo && settings.bankAccountName)
const whatsappReady = waStatus === "CONNECTED"
const stripeReady = !!settings.stripeSecretKey
const charityReady = !!settings.name
const essentials = [whatsappReady, bankReady, charityReady]
const doneCount = essentials.filter(Boolean).length
const totalCount = essentials.length
// Header message
const headerMsg = doneCount === totalCount
? "You're all set. Donors can pledge and you'll get WhatsApp notifications."
: doneCount === 0
? "Let's get you set up. Start with WhatsApp — it takes 30 seconds."
: `${totalCount - doneCount} thing${totalCount - doneCount > 1 ? "s" : ""} left before you go live.`
return (
<div className="space-y-6">
{/* ── Header — human progress, not a form page ── */}
<div className={`p-6 mb-6 ${doneCount === totalCount ? "bg-[#16A34A]" : "bg-[#111827]"}`}>
<div className="border-l-2 border-[#F59E0B] pl-3 mb-3">
<p className="text-[11px] font-semibold tracking-[0.15em] uppercase text-gray-500">Settings</p>
</div>
<h1 className="text-2xl md:text-3xl font-black text-white tracking-tight">
{settings.name}
</h1>
<p className="text-sm text-gray-400 mt-2">{headerMsg}</p>
<div className="flex items-center gap-3 mt-4">
<div className="flex-1 h-1.5 bg-white/10 overflow-hidden">
<div
className={`h-full transition-all duration-700 ${doneCount === totalCount ? "bg-white" : "bg-[#1E40AF]"}`}
style={{ width: `${Math.round((doneCount / totalCount) * 100)}%` }}
/>
</div>
<span className="text-xs font-bold text-white shrink-0">{doneCount}/{totalCount}</span>
</div>
</div>
{error && <div className="border-l-2 border-[#DC2626] bg-[#DC2626]/5 p-3 text-sm text-[#DC2626]">{error}</div>}
{/* ━━ TWO-COLUMN: Checklist left, Education right ━━━━━━ */}
<div className="grid lg:grid-cols-12 gap-6">
{/* LEFT: The Checklist */}
<div className="lg:col-span-7">
<div className="border border-gray-200 divide-y divide-gray-100 bg-white">
{/* ▸ WhatsApp ─────────────────────────── */}
<WhatsAppRow
waStatus={waStatus}
onStatusChange={setWaStatus}
isOpen={open === "whatsapp"}
onToggle={() => toggle("whatsapp")}
/>
{/* ▸ Bank account ─────────────────────── */}
<SettingRow
configured={bankReady}
icon={<Building2 className={`h-4 w-4 ${bankReady ? "text-[#16A34A]" : "text-gray-400"}`} />}
title="Bank account"
summary={bankReady ? `${settings.bankName || "Bank"} · ${settings.bankSortCode} · ****${settings.bankAccountNo.slice(-4)}` : "Where donors send their payment"}
isOpen={open === "bank"}
onToggle={() => toggle("bank")}
saving={saving === "bank"}
saved={saved === "bank"}
>
<div className="space-y-4">
<div className="border-l-2 border-[#1E40AF] pl-3 text-xs text-gray-500">
Donors see these details after pledging, with a unique reference to match their payment.
</div>
<div className="grid grid-cols-2 gap-3">
<Field label="Bank name" value={settings.bankName} onChange={v => update("bankName", v)} placeholder="e.g. Barclays" />
<Field label="Account name" value={settings.bankAccountName} onChange={v => update("bankAccountName", v)} placeholder="e.g. Al Furqan Mosque" />
</div>
<div className="grid grid-cols-2 gap-3">
<Field label="Sort code" value={settings.bankSortCode} onChange={v => update("bankSortCode", v)} placeholder="20-30-80" />
<Field label="Account number" value={settings.bankAccountNo} onChange={v => update("bankAccountNo", v)} placeholder="12345678" />
</div>
<div className="grid grid-cols-[96px_1fr] gap-3 items-end">
<Field label="Ref prefix" value={settings.refPrefix} onChange={v => update("refPrefix", v)} maxLength={4} />
<p className="text-[10px] text-gray-400 pb-2.5">Donors see <strong className="text-[#111827]">{settings.refPrefix || "PNPL"}-A2F4-50</strong></p>
</div>
{/* Live preview */}
{bankReady && (
<div className="bg-[#F9FAFB] border border-gray-100 p-4">
<p className="text-[9px] font-bold text-gray-400 uppercase tracking-wide mb-2">What donors see</p>
<div className="grid grid-cols-[72px_1fr] gap-y-1 text-xs">
<span className="text-gray-400">Bank</span><span className="font-bold text-[#111827]">{settings.bankName}</span>
<span className="text-gray-400">Name</span><span className="font-bold text-[#111827]">{settings.bankAccountName}</span>
<span className="text-gray-400">Sort code</span><span className="font-mono font-bold text-[#111827]">{settings.bankSortCode}</span>
<span className="text-gray-400">Account</span><span className="font-mono font-bold text-[#111827]">{settings.bankAccountNo}</span>
<span className="text-gray-400">Reference</span><span className="font-mono font-bold text-[#1E40AF]">{settings.refPrefix || "PNPL"}-A2F4-50</span>
</div>
</div>
)}
<SaveRow
section="bank" saving={saving} saved={saved}
onSave={() => save("bank", { bankName: settings.bankName, bankSortCode: settings.bankSortCode, bankAccountNo: settings.bankAccountNo, bankAccountName: settings.bankAccountName, refPrefix: settings.refPrefix })}
onCancel={() => setOpen(null)}
/>
</div>
</SettingRow>
{/* ▸ Charity name ─────────────────────── */}
<SettingRow
configured={charityReady}
icon={<Palette className={`h-4 w-4 ${charityReady ? "text-[#111827]" : "text-gray-400"}`} />}
title="Your charity"
summary={charityReady
? <span className="flex items-center gap-2">{settings.name} <span className="w-3 h-3 border border-gray-200 shrink-0" style={{ backgroundColor: settings.primaryColor || "#1E40AF" }} /></span>
: "Name and colour shown on pledge pages"
}
isOpen={open === "charity"}
onToggle={() => toggle("charity")}
saving={saving === "brand"}
saved={saved === "brand"}
>
<div className="space-y-4">
<Field label="Charity name" value={settings.name} onChange={v => update("name", v)} placeholder="e.g. Al Furqan Mosque" />
<div>
<label className="text-[10px] font-bold text-gray-500 uppercase tracking-wide block mb-1.5">Brand colour</label>
<div className="flex gap-2">
<div className="w-10 h-10 border-2 border-gray-200 shrink-0 cursor-pointer relative overflow-hidden" style={{ backgroundColor: settings.primaryColor || "#1E40AF" }}>
<input type="color" value={settings.primaryColor || "#1E40AF"} onChange={e => update("primaryColor", e.target.value)} className="absolute inset-0 w-full h-full opacity-0 cursor-pointer" />
</div>
<input value={settings.primaryColor || "#1E40AF"} onChange={e => update("primaryColor", e.target.value)} className="flex-1 h-10 px-3 border-2 border-gray-200 text-sm font-mono focus:border-[#1E40AF] outline-none" />
</div>
</div>
{/* Preview */}
<div className="bg-[#F9FAFB] border border-gray-100 p-4">
<p className="text-[9px] font-bold text-gray-400 uppercase tracking-wide mb-2">Pledge page header</p>
<div className="bg-white border border-gray-200 p-3 flex items-center gap-2.5">
<div className="h-7 w-7 flex items-center justify-center" style={{ backgroundColor: settings.primaryColor || "#1E40AF" }}>
<span className="text-white text-[10px] font-black">{(settings.name || "P")[0].toUpperCase()}</span>
</div>
<span className="font-black text-sm tracking-tight text-[#111827]">{settings.name || "Your Charity"}</span>
</div>
</div>
<SaveRow
section="brand" saving={saving} saved={saved}
onSave={() => save("brand", { name: settings.name, primaryColor: settings.primaryColor })}
onCancel={() => setOpen(null)}
/>
</div>
</SettingRow>
{/* ▸ Card payments (Stripe) ────────────── */}
<SettingRow
configured={stripeReady}
icon={<CreditCard className={`h-4 w-4 ${stripeReady ? "text-[#635BFF]" : "text-gray-400"}`} />}
title="Card payments"
summary={stripeReady ? "Stripe connected · donors can pay by card" : "Optional — let donors pay by Visa, Mastercard, Apple Pay"}
isOpen={open === "stripe"}
onToggle={() => toggle("stripe")}
optional
saving={saving === "stripe"}
saved={saved === "stripe"}
>
<div className="space-y-4">
<div className="border-l-2 border-[#635BFF] pl-3 text-xs text-gray-500">
Connect your <strong className="text-gray-700">own Stripe account</strong>. Money goes to your balance we never touch it.
</div>
{!stripeReady && (
<div className="bg-[#F9FAFB] border border-gray-100 p-3">
<p className="text-[10px] font-bold text-[#111827] mb-1.5">How to get your key</p>
<ol className="text-[10px] text-gray-500 space-y-1 list-decimal list-inside">
<li>Go to <a href="https://dashboard.stripe.com/apikeys" target="_blank" rel="noopener noreferrer" className="text-[#635BFF] font-bold hover:underline">dashboard.stripe.com/apikeys</a></li>
<li>Copy the <strong className="text-gray-700">Secret key</strong> (<code className="bg-gray-100 px-1 text-[9px] font-mono">sk_live_</code> or <code className="bg-gray-100 px-1 text-[9px] font-mono">sk_test_</code>)</li>
<li>Paste below</li>
</ol>
</div>
)}
<Field label="Stripe secret key" value={settings.stripeSecretKey || ""} onChange={v => update("stripeSecretKey", v)} placeholder="sk_live_... or sk_test_..." type="password" />
<details className="text-xs">
<summary className="text-gray-400 cursor-pointer hover:text-gray-600 font-bold">Webhook (optional auto-confirms payments)</summary>
<div className="mt-3 pt-3 border-t border-gray-100 space-y-3">
<div className="text-[10px] text-gray-500 space-y-1">
<p>Add this endpoint in Stripe Developers Webhooks:</p>
<code className="block bg-gray-50 px-2 py-1.5 font-mono text-[9px] border border-gray-100">{typeof window !== "undefined" ? window.location.origin : ""}/api/stripe/webhook</code>
<p>Event: <code className="bg-gray-50 px-1 font-mono text-[9px]">checkout.session.completed</code></p>
</div>
<Field label="Webhook secret" value={settings.stripeWebhookSecret || ""} onChange={v => update("stripeWebhookSecret", v)} placeholder="whsec_..." type="password" />
</div>
</details>
{stripeReady && (
<div className="bg-[#635BFF]/5 border border-[#635BFF]/20 p-3 flex items-start gap-2">
<Zap className="h-3.5 w-3.5 text-[#635BFF] mt-0.5 shrink-0" />
<p className="text-[10px] text-gray-600"><strong className="text-[#635BFF]">Live.</strong> Donors see &ldquo;Pay by Card.&rdquo; Visa, Mastercard, Amex, Apple Pay, Google Pay.</p>
</div>
)}
<SaveRow
section="stripe" saving={saving} saved={saved}
onSave={() => save("stripe", { stripeSecretKey: settings.stripeSecretKey || "", stripeWebhookSecret: settings.stripeWebhookSecret || "" })}
onCancel={() => setOpen(null)}
/>
</div>
</SettingRow>
{/* ▸ Email ─────────────────────────────── */}
<SettingRow
configured={!!settings.emailApiKey}
icon={<Mail className={`h-4 w-4 ${settings.emailApiKey ? "text-[#1E40AF]" : "text-gray-400"}`} />}
title="Email"
summary={settings.emailApiKey ? `${settings.emailProvider || "Resend"} · ${settings.emailFromAddress}` : "Send receipts and reminders by email"}
isOpen={open === "email"}
onToggle={() => toggle("email")}
optional
saving={saving === "email"}
saved={saved === "email"}
>
<div className="space-y-4">
<div className="border-l-2 border-[#1E40AF] pl-3 text-xs text-gray-500">
Send receipts and reminders to donors who don&apos;t have WhatsApp. Connect your <strong className="text-gray-700">own email provider</strong> messages come from your domain.
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 uppercase tracking-wide block mb-2">Provider</label>
<div className="flex gap-2">
{["resend", "sendgrid"].map(p => (
<button key={p} onClick={() => update("emailProvider", p)} className={`px-4 py-2 text-xs font-bold border-2 transition-colors ${(settings.emailProvider || "resend") === p ? "border-[#1E40AF] bg-[#1E40AF]/5 text-[#1E40AF]" : "border-gray-200 text-gray-400"}`}>
{p === "resend" ? "Resend" : "SendGrid"}
</button>
))}
</div>
{(settings.emailProvider || "resend") === "resend" && !settings.emailApiKey && (
<p className="text-[10px] text-gray-400 mt-2">Free: 3,000 emails/month at <a href="https://resend.com" target="_blank" rel="noopener noreferrer" className="text-[#1E40AF] font-bold hover:underline">resend.com</a></p>
)}
</div>
<Field label="API key" value={settings.emailApiKey || ""} onChange={v => update("emailApiKey", v)} placeholder={settings.emailProvider === "sendgrid" ? "SG.xxxxx" : "re_xxxxx"} type="password" />
<div className="grid grid-cols-2 gap-3">
<Field label="From address" value={settings.emailFromAddress || ""} onChange={v => update("emailFromAddress", v)} placeholder="donations@mymosque.org" />
<Field label="From name" value={settings.emailFromName || ""} onChange={v => update("emailFromName", v)} placeholder="Al Furqan Mosque" />
</div>
<SaveRow
section="email" saving={saving} saved={saved}
onSave={() => save("email", { emailProvider: settings.emailProvider || "resend", emailApiKey: settings.emailApiKey || "", emailFromAddress: settings.emailFromAddress || "", emailFromName: settings.emailFromName || "" })}
onCancel={() => setOpen(null)}
/>
</div>
</SettingRow>
{/* ▸ SMS ──────────────────────────────── */}
<SettingRow
configured={!!settings.smsAccountSid}
icon={<Smartphone className={`h-4 w-4 ${settings.smsAccountSid ? "text-[#F59E0B]" : "text-gray-400"}`} />}
title="SMS"
summary={settings.smsAccountSid ? `Twilio · ${settings.smsFromNumber}` : "Text reminders for donors without WhatsApp"}
isOpen={open === "sms"}
onToggle={() => toggle("sms")}
optional
saving={saving === "sms"}
saved={saved === "sms"}
>
<div className="space-y-4">
<div className="border-l-2 border-[#F59E0B] pl-3 text-xs text-gray-500">
Send SMS reminders via <strong className="text-gray-700">Twilio</strong>. Reaches donors who don&apos;t have WhatsApp and haven&apos;t provided an email. Pay-as-you-go (~3p per SMS).
</div>
{!settings.smsAccountSid && (
<div className="bg-[#F9FAFB] border border-gray-100 p-3">
<p className="text-[10px] font-bold text-[#111827] mb-1">Get your Twilio credentials</p>
<ol className="text-[10px] text-gray-500 space-y-1 list-decimal list-inside">
<li>Sign up at <a href="https://www.twilio.com" target="_blank" rel="noopener noreferrer" className="text-[#F59E0B] font-bold hover:underline">twilio.com</a></li>
<li>Copy your <strong className="text-gray-700">Account SID</strong> and <strong className="text-gray-700">Auth Token</strong> from the dashboard</li>
<li>Buy a phone number (or use the trial number)</li>
</ol>
</div>
)}
<Field label="Account SID" value={settings.smsAccountSid || ""} onChange={v => update("smsAccountSid", v)} placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<Field label="Auth token" value={settings.smsAuthToken || ""} onChange={v => update("smsAuthToken", v)} placeholder="Your auth token" type="password" />
<Field label="From number" value={settings.smsFromNumber || ""} onChange={v => update("smsFromNumber", v)} placeholder="+447123456789" />
<SaveRow
section="sms" saving={saving} saved={saved}
onSave={() => save("sms", { smsProvider: "twilio", smsAccountSid: settings.smsAccountSid || "", smsAuthToken: settings.smsAuthToken || "", smsFromNumber: settings.smsFromNumber || "" })}
onCancel={() => setOpen(null)}
/>
</div>
</SettingRow>
{/* ▸ Team ─────────────────────────────── */}
{isAdmin && (
<TeamRow
team={team}
currentUser={currentUser}
isOpen={open === "team"}
onToggle={() => toggle("team")}
showInvite={showInvite}
setShowInvite={setShowInvite}
inviteEmail={inviteEmail} setInviteEmail={setInviteEmail}
inviteName={inviteName} setInviteName={setInviteName}
inviteRole={inviteRole} setInviteRole={setInviteRole}
inviting={inviting} inviteMember={inviteMember}
inviteResult={inviteResult} setInviteResult={setInviteResult}
copiedCred={copiedCred} copyCredentials={copyCredentials}
changeRole={changeRole} removeMember={removeMember}
orgName={settings?.name}
/>
)}
{/* ▸ Direct Debit ─────────────────────── */}
<SettingRow
configured={!!settings.gcAccessToken}
icon={<Building2 className="h-4 w-4 text-gray-400" />}
title="Direct Debit"
summary={settings.gcAccessToken ? `GoCardless · ${settings.gcEnvironment}` : "GoCardless — most charities don't need this"}
isOpen={open === "gc"}
onToggle={() => toggle("gc")}
optional
dimmed
saving={saving === "gc"}
saved={saved === "gc"}
>
<div className="space-y-4">
<div className="border-l-2 border-gray-300 pl-3 text-xs text-gray-500">
Accept Direct Debit via GoCardless. Donors set up a mandate and payments auto-collect. Bank transfer works fine for most charities.
</div>
<Field label="GoCardless access token" value={settings.gcAccessToken} onChange={v => update("gcAccessToken", v)} placeholder="sandbox_xxxxx or live_xxxxx" type="password" />
<div>
<label className="text-[10px] font-bold text-gray-500 uppercase tracking-wide block mb-2">Mode</label>
<div className="flex gap-2">
{(["sandbox", "live"] as const).map(env => (
<button key={env} onClick={() => update("gcEnvironment", env)} className={`px-4 py-2 text-xs font-bold border-2 transition-colors ${settings.gcEnvironment === env ? env === "live" ? "border-[#DC2626] bg-[#DC2626]/5 text-[#DC2626]" : "border-[#1E40AF] bg-[#1E40AF]/5 text-[#1E40AF]" : "border-gray-200 text-gray-400"}`}>
{env === "sandbox" ? "Test" : "Live"}
</button>
))}
</div>
</div>
<SaveRow
section="gc" saving={saving} saved={saved}
onSave={() => save("gc", { gcAccessToken: settings.gcAccessToken, gcEnvironment: settings.gcEnvironment })}
onCancel={() => setOpen(null)}
/>
</div>
</SettingRow>
</div>
</div>
{/* RIGHT: Education + Context */}
<div className="lg:col-span-5 space-y-6">
{/* What each setting does */}
<div className="border border-gray-200 bg-white">
<div className="border-b border-gray-100 px-5 py-3">
<h3 className="text-sm font-bold text-[#111827]">What you&apos;re setting up</h3>
</div>
<div className="divide-y divide-gray-50">
{[
{ n: "01", title: "WhatsApp", desc: "Scan a QR code to connect your phone. Donors get receipts and reminders automatically. They can reply PAID, HELP, or CANCEL.", essential: true },
{ n: "02", title: "Bank account", desc: "Your sort code and account number. Shown to donors after they pledge so they know where to send money.", essential: true },
{ n: "03", title: "Your charity", desc: "Name and brand colour shown on pledge pages. Donors see this when they tap your link.", essential: true },
{ n: "04", title: "Card payments", desc: "Connect Stripe to let donors pay by Visa, Mastercard, or Apple Pay. Money goes straight to your account.", essential: false },
{ n: "05", title: "Team", desc: "Invite community leaders and volunteers. They get their own pledge links and can see their own results.", essential: false },
].map(s => (
<div key={s.n} className="px-5 py-3 flex gap-3">
<span className={`text-lg font-black shrink-0 w-6 ${s.essential ? "text-[#1E40AF]" : "text-gray-200"}`}>{s.n}</span>
<div>
<p className="text-xs font-bold text-[#111827] flex items-center gap-1.5">
{s.title}
{s.essential && <span className="text-[8px] font-bold bg-[#1E40AF]/10 text-[#1E40AF] px-1 py-0.5">Required</span>}
</p>
<p className="text-[11px] text-gray-500 leading-relaxed mt-0.5">{s.desc}</p>
</div>
</div>
))}
</div>
</div>
{/* Privacy & data */}
<div className="border-l-2 border-[#1E40AF] pl-4 space-y-2">
<p className="text-xs font-bold text-[#111827]">Privacy &amp; data</p>
<div className="space-y-1.5">
<p className="text-[10px] text-gray-500">
<strong className="text-[#111827]">Your data stays yours.</strong> We never access your Stripe account, bank details, or WhatsApp messages. Everything is stored encrypted.
</p>
<p className="text-[10px] text-gray-500">
<strong className="text-[#111827]">GDPR compliant.</strong> Donor consent is recorded at pledge time. You can export or delete all data anytime.
</p>
<p className="text-[10px] text-gray-500">
<strong className="text-[#111827]">No vendor lock-in.</strong> Download your full data as CSV from Reports. Your donors, your data, always.
</p>
</div>
</div>
{/* Common questions */}
<div className="border-l-2 border-[#F59E0B] pl-4 space-y-2">
<p className="text-xs font-bold text-[#111827]">Common questions</p>
<div className="space-y-2">
{[
{ q: "Do I need Stripe?", a: "No — most charities use bank transfer only. Stripe is optional for orgs that want card payments." },
{ q: "Can I change my bank details later?", a: "Yes. New pledges will show the updated details. Existing pledges keep the original reference." },
{ q: "What happens if WhatsApp disconnects?", a: "Reminders pause until you reconnect. Come back here, scan the QR again. It takes 30 seconds." },
{ q: "Can volunteers see financial data?", a: "No. Volunteers only see their own link performance. Admins see everything." },
].map(item => (
<div key={item.q}>
<p className="text-[11px] font-bold text-[#111827]">{item.q}</p>
<p className="text-[10px] text-gray-500">{item.a}</p>
</div>
))}
</div>
</div>
{/* Need help? */}
<div className="bg-[#111827] p-5">
<p className="text-xs font-bold text-white">Need help setting up?</p>
<p className="text-[11px] text-gray-400 mt-1 leading-relaxed">
Our team can walk you through the setup in 15 minutes. Free, no strings attached.
</p>
<a href="mailto:omair@quikcue.com" className="inline-block mt-3 border border-gray-600 px-3 py-1.5 text-[11px] font-bold text-gray-300 hover:text-white hover:border-white transition-colors">
Get in touch
</a>
</div>
</div>
</div>
</div>
)
}
// ─── SettingRow: the core pattern ────────────────────────────
// Collapsed = one line. Expanded = form.
function SettingRow({ configured, icon, title, summary, isOpen, onToggle, children, optional, dimmed, saving, saved }: {
configured: boolean; icon: React.ReactNode; title: string; summary: React.ReactNode
isOpen: boolean; onToggle: () => void; children: React.ReactNode
optional?: boolean; dimmed?: boolean; saving?: boolean; saved?: boolean
}) {
return (
<div className={dimmed && !isOpen ? "opacity-60 hover:opacity-100 transition-opacity" : ""}>
{/* Summary row — always visible */}
<button
onClick={onToggle}
className={`w-full px-5 py-4 flex items-center gap-3 text-left transition-colors group ${isOpen ? "" : "hover:bg-[#F9FAFB]"}`}
>
{/* Status dot */}
<div className={`w-2 h-2 shrink-0 ${
saved ? "bg-[#16A34A]" :
saving ? "bg-[#1E40AF]" :
configured ? "bg-[#16A34A]" :
optional ? "bg-gray-300" : "bg-[#F59E0B]"
}`} />
{/* Icon */}
<div className="w-6 flex items-center justify-center shrink-0">{icon}</div>
{/* Content */}
<div className="flex-1 min-w-0">
<p className="text-sm font-bold text-[#111827]">{title}</p>
{!isOpen && <p className="text-[10px] text-gray-500 truncate mt-0.5">{summary}</p>}
</div>
{/* Action hint */}
{!isOpen && (
configured ? (
<span className="text-[10px] font-bold text-gray-300 group-hover:text-[#1E40AF] transition-colors flex items-center gap-1">
<Pencil className="h-3 w-3" /> Edit
</span>
) : (
<span className="text-[10px] font-bold text-[#1E40AF]">Set up </span>
)
)}
{isOpen && <ChevronRight className="h-4 w-4 text-gray-300 rotate-90 shrink-0" />}
</button>
{/* Expanded form */}
{isOpen && (
<div className="px-5 pb-5 pt-0">
<div className="border-l-2 border-[#1E40AF] pl-4 ml-[3px]">
{children}
</div>
</div>
)}
</div>
)
}
// ─── WhatsApp Row (special: has QR flow) ─────────────────────
function WhatsAppRow({ waStatus, onStatusChange, isOpen, onToggle }: {
waStatus: string; onStatusChange: (s: string) => void
isOpen: boolean; onToggle: () => void
}) {
const [qrImage, setQrImage] = useState<string | null>(null)
const [phone, setPhone] = useState("")
const [pushName, setPushName] = useState("")
const [starting, setStarting] = useState(false)
const [showQr, setShowQr] = useState(false)
const checkStatus = useCallback(async () => {
try {
const res = await fetch("/api/whatsapp/qr")
const data = await res.json()
onStatusChange(data.status)
if (data.screenshot) setQrImage(data.screenshot)
if (data.phone) setPhone(data.phone)
if (data.pushName) setPushName(data.pushName)
if (data.status === "CONNECTED") setShowQr(false)
} catch { onStatusChange("ERROR") }
}, [onStatusChange])
useEffect(() => { checkStatus() }, [checkStatus])
useEffect(() => { if (!showQr) return; const i = setInterval(checkStatus, 5000); return () => clearInterval(i) }, [showQr, checkStatus])
const startSession = async () => {
setStarting(true); setShowQr(true)
try {
await fetch("/api/whatsapp/qr", { method: "POST" })
await new Promise(r => setTimeout(r, 3000))
await checkStatus()
} catch { /* */ }
setStarting(false)
}
const connected = waStatus === "CONNECTED"
const scanning = waStatus === "SCAN_QR_CODE" && showQr
return (
<div>
{/* Summary row */}
<button onClick={onToggle} className={`w-full px-5 py-4 flex items-center gap-3 text-left transition-colors group ${isOpen ? "" : "hover:bg-[#F9FAFB]"}`}>
<div className={`w-2 h-2 shrink-0 ${connected ? "bg-[#25D366]" : scanning ? "bg-[#F59E0B]" : "bg-[#F59E0B]"}`} />
<div className="w-6 flex items-center justify-center shrink-0">
{connected ? <Smartphone className="h-4 w-4 text-[#25D366]" /> : <WifiOff className="h-4 w-4 text-gray-400" />}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-bold text-[#111827]">WhatsApp</p>
{connected && <span className="text-[8px] font-bold px-1 py-0.5 bg-[#25D366]/10 text-[#25D366] flex items-center gap-0.5"><Radio className="h-2 w-2" /> Live</span>}
</div>
{!isOpen && <p className="text-[10px] text-gray-500 truncate mt-0.5">
{connected ? `${pushName || "WhatsApp"} · +${phone} · Receipts, reminders, chatbot` : scanning ? "Waiting for QR scan…" : "Connect to send receipts and reminders"}
</p>}
</div>
{!isOpen && (
connected ? <span className="text-[10px] font-bold text-gray-300 group-hover:text-[#1E40AF] transition-colors">Details</span>
: scanning ? <span className="text-[10px] font-bold text-[#F59E0B]">Scanning</span>
: <span className="text-[10px] font-bold text-[#25D366]">Connect </span>
)}
{isOpen && <ChevronRight className="h-4 w-4 text-gray-300 rotate-90 shrink-0" />}
</button>
{/* Expanded content */}
{isOpen && (
<div className="px-5 pb-5">
<div className="border-l-2 border-[#25D366] pl-4 ml-[3px] space-y-4">
{/* Connected: show features */}
{connected && (
<>
<div className="flex items-center gap-3">
<Wifi className="h-5 w-5 text-[#25D366]" />
<div>
<p className="text-sm font-bold text-[#111827]">{pushName || "WhatsApp"}</p>
<p className="text-[10px] text-gray-500">+{phone}</p>
</div>
</div>
<div className="grid grid-cols-3 gap-px bg-[#25D366]/10">
{[
{ label: "Receipts", desc: "Auto-sent on pledge" },
{ label: "Reminders", desc: "4-step nudge sequence" },
{ label: "Chatbot", desc: "PAID, HELP, CANCEL" },
].map(f => (
<div key={f.label} className="bg-white p-3 text-center">
<p className="text-[10px] font-bold text-[#111827]">{f.label}</p>
<p className="text-[8px] text-gray-500 mt-0.5">{f.desc}</p>
</div>
))}
</div>
</>
)}
{/* Scanning: show QR */}
{scanning && (
<div className="flex flex-col items-center gap-3 py-2">
{qrImage ? (
<div className="w-56 h-56 border-2 border-[#25D366]/20 overflow-hidden bg-white">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={qrImage} alt="QR" className="w-[200%] h-auto max-w-none" style={{ marginLeft: "-30%", marginTop: "-35%" }} />
</div>
) : (
<div className="w-56 h-56 border-2 border-dashed border-gray-200 flex items-center justify-center"><Loader2 className="h-5 w-5 text-gray-300 animate-spin" /></div>
)}
<p className="text-xs text-gray-500">WhatsApp Settings Linked Devices Link a Device</p>
<button onClick={checkStatus} className="border border-gray-200 px-3 py-1.5 text-[10px] font-bold text-gray-500 hover:bg-gray-50 flex items-center gap-1"><RefreshCw className="h-3 w-3" /> Refresh</button>
</div>
)}
{/* Not connected: show connect button */}
{!connected && !scanning && (
<>
<div className="text-xs text-gray-500 space-y-1">
<p className="font-bold text-[#111827]">When connected, donors automatically receive:</p>
<p>Pledge receipt with your bank details within seconds</p>
<p>Payment reminders 4-step sequence over 14 days</p>
<p>Chatbot they text <span className="font-mono font-bold text-[#111827]">PAID</span>, <span className="font-mono font-bold text-[#111827]">HELP</span>, or <span className="font-mono font-bold text-[#111827]">CANCEL</span></p>
</div>
<button onClick={startSession} disabled={starting} className="w-full bg-[#25D366] px-4 py-2.5 text-sm font-bold text-white hover:bg-[#25D366]/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2">
{starting ? <><Loader2 className="h-4 w-4 animate-spin" /> Starting</> : <><MessageCircle className="h-4 w-4" /> Connect WhatsApp</>}
</button>
</>
)}
</div>
</div>
)}
</div>
)
}
// ─── Team Row (special: has member list + invite) ────────────
function TeamRow({ team, currentUser, isOpen, onToggle, showInvite, setShowInvite, inviteEmail, setInviteEmail, inviteName, setInviteName, inviteRole, setInviteRole, inviting, inviteMember, inviteResult, setInviteResult, copiedCred, copyCredentials, changeRole, removeMember, orgName }: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
team: TeamMember[]; currentUser: any; isOpen: boolean; onToggle: () => void
showInvite: boolean; setShowInvite: (v: boolean) => void
inviteEmail: string; setInviteEmail: (v: string) => void
inviteName: string; setInviteName: (v: string) => void
inviteRole: string; setInviteRole: (v: string) => void
inviting: boolean; inviteMember: () => void
inviteResult: { email: string; tempPassword: string } | null; setInviteResult: (v: null) => void
copiedCred: boolean; copyCredentials: (e: string, p: string) => void
changeRole: (id: string, role: string) => void; removeMember: (id: string) => void; orgName?: string
}) {
const isAdmin = currentUser?.role === "org_admin" || currentUser?.role === "super_admin"
const summary = team.length === 0 ? "Just you — invite community leaders to track their pledges"
: team.length === 1 ? "1 member"
: `${team.length} members · ${team.filter(m => m.role === "community_leader").length} leader${team.filter(m => m.role === "community_leader").length !== 1 ? "s" : ""}`
return (
<div>
<button onClick={onToggle} className={`w-full px-5 py-4 flex items-center gap-3 text-left transition-colors group ${isOpen ? "" : "hover:bg-[#F9FAFB]"}`}>
<div className={`w-2 h-2 shrink-0 ${team.length > 1 ? "bg-[#16A34A]" : "bg-gray-300"}`} />
<div className="w-6 flex items-center justify-center shrink-0"><Users className="h-4 w-4 text-[#1E40AF]" /></div>
<div className="flex-1 min-w-0">
<p className="text-sm font-bold text-[#111827]">Team</p>
{!isOpen && <p className="text-[10px] text-gray-500 truncate mt-0.5">{summary}</p>}
</div>
{!isOpen && <span className="text-[10px] font-bold text-gray-300 group-hover:text-[#1E40AF] transition-colors">Manage</span>}
{isOpen && <ChevronRight className="h-4 w-4 text-gray-300 rotate-90 shrink-0" />}
</button>
{isOpen && (
<div className="px-5 pb-5">
<div className="border-l-2 border-[#1E40AF] pl-4 ml-[3px] space-y-3">
{/* Invite button */}
{!showInvite && !inviteResult && (
<button onClick={() => setShowInvite(true)} className="bg-[#111827] px-3 py-1.5 text-xs font-bold text-white hover:bg-gray-800 transition-colors flex items-center gap-1.5">
<UserPlus className="h-3.5 w-3.5" /> Invite someone
</button>
)}
{/* Invite form */}
{showInvite && !inviteResult && (
<div className="bg-[#F9FAFB] border border-gray-100 p-4 space-y-3">
<div className="grid grid-cols-2 gap-3">
<Field label="Email" value={inviteEmail} onChange={setInviteEmail} placeholder="imam@mosque.org" />
<Field label="Name (optional)" value={inviteName} onChange={setInviteName} placeholder="Imam Yusuf" />
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 uppercase tracking-wide block mb-2">Role</label>
<div className="grid grid-cols-2 gap-1.5">
{Object.entries(ROLE_META).filter(([k]) => k !== "org_admin" || currentUser?.role === "super_admin").map(([key, r]) => (
<button key={key} onClick={() => setInviteRole(key)} className={`border-2 p-2.5 text-left transition-all ${inviteRole === key ? "border-[#1E40AF] bg-[#1E40AF]/5" : "border-gray-200 bg-white"}`}>
<p className="text-[10px] font-bold text-[#111827]">{r.label}</p>
<p className="text-[9px] text-gray-500">{r.desc}</p>
</button>
))}
</div>
</div>
<div className="flex gap-2">
<button onClick={() => setShowInvite(false)} className="flex-1 border border-gray-200 py-2 text-[10px] font-bold">Cancel</button>
<button onClick={inviteMember} disabled={!inviteEmail.trim() || inviting} className="flex-1 bg-[#111827] py-2 text-[10px] font-bold text-white disabled:opacity-40 flex items-center justify-center gap-1">
{inviting ? <Loader2 className="h-3 w-3 animate-spin" /> : "Create account"}
</button>
</div>
</div>
)}
{/* Invite result */}
{inviteResult && (
<div className="bg-[#16A34A]/5 border border-[#16A34A]/20 p-4 space-y-3">
<p className="text-xs font-bold text-[#111827] flex items-center gap-1.5"><Check className="h-3.5 w-3.5 text-[#16A34A]" /> Account created</p>
<div className="bg-white border border-gray-200 p-3 grid grid-cols-[72px_1fr] gap-1 text-[10px]">
<span className="text-gray-400">Email</span><span className="font-mono font-bold">{inviteResult.email}</span>
<span className="text-gray-400">Password</span><span className="font-mono font-bold">{inviteResult.tempPassword}</span>
<span className="text-gray-400">Login</span><span className="font-mono font-bold text-[9px]">{typeof window !== "undefined" ? window.location.origin : ""}/login</span>
</div>
<div className="grid grid-cols-2 gap-2">
<button onClick={() => copyCredentials(inviteResult.email, inviteResult.tempPassword)} className={`py-2 text-[10px] font-bold flex items-center justify-center gap-1 ${copiedCred ? "bg-[#16A34A] text-white" : "bg-[#111827] text-white"}`}>
{copiedCred ? <><Check className="h-3 w-3" /> Copied</> : <><Copy className="h-3 w-3" /> Copy</>}
</button>
<button onClick={() => {
const t = `Login for ${orgName}:\nEmail: ${inviteResult.email}\nPassword: ${inviteResult.tempPassword}\nLogin: ${window.location.origin}/login`
window.open(`https://wa.me/?text=${encodeURIComponent(t)}`, "_blank")
}} className="bg-[#25D366] py-2 text-[10px] font-bold text-white flex items-center justify-center gap-1">
<MessageCircle className="h-3 w-3" /> WhatsApp
</button>
</div>
<button onClick={() => { setInviteResult(null); setShowInvite(false) }} className="text-[10px] text-gray-400 hover:text-gray-600">Done</button>
</div>
)}
{/* Member list */}
{team.length > 0 && (
<div className="divide-y divide-gray-50">
{team.map(m => {
const r = ROLE_META[m.role] || ROLE_META.staff
const isMe = m.id === currentUser?.id
return (
<div key={m.id} className="py-2.5 flex items-center gap-2.5">
<div className={`w-6 h-6 flex items-center justify-center shrink-0 ${r.bg}`}>
<r.icon className={`h-3 w-3 ${r.color}`} />
</div>
<div className="flex-1 min-w-0">
<p className="text-xs font-medium text-[#111827] truncate">
{m.name || m.email.split("@")[0]}
{isMe && <span className="text-[8px] text-gray-400 ml-1">you</span>}
</p>
</div>
{isAdmin && !isMe ? (
<>
<select value={m.role} onChange={e => changeRole(m.id, e.target.value)} className="text-[9px] font-bold border border-gray-200 px-1.5 py-1 bg-white">
{Object.entries(ROLE_META).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
</select>
<button onClick={() => removeMember(m.id)} className="text-gray-300 hover:text-[#DC2626] transition-colors"><Trash2 className="h-3 w-3" /></button>
</>
) : (
<span className={`text-[9px] font-bold px-1.5 py-0.5 ${r.bg} ${r.color}`}>{r.label}</span>
)}
</div>
)
})}
</div>
)}
</div>
</div>
)}
</div>
)
}
// ─── Reusable pieces ─────────────────────────────────────────
function Field({ label, value, onChange, placeholder, type = "text", maxLength }: {
label: string; value: string; onChange: (v: string) => void
placeholder?: string; type?: string; maxLength?: number
}) {
return (
<div>
<label className="text-[10px] font-bold text-gray-500 uppercase tracking-wide block mb-1.5">{label}</label>
<input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} maxLength={maxLength}
className="w-full h-10 px-3 border-2 border-gray-200 text-sm placeholder:text-gray-300 focus:border-[#1E40AF] outline-none transition-colors" />
</div>
)
}
function SaveRow({ section, saving, saved, onSave, onCancel }: {
section: string; saving: string | null; saved: string | null
onSave: () => void; onCancel: () => void
}) {
const isSaving = saving === section
const isSaved = saved === section
return (
<div className="flex items-center gap-2 pt-2">
<button onClick={onSave} disabled={isSaving} className={`px-4 py-2 text-xs font-bold transition-all flex items-center gap-1.5 ${isSaved ? "bg-[#16A34A] text-white" : "bg-[#111827] text-white hover:bg-gray-800 disabled:opacity-50"}`}>
{isSaving ? <><Loader2 className="h-3 w-3 animate-spin" /> Saving</> : isSaved ? <><Check className="h-3 w-3" /> Saved</> : "Save"}
</button>
{!isSaved && <button onClick={onCancel} className="px-3 py-2 text-xs text-gray-400 hover:text-gray-600">Cancel</button>}
</div>
)
}