{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "nonprofit-donate",
  "title": "Nonprofit: Donate page",
  "description": "The donate flow in one centred column: where the gift goes (a project chosen on its page, the appeal with the gift in its bar, or where it is needed most once the appeal has closed), one-off or monthly, an amount or a typed one, your details, a generic tax-relief box that asks for an address only when ticked, your gift as rows and Continue to payment, with a confirmation that names where it goes.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://eased.dev/r/eased-tokens.json",
    "https://eased.dev/r/eased-motion.json",
    "https://eased.dev/r/nonprofit-core.json",
    "https://eased.dev/r/template-core.json",
    "https://eased.dev/r/segmented.json",
    "https://eased.dev/r/number-roll.json",
    "https://eased.dev/r/text-swap.json",
    "https://eased.dev/r/button.json",
    "https://eased.dev/r/checkbox.json",
    "https://eased.dev/r/field.json",
    "https://eased.dev/r/input.json",
    "https://eased.dev/r/nonprofit-projects.json"
  ],
  "files": [
    {
      "path": "src/registry/eased/templates/nonprofit/donate.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useEffect, useRef, useState, type FormEvent, type ReactNode, type RefObject } from \"react\";\nimport { Button } from \"../../button/button\";\nimport { Checkbox } from \"../../checkbox/checkbox\";\nimport { Field } from \"../../field/field\";\nimport { Input } from \"../../input/input\";\nimport { enter, exitFast, reducedFade, useSafeReducedMotion } from \"../../lib/motion\";\nimport { NumberRoll } from \"../../number-roll/number-roll\";\nimport { Segmented } from \"../../segmented/segmented\";\nimport { TextSwap } from \"../../text-swap/text-swap\";\nimport { Faq } from \"../_shared/faq\";\nimport { demoSubmit, EMAIL, type SubmitHandler } from \"../_shared/send\";\nimport { AppealBar, appealWith, useAppealTime } from \"./appeal\";\nimport { appeal, donatePage, formatMoney, frequencies, giving, hero, locale, money, projects, projectsPage } from \"./content\";\nimport { amountOf, useGift, type Gift } from \"./gift\";\nimport { countOf, parseAmount, unitsFor, yearly } from \"./giving\";\nimport { COLUMN, PageHead } from \"./kit\";\nimport { fundedOf } from \"./projects\";\n\n/** What \"Continue to payment\" hands on: the gift and the details, never a card or bank detail. */\nexport type DonationValues = Gift & { first: string; last: string; email: string; relief: boolean; address: string; postcode: string; updates: boolean };\n\ntype FieldName = \"first\" | \"last\" | \"email\" | \"address\" | \"postcode\";\n\n/**\n * The donate page: the amount (how often, a preset or a typed amount, with what it gives rolling\n * under it), your details, a generic tax-relief box that asks for a home address only when it is\n * ticked, and \"Continue to payment\", where your payment provider would take over. The gift chosen\n * on the home page is already here (sessionStorage, restored before it is shown, nothing rolls);\n * every change here is kept the same way. One centred column: the appeal the gift goes to at the\n * head, the three steps, then your gift as rows above a full-width button, and questions under it.\n *\n * Nothing leaves the page until you pass `onContinue` (README, \"Before you ship\").\n */\nexport function Donate({ onContinue = demoSubmit }: { onContinue?: SubmitHandler<DonationValues> }) {\n  const { gift, chosen, live, choose } = useGift();\n  const { closed } = useAppealTime();\n  const [values, setValues] = useState({ first: \"\", last: \"\", email: \"\", address: \"\", postcode: \"\" });\n  const [relief, setRelief] = useState(false);\n  const [updates, setUpdates] = useState(false);\n  const [errors, setErrors] = useState<Partial<Record<FieldName, string>>>({});\n  const [state, setState] = useState<\"idle\" | \"pending\" | \"ready\">(\"idle\");\n  const ready = useRef<HTMLDivElement>(null);\n\n  const set = (name: FieldName) => (value: string) => {\n    setValues((v) => ({ ...v, [name]: value }));\n    if (errors[name]) setErrors((e) => ({ ...e, [name]: undefined }));\n  };\n\n  const submit = async (e: FormEvent) => {\n    e.preventDefault();\n    if (state === \"pending\") return;\n    const f = donatePage.fields;\n    const found: Partial<Record<FieldName, string>> = {};\n    if (!values.first.trim()) found.first = f.first.required;\n    if (!values.last.trim()) found.last = f.last.required;\n    if (!values.email.trim()) found.email = f.email.required;\n    else if (!EMAIL.test(values.email.trim())) found.email = f.email.invalid;\n    if (relief && !values.address.trim()) found.address = f.address.required;\n    if (relief && !values.postcode.trim()) found.postcode = f.postcode.required;\n    setErrors(found);\n    const first = (Object.keys(found) as FieldName[])[0];\n    if (first) {\n      document.getElementById(`donate-${first}`)?.focus();\n      return;\n    }\n    setState(\"pending\");\n    try {\n      await onContinue({ ...gift, ...values, relief, updates });\n      setState(\"ready\");\n    } catch {\n      setState(\"idle\");\n    }\n  };\n\n  useEffect(() => {\n    if (state === \"ready\") ready.current?.focus();\n  }, [state]);\n\n  return (\n    <div className={`${COLUMN} pt-pad-xl pb-section`}>\n      <div className=\"mx-auto flex w-full max-w-2xl min-w-0 flex-col gap-group\">\n        <PageHead label={donatePage.label} title={donatePage.title} lead={donatePage.lead}>\n          {chosen && <p className=\"nf-rise text-ui-sm text-text-muted [--i:3]\">{donatePage.restored}</p>}\n        </PageHead>\n        <AppealCard gift={gift} live={live} choose={choose} />\n        {state === \"ready\" ? (\n          <Ready panel={ready} to={donatePage.next.to(`${formatMoney(amountOf(gift))} ${donatePage.summary.per[gift.frequency]}`, destination(gift, closed))} onBack={() => setState(\"idle\")} />\n        ) : (\n          <form noValidate onSubmit={submit} aria-label={donatePage.label} className=\"nf-rise flex flex-col gap-group [--i:3]\">\n            <Step n={1} title={donatePage.steps.amount}>\n              <Amount gift={gift} live={live} choose={choose} />\n            </Step>\n            <Step n={2} title={donatePage.steps.details}>\n              <div className=\"grid gap-pad-md sm:grid-cols-2\">\n                <Text name=\"first\" value={values.first} error={errors.first} onChange={set(\"first\")} autoComplete=\"given-name\" />\n                <Text name=\"last\" value={values.last} error={errors.last} onChange={set(\"last\")} autoComplete=\"family-name\" />\n                <Text name=\"email\" value={values.email} error={errors.email} onChange={set(\"email\")} autoComplete=\"email\" type=\"email\" className=\"sm:col-span-2\" />\n              </div>\n            </Step>\n            <Step n={3} title={donatePage.steps.relief}>\n              <div className=\"flex flex-col gap-pad-md\">\n                <Checkbox checked={relief} onCheckedChange={setRelief} description={donatePage.relief.description}>\n                  {donatePage.relief.label}\n                </Checkbox>\n                <AnimatePresence initial={false}>\n                  {relief && (\n                    <motion.div\n                      key=\"address\"\n                      initial={{ opacity: 0, y: -4 }}\n                      animate={{ opacity: 1, y: 0, transition: enter }}\n                      exit={{ opacity: 0, transition: exitFast }}\n                      className=\"grid gap-pad-md sm:grid-cols-[2fr_1fr]\"\n                    >\n                      <Text name=\"address\" value={values.address} error={errors.address} onChange={set(\"address\")} autoComplete=\"street-address\" />\n                      <Text name=\"postcode\" value={values.postcode} error={errors.postcode} onChange={set(\"postcode\")} autoComplete=\"postal-code\" />\n                    </motion.div>\n                  )}\n                </AnimatePresence>\n                <Checkbox checked={updates} onCheckedChange={setUpdates} description={donatePage.updates.description}>\n                  {donatePage.updates.label}\n                </Checkbox>\n              </div>\n            </Step>\n            <div className=\"flex flex-col gap-pad-md border-t border-line-subtle pt-pad-md\">\n              <Summary gift={gift} live={live} relief={relief} />\n              <Button type=\"submit\" variant=\"primary\" size=\"lg\" loading={state === \"pending\"} className=\"h-12! w-full\">\n                {donatePage.submit}\n              </Button>\n            </div>\n          </form>\n        )}\n        <Faq items={donatePage.faq} className=\"border-t border-line-subtle\" itemClassName=\"[&_button]:min-h-11 [&_button]:text-ui-md\" />\n      </div>\n    </div>\n  );\n}\n\n/** One numbered step of the form, its title the fieldset's legend. */\nfunction Step({ n, title, children }: { n: number; title: string; children: ReactNode }) {\n  return (\n    <fieldset className=\"flex min-w-0 flex-col gap-pad-md\">\n      <legend className=\"mb-pad-md flex items-baseline gap-2.5 font-display text-display-2xl font-semibold tracking-display text-text\">\n        <span className=\"text-brand-text tabular-nums\">{n}</span>\n        {title}\n      </legend>\n      {children}\n    </fieldset>\n  );\n}\n\n/** A labelled text field with its error. */\nfunction Text({\n  name,\n  value,\n  error,\n  onChange,\n  autoComplete,\n  type = \"text\",\n  className = \"\",\n}: {\n  name: FieldName;\n  value: string;\n  error?: string;\n  onChange: (v: string) => void;\n  autoComplete: string;\n  type?: \"text\" | \"email\";\n  className?: string;\n}) {\n  const f = donatePage.fields[name];\n  return (\n    <Field label={f.label} error={error} className={className}>\n      <Input\n        id={`donate-${name}`}\n        type={type}\n        value={value}\n        onChange={(e) => onChange(e.target.value)}\n        autoComplete={autoComplete}\n        aria-required\n        placeholder={\"placeholder\" in f ? f.placeholder : undefined}\n        size=\"lg\"\n        className=\"max-sm:h-11\"\n      />\n    </Field>\n  );\n}\n\n/**\n * The amount: how often, the four amounts for it, or a typed one in whole pounds. What the gift\n * gives rolls under it. Every change is kept for the visit.\n */\nfunction Amount({ gift, live, choose }: { gift: Gift; live: boolean; choose: (p: Partial<Gift>) => void }) {\n  const f = gift.frequency;\n  const range = f === \"monthly\" ? giving.monthly : giving.once;\n  const amount = amountOf(gift);\n  const [text, setText] = useState<string | null>(null);\n  const [error, setError] = useState<string | null>(null);\n  const invalid = error !== null;\n  const setAmount = (n: number) => choose(f === \"monthly\" ? { monthly: n } : { once: n });\n  const typed = (value: string) => {\n    setText(value);\n    const n = parseAmount(value);\n    if (value.trim() === \"\") return setError(null);\n    if (n === null || n < giving.typed.min) return setError(hero.otherInvalid(formatMoney(giving.typed.min)));\n    if (n > giving.typed.max) return setError(hero.otherTooMuch(formatMoney(giving.typed.max)));\n    setError(null);\n    setAmount(n);\n  };\n  const n = unitsFor(amount, f, giving.unit);\n  return (\n    <div className=\"flex flex-col gap-pad-md\">\n      <Segmented\n        options={frequencies}\n        value={f}\n        onValueChange={(v) => {\n          setText(null);\n          setError(null);\n          choose({ frequency: v });\n        }}\n        size=\"md\"\n        aria-label={hero.frequencyLabel}\n        className=\"max-sm:h-12 max-sm:w-full max-sm:[&>button]:min-h-11 max-sm:[&>button]:flex-1 sm:self-start\"\n      />\n      <div className=\"grid gap-pad-sm sm:grid-cols-[auto_minmax(0,14rem)] sm:items-start\">\n        <div role=\"group\" aria-label={hero.presetsLabel} className=\"grid grid-cols-4 gap-1.5\">\n          {range.presets.map((p, i) => (\n            <Button\n              key={i}\n              variant=\"secondary\"\n              size=\"lg\"\n              aria-pressed={p === amount}\n              onClick={() => {\n                setText(null);\n                setError(null);\n                setAmount(p);\n              }}\n              className=\"tabular-nums max-sm:h-11 aria-pressed:bg-text aria-pressed:text-bg hover-fine:aria-pressed:bg-text\"\n            >\n              {formatMoney(p)}\n            </Button>\n          ))}\n        </div>\n        <Field error={error ?? undefined}>\n          <Input\n            aria-label={hero.other}\n            inputMode=\"numeric\"\n            start=\"£\"\n            value={text ?? String(amount)}\n            onChange={(e) => typed(e.target.value)}\n            onBlur={() => !invalid && setText(null)}\n            size=\"lg\"\n            className=\"max-sm:h-11\"\n            data-nf-restore=\"\"\n          />\n        </Field>\n      </div>\n      <p data-nf-restore=\"\" className=\"text-ui-lg text-pretty text-text\">\n        {n > 0 ? (\n          <>\n            {formatMoney(amount)}\n            {hero.per[f]} {hero.gives}{\" \"}\n            <span className=\"font-semibold text-brand-text\">\n              <NumberRoll value={n} animated={live} locale={locale} className=\"tabular-nums\" /> <TextSwap>{n === 1 ? giving.unit.one : giving.unit.many}</TextSwap>\n            </span>{\" \"}\n            {f === \"monthly\" ? hero.what.monthly : hero.what.once}\n          </>\n        ) : (\n          `${formatMoney(amount)}${hero.per[f]} ${hero.toward(formatMoney(giving.unit.cost - (yearly(amount, f) % giving.unit.cost)), f === \"monthly\")}`\n        )}\n      </p>\n    </div>\n  );\n}\n\n/** Where the gift goes, as words for the confirmation: the project, the appeal, or (once it has closed) where it is needed most. */\nfunction destination(gift: Gift, closed: boolean) {\n  const project = projects.find((p) => p.slug === gift.project);\n  return project ? project.name.charAt(0).toLowerCase() + project.name.slice(1) : closed ? appeal.general.toLowerCase() : `the ${appeal.name.toLowerCase()}`;\n}\n\n/**\n * Where the gift goes, at the head of the page. A gift from a project's page goes to that\n * project, shown with its funding and a way back to the appeal; otherwise the appeal, with its\n * families funded, days left and the bar with the gift in it; once the appeal has closed, a line\n * on where gifts go instead.\n */\nfunction AppealCard({ gift, live, choose }: { gift: Gift; live: boolean; choose: (p: Partial<Gift>) => void }) {\n  const added = yearly(amountOf(gift), gift.frequency);\n  const { before, after } = appealWith(added);\n  const time = useAppealTime();\n  const project = projects.find((p) => p.slug === gift.project);\n  const card = \"nf-rise flex flex-col gap-pad-sm rounded-surface border border-line-subtle bg-surface p-pad-md [--i:3]\";\n  if (project) {\n    const pct = fundedOf(project);\n    return (\n      <div data-nf-restore=\"\" className={card}>\n        <p className=\"text-ui-sm text-text-muted\">{donatePage.project.label}</p>\n        <p className=\"text-ui-lg font-semibold text-text\">{project.name}</p>\n        <span aria-hidden className=\"relative block h-2.5 overflow-hidden rounded-pill bg-surface-sunken inset-shadow-well\">\n          <span className=\"absolute inset-y-0 left-0 w-full origin-left rounded-pill bg-(--nf-sea)\" style={{ transform: `scaleX(${pct / 100})` }} />\n        </span>\n        <div className=\"flex flex-wrap items-center justify-between gap-x-pad-base\">\n          <p className=\"text-ui text-text-secondary tabular-nums\">{projectsPage.raised(formatMoney(project.raised), formatMoney(project.target))}</p>\n          <Button variant=\"ghost\" size=\"md\" edge=\"end\" hitArea onClick={() => choose({ project: null })}>\n            {donatePage.project.instead}\n          </Button>\n        </div>\n      </div>\n    );\n  }\n  if (time.closed) {\n    return (\n      <div className={card}>\n        <p className=\"text-ui-md font-medium text-text\">{appeal.general}</p>\n        <p className=\"text-ui text-pretty text-text-secondary\">{appeal.after}</p>\n      </div>\n    );\n  }\n  return (\n    <div data-nf-restore=\"\" className={card}>\n      <div className=\"flex flex-wrap items-baseline justify-between gap-x-pad-base gap-y-1\">\n        <p className=\"text-ui-md font-medium text-text\">{donatePage.summary.appeal(appeal.name)}</p>\n        <p className=\"text-ui-sm text-text-muted\">{time.text}</p>\n      </div>\n      <AppealBar added={added} instant={!live} className=\"h-2.5 rounded-pill\" trackClassName=\"bg-surface-sunken inset-shadow-well\" />\n      <p className=\"text-ui text-text-secondary tabular-nums\">\n        <span className=\"font-medium text-text\">{before}</span> {appeal.of(appeal.target)} {appeal.families} · {hero.withGift}{\" \"}\n        <NumberRoll value={after} animated={live} locale={locale} className=\"font-medium text-text\" />\n      </p>\n    </div>\n  );\n}\n\n/** Your gift, as rows above the button: the gift, what it gives, and what tax relief adds when it is ticked. */\nfunction Summary({ gift, live, relief }: { gift: Gift; live: boolean; relief: boolean }) {\n  const f = gift.frequency;\n  const amount = amountOf(gift);\n  const n = unitsFor(amount, f, giving.unit);\n  const extra = new Intl.NumberFormat(locale, { style: \"currency\", currency: \"GBP\" }).format(amount * donatePage.relief.rate);\n  const rows = [\n    { label: donatePage.summary.rows.gift, value: <><NumberRoll value={amount} format={money} locale={locale} animated={live} /> {donatePage.summary.per[f]}</> },\n    { label: donatePage.summary.rows.gives, value: n > 0 ? countOf(n, giving.unit) : donatePage.summary.toward },\n    ...(relief ? [{ label: donatePage.summary.rows.relief, value: extra }] : []),\n  ];\n  return (\n    <div className=\"flex flex-col gap-pad-xs\">\n      <h2 className=\"text-ui-md font-semibold text-text\">{donatePage.summary.label}</h2>\n      <dl data-nf-restore=\"\" className=\"flex flex-col\">\n        {rows.map((r) => (\n          <div key={r.label} className=\"flex items-baseline justify-between gap-pad-base py-1.5 text-ui-md\">\n            <dt className=\"text-text-secondary\">{r.label}</dt>\n            <dd className=\"text-right text-text tabular-nums\">{r.value}</dd>\n          </div>\n        ))}\n      </dl>\n    </div>\n  );\n}\n\n/** After \"Continue to payment\": where the provider takes over. Takes focus so it is read. */\nfunction Ready({ panel, to, onBack }: { panel: RefObject<HTMLDivElement | null>; to: string; onBack: () => void }) {\n  const reduced = useSafeReducedMotion();\n  return (\n    <motion.div\n      ref={panel}\n      tabIndex={-1}\n      role=\"status\"\n      initial={reduced ? { opacity: 0 } : { opacity: 0, y: 8 }}\n      animate={{ opacity: 1, y: 0 }}\n      transition={reduced ? reducedFade : enter}\n      className=\"flex flex-col items-start gap-pad-md rounded-surface border border-line-subtle p-pad-md outline-none sm:p-pad-lg\"\n    >\n      <h2 className=\"font-display text-display-4xl font-semibold tracking-display text-text\">{donatePage.next.title}</h2>\n      <p className=\"text-ui-lg text-text\">{to}</p>\n      <p className=\"max-w-lg text-ui-md text-pretty text-text-secondary\">{donatePage.next.body}</p>\n      <Button variant=\"secondary\" size=\"lg\" onClick={onBack}>\n        {donatePage.next.back}\n      </Button>\n    </motion.div>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/eased/templates/nonprofit/donate.tsx"
    }
  ],
  "meta": {
    "template": "nonprofit",
    "kind": "template-section",
    "industries": [
      "health"
    ]
  },
  "type": "registry:block"
}