@lockerverse/react 0.2.100 → 0.2.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"auctions.js","names":[],"sources":["../src/lockerverse-auctions.tsx","../src/use-lockerverse-auctions.ts"],"sourcesContent":["import type {\n LockerverseAuction,\n LockerverseAuctionItem,\n LockerverseAuctionStatus,\n} from \"@lockerverse/sdk/auctions\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { formatMoney } from \"./format-money.ts\";\nimport type { LockerverseStyle, LockerverseTheme } from \"./theme.ts\";\nimport type { UseLockerverseAuctionsResult } from \"./use-lockerverse-auctions.ts\";\n\nexport type LockerverseAuctionsProps = {\n auctions: UseLockerverseAuctionsResult;\n onSelectItem: (\n auction: LockerverseAuction,\n item: LockerverseAuctionItem\n ) => void;\n theme?: LockerverseTheme;\n style?: LockerverseStyle;\n className?: string;\n};\n\nconst STATUS_LABELS = {\n active: \"Live now\",\n draft: \"Coming soon\",\n finished: \"Closed\",\n} satisfies Record<LockerverseAuctionStatus, string>;\nconst dateFormatter = new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n timeZone: \"UTC\",\n});\n\nfunction AuctionTiming({ auction }: { auction: LockerverseAuction }) {\n const boundary = auction.status === \"draft\" ? auction.startAt : auction.endAt;\n const date = new Date(boundary);\n if (!Number.isFinite(date.getTime())) {\n return null;\n }\n const label = { active: \"Ends\", draft: \"Opens\", finished: \"Ended\" }[\n auction.status\n ];\n return (\n <span className=\"lockerverse-auctions__meta\">\n {label} <time dateTime={boundary}>{dateFormatter.format(date)} UTC</time>\n </span>\n );\n}\n\nfunction CatalogImage({ src }: { src: string | null | undefined }) {\n return src ? (\n <img\n alt=\"\"\n className=\"lockerverse-auctions__image\"\n height={250}\n loading=\"lazy\"\n src={src}\n width={320}\n />\n ) : null;\n}\n\nfunction AuctionCard({\n auction,\n onSelect,\n}: {\n auction: LockerverseAuction;\n onSelect: () => void;\n}) {\n return (\n <article className=\"lockerverse-auctions__card\">\n <CatalogImage\n src={\n auction.configuration.image ??\n auction.items.find((item) => item.image)?.image\n }\n />\n <div className=\"lockerverse-auctions__body\">\n <span className=\"lockerverse-auctions__meta\">\n {STATUS_LABELS[auction.status]} · {auction.items.length}{\" \"}\n {auction.items.length === 1 ? \"item\" : \"items\"}\n </span>\n <h3>{auction.name}</h3>\n <AuctionTiming auction={auction} />\n <button\n aria-label={`View items in ${auction.name}`}\n onClick={onSelect}\n type=\"button\"\n >\n View items\n </button>\n </div>\n </article>\n );\n}\n\nfunction ItemCard({\n auction,\n item,\n onSelect,\n}: {\n auction: LockerverseAuction;\n item: LockerverseAuctionItem;\n onSelect: () => void;\n}) {\n const status = auction.status === \"active\" ? item.status : auction.status;\n const canBuyNow = item.saleMode !== \"auction\";\n const canBid = item.saleMode !== \"buy_now\";\n return (\n <article className=\"lockerverse-auctions__card\">\n <CatalogImage\n src={item.image ?? item.images[0] ?? auction.configuration.image}\n />\n <div className=\"lockerverse-auctions__body\">\n <span className=\"lockerverse-auctions__meta\">\n {canBuyNow && item.isSoldOut ? \"Sold out\" : STATUS_LABELS[status]}\n </span>\n <h3>{item.name}</h3>\n <dl className=\"lockerverse-auctions__metrics\">\n {canBid ? (\n <div>\n <dt>\n {item.maxBidAmount === null ? \"Starting bid\" : \"Current bid\"}\n </dt>\n <dd>\n {formatMoney(item.maxBidAmount ?? item.minBidAmount ?? 0)}\n </dd>\n </div>\n ) : null}\n {canBuyNow && item.buyNowPriceAmount !== null ? (\n <div>\n <dt>Buy now</dt>\n <dd>{formatMoney(item.buyNowPriceAmount)}</dd>\n </div>\n ) : null}\n {canBuyNow && item.availableQuantity !== null ? (\n <div>\n <dt>Available</dt>\n <dd>{item.availableQuantity}</dd>\n </div>\n ) : null}\n </dl>\n <button\n aria-label={`View ${item.name}`}\n onClick={onSelect}\n type=\"button\"\n >\n View item\n </button>\n </div>\n </article>\n );\n}\n\n/** Optional catalog UI. Use onSelectItem to open your item view or LockerverseAuctionItem. */\nexport function LockerverseAuctions({\n auctions,\n onSelectItem,\n theme = \"dark\",\n style,\n className,\n}: LockerverseAuctionsProps) {\n const [selectedId, setSelectedId] = useState<string | null>(null);\n const headingRef = useRef<HTMLHeadingElement>(null);\n const previousId = useRef(selectedId);\n const selected = auctions.auctions?.find(\n (auction) => auction.id === selectedId\n );\n useEffect(() => {\n if (previousId.current !== selectedId) {\n headingRef.current?.focus();\n previousId.current = selectedId;\n }\n }, [selectedId]);\n return (\n <section\n aria-busy={auctions.loading}\n aria-label=\"Auctions\"\n className={[\"lockerverse-auctions\", className].filter(Boolean).join(\" \")}\n data-lockerverse-theme={theme}\n style={style}\n >\n <header className=\"lockerverse-auctions__header\">\n {selected ? (\n <button\n className=\"lockerverse-auctions__back\"\n onClick={() => setSelectedId(null)}\n type=\"button\"\n >\n Back to auctions\n </button>\n ) : null}\n <h2 ref={headingRef} tabIndex={-1}>\n {selected?.name ?? \"Auctions\"}\n </h2>\n {selected?.description ? <p>{selected.description}</p> : null}\n {selected ? <AuctionTiming auction={selected} /> : null}\n </header>\n {auctions.loading ? <p role=\"status\">Loading auctions…</p> : null}\n {auctions.error ? (\n <div role=\"alert\">\n <p>{auctions.error.message}</p>\n <button onClick={auctions.refresh} type=\"button\">\n Try again\n </button>\n </div>\n ) : null}\n {selected && selected.items.length === 0 ? (\n <p>No items are available in this auction.</p>\n ) : null}\n {selected && selected.items.length > 0 ? (\n <ul className=\"lockerverse-auctions__grid\">\n {selected.items.map((item) => (\n <li key={item.id}>\n <ItemCard\n auction={selected}\n item={item}\n onSelect={() => onSelectItem(selected, item)}\n />\n </li>\n ))}\n </ul>\n ) : null}\n {!selected && auctions.auctions?.length === 0 ? (\n <p>No auctions are available.</p>\n ) : null}\n {!selected && auctions.auctions && auctions.auctions.length > 0 ? (\n <ul className=\"lockerverse-auctions__grid\">\n {auctions.auctions.map((auction) => (\n <li key={auction.id}>\n <AuctionCard\n auction={auction}\n onSelect={() => setSelectedId(auction.id)}\n />\n </li>\n ))}\n </ul>\n ) : null}\n </section>\n );\n}\n","import {\n type CreateLockerverseAuctionOptions,\n createLockerverseAuctionClient,\n type LockerverseAuction,\n type LockerverseAuctionClient,\n type LockerverseSdkError,\n} from \"@lockerverse/sdk/auctions\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useImmutableResourceIdentity } from \"./immutable-resource-identity.ts\";\n\nexport type UseLockerverseAuctionsResult = {\n client: LockerverseAuctionClient;\n auctions: LockerverseAuction[] | null;\n loading: boolean;\n error: LockerverseSdkError | null;\n refresh: () => void;\n};\n\ntype AuctionLoadState = Pick<\n UseLockerverseAuctionsResult,\n \"auctions\" | \"error\"\n>;\n\nexport function useLockerverseAuctions(\n options: CreateLockerverseAuctionOptions\n): UseLockerverseAuctionsResult {\n useImmutableResourceIdentity(\"auctions\", {\n apiBaseUrl: options.apiBaseUrl,\n communitySlug: options.communitySlug,\n environment: options.environment,\n slug: \"\",\n });\n const onErrorRef = useRef(options.onError);\n onErrorRef.current = options.onError;\n const [client] = useState(() =>\n createLockerverseAuctionClient({\n ...options,\n onError: (error) => onErrorRef.current?.(error),\n })\n );\n const [revision, setRevision] = useState(0);\n const [state, setState] = useState<AuctionLoadState>({\n auctions: null,\n error: null,\n });\n useEffect(() => {\n let active = true;\n client.list().then(\n (auctions) => {\n if (active) {\n setState({ auctions, error: null });\n }\n },\n (error: LockerverseSdkError) => {\n if (active) {\n setState({ auctions: null, error });\n }\n }\n );\n return () => {\n active = false;\n };\n }, [client, revision]);\n const refresh = useCallback(() => {\n setState({ auctions: null, error: null });\n setRevision((value) => value + 1);\n }, []);\n return {\n ...state,\n client,\n loading: state.auctions === null && state.error === null,\n refresh,\n };\n}\n"],"mappings":"gSAqBA,MAAM,EAAgB,CACpB,OAAQ,WACR,MAAO,cACP,SAAU,QACZ,EACM,EAAgB,IAAI,KAAK,eAAe,QAAS,CACrD,UAAW,SACX,UAAW,QACX,SA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,SACF,CACF"}
1
+ {"version":3,"file":"auctions.js","names":["Icon","formatMoney"],"sources":["../src/lockerverse-auctions.tsx","../src/use-lockerverse-auctions.ts"],"sourcesContent":["import type {\n LockerverseAuction,\n LockerverseAuctionItem,\n LockerverseAuctionStatus,\n} from \"@lockerverse/sdk/auctions\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { AuctionDescription } from \"./auction-description.tsx\";\nimport {\n formatAuctionBoundary,\n formatAuctionMoney as formatMoney,\n getAuctionDisplayStatus,\n} from \"./auction-display.ts\";\nimport { AuctionIcon as Icon } from \"./auction-icons.tsx\";\nimport type { LockerverseStyle, LockerverseTheme } from \"./theme.ts\";\nimport type { UseLockerverseAuctionsResult } from \"./use-lockerverse-auctions.ts\";\n\nexport type LockerverseAuctionsProps = {\n auctions: UseLockerverseAuctionsResult;\n onSelectItem: (\n auction: LockerverseAuction,\n item: LockerverseAuctionItem\n ) => void;\n theme?: LockerverseTheme;\n style?: LockerverseStyle;\n className?: string;\n};\nconst STATUS_LABELS = {\n active: \"Live now\",\n draft: \"Coming soon\",\n finished: \"Closed\",\n} satisfies Record<LockerverseAuctionStatus, string>;\nconst FILTERS = [\n { label: \"All\", value: \"all\" },\n { label: \"Live\", value: \"active\" },\n { label: \"Upcoming\", value: \"draft\" },\n { label: \"Closed\", value: \"finished\" },\n] as const;\ntype ItemFilter = (typeof FILTERS)[number][\"value\"];\n\nfunction CatalogImage({\n images,\n fallback,\n name,\n}: {\n images?: string[];\n fallback?: string | null | undefined;\n name: string;\n}) {\n const photos = [...new Set(images?.filter(Boolean))];\n if (!photos.length && fallback) {\n photos.push(fallback);\n }\n const [index, setIndex] = useState(0);\n const imageRef = useRef<HTMLDivElement>(null);\n const loaded = useRef(new Set<string>());\n const count = photos.length;\n const current = count ? index % count : 0;\n useEffect(() => {\n if (count < 2) {\n return;\n }\n const motion = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n const timer = window.setInterval(() => {\n if (\n document.hidden ||\n motion.matches ||\n imageRef.current?.closest(\"article\")?.matches(\":hover, :focus-within\")\n ) {\n return;\n }\n setIndex((previous) =>\n loaded.current.has(photos[(previous + 1) % count] ?? \"\")\n ? (previous + 1) % count\n : previous\n );\n }, 5000);\n return () => window.clearInterval(timer);\n }, [count, photos]);\n return (\n <div className=\"lockerverse-auctions__catalog-images\" ref={imageRef}>\n {count\n ? [current, ...(count > 1 ? [(current + 1) % count] : [])].map(\n (photo) => (\n <img\n alt={photo === current ? name : \"\"}\n aria-hidden={photo !== current}\n className=\"lockerverse-auctions__catalog-photo\"\n data-visible={photo === current}\n height={500}\n key={photos[photo]}\n loading=\"lazy\"\n onLoad={() => loaded.current.add(photos[photo] ?? \"\")}\n src={photos[photo]}\n width={640}\n />\n )\n )\n : null}\n </div>\n );\n}\nfunction Metric({\n icon,\n label,\n value,\n}: {\n icon: \"items\" | \"gavel\" | \"clock\" | \"bag\";\n label: string;\n value: string;\n}) {\n return (\n <div className=\"lockerverse-auctions__catalog-metric\">\n <dt>\n <Icon kind={icon} />\n {label}\n </dt>\n <dd>{value}</dd>\n </div>\n );\n}\nfunction Timing({\n auction,\n status = getAuctionDisplayStatus(auction),\n item = false,\n}: {\n auction: LockerverseAuction;\n status?: LockerverseAuctionStatus;\n item?: boolean;\n}) {\n let label = \"\";\n if (status === \"draft\") {\n label = \"Opens \";\n }\n if (status === \"active\") {\n label = item ? \"Closes \" : \"Ends \";\n }\n return (\n <span className=\"lockerverse-auctions__catalog-timing\">\n {label}\n {formatAuctionBoundary(auction, status)}\n </span>\n );\n}\nfunction AuctionCard({\n auction,\n onSelect,\n}: {\n auction: LockerverseAuction;\n onSelect: () => void;\n}) {\n const fallback =\n auction.configuration.image ||\n auction.items.find((item) => item.image || item.images.length)?.image ||\n auction.items.find((item) => item.images.length)?.images[0] ||\n auction.community?.banner ||\n auction.community?.thumbnail;\n const description =\n auction.description ||\n {\n active: \"Bidding is open across this auction's items.\",\n draft: \"Preview the lineup before bidding opens.\",\n finished: \"Bidding has wrapped. Review the completed items.\",\n }[getAuctionDisplayStatus(auction)];\n return (\n <article className=\"lockerverse-auctions__catalog-card\">\n <button\n aria-label={`View items in ${auction.name}`}\n className=\"lockerverse-auctions__catalog-select\"\n onClick={onSelect}\n type=\"button\"\n />\n <div className=\"lockerverse-auctions__catalog-media\">\n <CatalogImage fallback={fallback} name={auction.name} />\n <div className=\"lockerverse-auctions__catalog-chips\">\n <span className=\"lockerverse-auctions__catalog-chip\">\n {STATUS_LABELS[getAuctionDisplayStatus(auction)]}\n </span>\n <Timing auction={auction} />\n </div>\n <dl className=\"lockerverse-auctions__catalog-metrics\">\n <Metric\n icon=\"items\"\n label=\"Items\"\n value={String(auction.items.length)}\n />\n <Metric\n icon=\"gavel\"\n label=\"Bids\"\n value={String(\n auction.items.reduce((sum, item) => sum + item.bidCount, 0)\n )}\n />\n </dl>\n </div>\n <div className=\"lockerverse-auctions__catalog-body\">\n <h3>{auction.name}</h3>\n <AuctionDescription\n className=\"lockerverse-auctions__catalog-description\"\n description={description}\n links={false}\n />\n <div className=\"lockerverse-auctions__catalog-footer\">\n <span className=\"lockerverse-auctions__catalog-cta\">\n {getAuctionDisplayStatus(auction) === \"draft\"\n ? \"Preview items\"\n : \"View items\"}\n </span>\n <span className=\"lockerverse-auctions__catalog-arrow\">\n <Icon kind=\"arrow\" />\n </span>\n </div>\n </div>\n </article>\n );\n}\nfunction itemCardDisplay(\n item: LockerverseAuctionItem,\n status: LockerverseAuctionStatus\n) {\n if (item.saleMode === \"buy_now\") {\n const label = item.isSoldOut ? \"Sold out\" : \"Buy now\";\n return {\n chip: label,\n cta: label,\n price: formatMoney(item.buyNowPriceAmount ?? 0),\n priceLabel: \"Buy Now\",\n secondary:\n item.availableQuantity === null\n ? \"Available\"\n : String(item.availableQuantity),\n };\n }\n return {\n chip: status === \"active\" ? \"Live\" : STATUS_LABELS[status],\n cta: { active: \"Bid now\", draft: \"Preview item\", finished: \"View item\" }[\n status\n ],\n price:\n status === \"finished\" && !item.maxBidAmount\n ? \"No bids\"\n : formatMoney(item.maxBidAmount ?? 0),\n priceLabel: status === \"finished\" ? \"Final bid\" : \"Current\",\n secondary: formatMoney(item.minBidAmount ?? 0),\n };\n}\nfunction ItemCard({\n auction,\n item,\n onSelect,\n}: {\n auction: LockerverseAuction;\n item: LockerverseAuctionItem;\n onSelect: () => void;\n}) {\n const status = getAuctionDisplayStatus(auction, item);\n const buyNow = item.saleMode === \"buy_now\";\n const display = itemCardDisplay(item, status);\n return (\n <article className=\"lockerverse-auctions__catalog-card\">\n <button\n aria-label={`View ${item.name}`}\n className=\"lockerverse-auctions__catalog-select\"\n onClick={onSelect}\n type=\"button\"\n />\n <div className=\"lockerverse-auctions__catalog-media\">\n <CatalogImage\n fallback={\n item.image ||\n auction.configuration.image ||\n auction.community?.banner ||\n auction.community?.thumbnail\n }\n images={item.images}\n name={item.name}\n />\n <div className=\"lockerverse-auctions__catalog-chips\">\n <span\n className=\"lockerverse-auctions__catalog-chip\"\n data-live={status === \"active\"}\n >\n {display.chip}\n </span>\n <Timing\n auction={\n item.finishedAt && status === \"finished\"\n ? { ...auction, endAt: item.finishedAt }\n : auction\n }\n item\n status={status}\n />\n </div>\n <dl className=\"lockerverse-auctions__catalog-metrics\">\n <Metric\n icon={buyNow ? \"bag\" : \"gavel\"}\n label={display.priceLabel}\n value={display.price}\n />\n <Metric\n icon=\"clock\"\n label={buyNow ? \"Available\" : \"Floor\"}\n value={display.secondary}\n />\n </dl>\n </div>\n <div className=\"lockerverse-auctions__catalog-body\">\n <h3>{item.name}</h3>\n <AuctionDescription\n className=\"lockerverse-auctions__catalog-description\"\n description={item.description || \"View auction item details.\"}\n links={false}\n />\n <div className=\"lockerverse-auctions__catalog-footer lockerverse-auctions__catalog-footer--item\">\n <span className=\"lockerverse-auctions__catalog-cta\">\n {display.cta}\n <Icon kind=\"arrow\" />\n </span>\n </div>\n </div>\n </article>\n );\n}\n/** Optional catalog UI, shared with the Lockerverse auction design. */\nexport function LockerverseAuctions({\n auctions,\n onSelectItem,\n theme = \"dark\",\n style,\n className,\n}: LockerverseAuctionsProps) {\n const [selectedId, setSelectedId] = useState<string | null>(null);\n const [filter, setFilter] = useState<ItemFilter>(\"all\");\n const headingRef = useRef<HTMLHeadingElement>(null);\n const previousId = useRef(selectedId);\n const selected = auctions.auctions?.find(\n (auction) => auction.id === selectedId\n );\n useEffect(() => {\n if (previousId.current !== selectedId) {\n headingRef.current?.focus();\n previousId.current = selectedId;\n }\n }, [selectedId]);\n const items = [...(selected?.items ?? [])].sort(\n (left, right) =>\n left.position - right.position ||\n left.createdAt.localeCompare(right.createdAt)\n );\n const filtered = selected\n ? items.filter(\n (item) =>\n filter === \"all\" || getAuctionDisplayStatus(selected, item) === filter\n )\n : [];\n return (\n <section\n aria-busy={auctions.loading}\n aria-label=\"Auctions\"\n className={[\n \"lockerverse-auctions\",\n \"lockerverse-auctions--catalog\",\n className,\n ]\n .filter(Boolean)\n .join(\" \")}\n data-lockerverse-theme={theme}\n style={style}\n >\n <header className=\"lockerverse-auctions__catalog-header\">\n {selected ? (\n <button\n className=\"lockerverse-auctions__catalog-back\"\n onClick={() => {\n setSelectedId(null);\n setFilter(\"all\");\n }}\n type=\"button\"\n >\n <Icon kind=\"back\" />\n Auctions\n </button>\n ) : null}\n <h2 ref={headingRef} tabIndex={-1}>\n {selected?.name ?? \"Auctions\"}\n </h2>\n {selected?.description ? (\n <AuctionDescription description={selected.description} />\n ) : null}\n </header>\n {auctions.loading ? <p role=\"status\">Loading auctions…</p> : null}\n {auctions.error ? (\n <div role=\"alert\">\n <p>{auctions.error.message}</p>\n <button onClick={auctions.refresh} type=\"button\">\n Try again\n </button>\n </div>\n ) : null}\n {auctions.auctions && (selected || auctions.auctions.length > 0) ? (\n <>\n <div className=\"lockerverse-auctions__catalog-lineup\">\n <div>\n <h3>Auction lineup</h3>\n <p>Browse the current collection.</p>\n </div>\n <span>\n {selected\n ? `${filtered.length} ${filtered.length === 1 ? \"item\" : \"items\"}`\n : `${auctions.auctions.length} ${auctions.auctions.length === 1 ? \"auction\" : \"auctions\"}`}\n </span>\n </div>\n {selected ? (\n <fieldset\n aria-label=\"Filter auction items\"\n className=\"lockerverse-auctions__catalog-filters\"\n >\n {FILTERS.map((option) => (\n <button\n aria-pressed={filter === option.value}\n key={option.value}\n onClick={() => setFilter(option.value)}\n type=\"button\"\n >\n {option.label}\n <span>\n {option.value === \"all\"\n ? items.length\n : items.filter(\n (item) =>\n getAuctionDisplayStatus(selected, item) ===\n option.value\n ).length}\n </span>\n </button>\n ))}\n </fieldset>\n ) : null}\n </>\n ) : null}\n <CatalogResults\n auctions={auctions.auctions}\n filtered={filtered}\n onSelectAuction={(id) => {\n setSelectedId(id);\n setFilter(\"all\");\n }}\n onSelectItem={onSelectItem}\n selected={selected}\n />\n </section>\n );\n}\n\nfunction CatalogResults({\n selected,\n filtered,\n auctions,\n onSelectItem,\n onSelectAuction,\n}: {\n selected: LockerverseAuction | undefined;\n filtered: LockerverseAuctionItem[];\n auctions: LockerverseAuction[] | null;\n onSelectItem: LockerverseAuctionsProps[\"onSelectItem\"];\n onSelectAuction: (id: string) => void;\n}) {\n if (selected) {\n if (!filtered.length) {\n return (\n <p className=\"lockerverse-auctions__catalog-empty\">\n No items match this auction view.\n </p>\n );\n }\n return (\n <ul className=\"lockerverse-auctions__catalog-grid\">\n {filtered.map((item) => (\n <li key={item.id}>\n <ItemCard\n auction={selected}\n item={item}\n onSelect={() => onSelectItem(selected, item)}\n />\n </li>\n ))}\n </ul>\n );\n }\n if (!auctions) {\n return null;\n }\n if (!auctions.length) {\n return (\n <div className=\"lockerverse-auctions__catalog-empty\">\n <h3>No auctions yet.</h3>\n <p>Published auctions will appear here once they are available.</p>\n </div>\n );\n }\n return (\n <ul className=\"lockerverse-auctions__catalog-grid\">\n {auctions.map((auction) => (\n <li key={auction.id}>\n <AuctionCard\n auction={auction}\n onSelect={() => onSelectAuction(auction.id)}\n />\n </li>\n ))}\n </ul>\n );\n}\n","import {\n type CreateLockerverseAuctionOptions,\n createLockerverseAuctionClient,\n type LockerverseAuction,\n type LockerverseAuctionClient,\n type LockerverseSdkError,\n} from \"@lockerverse/sdk/auctions\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useImmutableResourceIdentity } from \"./immutable-resource-identity.ts\";\n\nexport type UseLockerverseAuctionsResult = {\n client: LockerverseAuctionClient;\n auctions: LockerverseAuction[] | null;\n loading: boolean;\n error: LockerverseSdkError | null;\n refresh: () => void;\n};\n\ntype AuctionLoadState = Pick<\n UseLockerverseAuctionsResult,\n \"auctions\" | \"error\"\n>;\n\nexport function useLockerverseAuctions(\n options: CreateLockerverseAuctionOptions\n): UseLockerverseAuctionsResult {\n useImmutableResourceIdentity(\"auctions\", {\n apiBaseUrl: options.apiBaseUrl,\n communitySlug: options.communitySlug,\n environment: options.environment,\n slug: \"\",\n });\n const onErrorRef = useRef(options.onError);\n onErrorRef.current = options.onError;\n const [client] = useState(() =>\n createLockerverseAuctionClient({\n ...options,\n onError: (error) => onErrorRef.current?.(error),\n })\n );\n const [revision, setRevision] = useState(0);\n const [state, setState] = useState<AuctionLoadState>({\n auctions: null,\n error: null,\n });\n useEffect(() => {\n let active = true;\n client.list().then(\n (auctions) => {\n if (active) {\n setState({ auctions, error: null });\n }\n },\n (error: LockerverseSdkError) => {\n if (active) {\n setState({ auctions: null, error });\n }\n }\n );\n return () => {\n active = false;\n };\n }, [client, revision]);\n const refresh = useCallback(() => {\n setState({ auctions: null, error: null });\n setRevision((value) => value + 1);\n }, []);\n return {\n ...state,\n client,\n loading: state.auctions === null && state.error === null,\n refresh,\n };\n}\n"],"mappings":"iVA0BA,MAAM,EAAgB,CACpB,OAAQ,WACR,MAAO,cACP,SAAU,QACZ,EACM,EAAU,CACd,CAAE,MAAO,MAAO,MAAO,KAAM,EAC7B,CAAE,MAAO,OAAQ,MAAO,QAAS,EACjC,CAAE,MAAO,WAAY,MAAO,OAAQ,EACpC,CAAE,MAAO,SAAU,MAAO,UAAW,CACvC,EAGA,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i}from"./format-money.js";import{a,c as o,i as s,l as c,n as l,o as u,r as d,s as f,t as p,u as m}from"./phone.js";import{AddressElement as h,Elements as g,PaymentElement as _,useElements as v,useStripe as y}from"@stripe/react-stripe-js";import{loadStripe as b}from"@stripe/stripe-js/pure/index.js";import{createContext as x,useCallback as S,useContext as C,useEffect as w,useId as T,useLayoutEffect as E,useMemo as D,useReducer as O,useRef as k,useState as A}from"react";import{array as j,minLength as M,minValue as N,nonEmpty as P,number as F,object as I,pipe as L,regex as R,safeInteger as z,safeParse as B,strictObject as V,string as ee,trim as H,union as te}from"valibot";import{Fragment as ne,jsx as U,jsxs as W}from"react/jsx-runtime";import{LockerverseSdkError as re,estimateLockerverseCheckout as ie}from"@lockerverse/sdk/checkout";import{Select as G}from"@base-ui/react/select";const ae=x(void 0);function K({children:e,container:t}){return U(ae.Provider,{value:t,children:e})}function q(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m4 6 4 4 4-4`})})}function oe(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m3 8 3 3 7-7`})})}function se({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=C(ae),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return U(`div`,{className:d,children:W(G.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[W(G.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[U(G.Value,{}),U(G.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:U(q,{})})]}),U(G.Portal,{container:u,children:U(G.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:U(G.Popup,{className:`lockerverse-payment__select-popup`,children:U(G.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>W(G.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[U(G.ItemText,{children:e.label}),U(G.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:U(oe,{})})]},e.value))})})})})]})})}const J=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],Y=[`15`,`12`,`10`,`5`],X=[...Y,`custom`];function ce({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=X.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%X.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+X.length)%X.length;break;case`Home`:r=0;break;case`End`:r=X.length-1;break;default:return}e.preventDefault();let i=X[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return W(`div`,{className:`lockerverse-payment__tip-box`,children:[U(`p`,{children:`Add a tip to support the Lockerverse platform`}),W(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[Y.map(e=>W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),W(`span`,{children:[e,`%`]})]},e)),W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),U(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?W(`label`,{children:[U(`span`,{children:`Custom tip`}),W(`span`,{className:`lockerverse-payment__money-input`,children:[U(`span`,{"aria-hidden":`true`,children:`$`}),U(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?U(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):U(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function le({checked:e,children:t,name:n,onChange:r}){return W(`label`,{className:`lockerverse-payment__check-row`,children:[U(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),U(`span`,{children:t})]})}function ue({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,memberIdLabel:o,onChange:s,onApplyPromo:c,promoError:l,values:u}){let d=e=>s({...u,...e});return W(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?W(`label`,{children:[U(`span`,{children:o?.trim()||`Member ID`}),U(`input`,{name:`memberId`,onChange:e=>d({memberId:e.currentTarget.value}),placeholder:`Optional`,value:u.memberId})]}):null,n.merchSize?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${r}-merch-size-label`,children:`Size`}),U(se,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=J.find(t=>t===e);t&&d({merchSize:t})},options:J.map(e=>({label:e,value:e})),value:u.merchSize})]}):null,n.promoCode?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),W(`div`,{className:`lockerverse-payment__promo-control`,children:[U(`input`,{"aria-describedby":l?`${r}-promo-code-error`:void 0,"aria-invalid":l?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>d({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:u.promoCode}),U(`button`,{disabled:!u.promoCode.trim()||i,onClick:c,type:`button`,children:i?`Applying…`:`Apply`})]}),l?U(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:l}):null]}):null,U(a,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>d({customFields:e}),values:u.customFields})]})}function de({amountCents:e,enabled:t,onChange:n,values:r}){return t?W(le,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,i(e),` to help cover processing fees`]}):null}function fe(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function Z(e,t,n){return t.includes(e.status)?{...e,...n}:e}function pe(e,t){if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return Z(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return Z(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return Z(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return Z(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return Z(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return Z(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return Z(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return Z(e,[`submitting`],{status:`editing`});case`retryable_failure`:return Z(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return Z(e,[`recovering`],{error:t.error,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return Z(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return Z(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function me(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function he(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:me(e)?`error`:`idle`}function ge(e){return e.status===`submitting`}function _e(e){return t(e)}function ve(t,r){let i=r?{...t,phone:_e(t.phone)}:t,a=I(r?{email:n,phone:e}:{email:n}),o=B(a,i);if(o.success)return{errors:{},value:o.output};let s={};for(let e of o.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}const ye=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],be=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function xe(e,t,n,r){return(n===t.totalCents?be:ye).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function Q(e){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function Se(e,t,n){if(t.checkoutStatus!==`action_required`)return Q(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return Q(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function Ce(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof re&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return Se(e,r,n)}async function we(e,t,n){try{return Se(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Te=L(ee(),H(),P()),Ee=L(F(),z(),N(1)),De=L(j(te([V({amountCents:Ee,productSlug:Te}),V({productSlug:Te,quantity:Ee}),V({productSlug:Te})])),M(1)),Oe=L(ee(),H(),R(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function ke(e){let t=B(Oe,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function Ae(e){let t=B(De,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const je=`This promo code is invalid or cannot be applied.`;function Me(e,t){return t.tipPercent===`custom`?t.customTip.trim()?ke(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Ne(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Pe(e,t,n){let r=e.widget.fields.tipping?Me(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Fe(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?je:void 0}}function Ie(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?je:void 0}}function Le(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Re(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Le(r.shipping,`Shipping`)}function ze({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function Be({catalog:e,confirmationToken:t,email:n,fieldValues:r,metadata:i,phone:a,shippingAddress:o}){let s={customFieldAnswers:u(e.widget.customFields,r.customFields),email:n};if(t&&(s.confirmationToken=t),i&&(s.metadata=i),e.widget.fields.memberId&&r.memberId.trim()&&(s.memberId=r.memberId.trim()),e.widget.fields.merchSize&&(s.merchSize=r.merchSize),e.widget.fields.phone&&(s.phone=a),o){let e={city:o.address.city??``,country:o.address.country,line1:o.address.line1??``,postal_code:o.address.postal_code??``,state:o.address.state??``};o.address.line2&&(e.line2=o.address.line2),s.shipping={address:e,name:o.name}}return s}function Ve(e){if(!e())throw Error(`Payment component is no longer active.`)}function He(e,t){r(e,t)}function Ue(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function We({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=_e(d),_=Me(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...Ne(t,o,h,_.cents),catalog:t,items:n});if(Ve(s),v.totalCents>0&&xe(f,v,c,m))return{kind:`quote_changed`,quote:v};let y,b;if(v.totalCents===0)t.widget.fields.shipping&&(y=Re(t,o,Le(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),Ve(s);let n=await i.submit();if(Ve(s),n.error)throw Error(n.error.message);let r=Le(e.billing,`Billing`);y=Re(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:ze({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:y})});if(Ve(s),a.error)throw Error(a.error.message);b=a.confirmationToken.id}He(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let x=await Ce(r,{checkout:v,submission:Be({catalog:t,confirmationToken:b,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:y})},p);return Ve(s),Ue(x,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function Ge(e,t){r(e,t)}function Ke(e,t){r(e,t)}function qe(e,t){return{...e,...t}}function Je(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}function Ye(e){return e instanceof re&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function Xe({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Fe(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Ze({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Ie(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function Qe({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:a,result:o,setDisplayedTotalCents:s,dispatchState:c}){if(o.kind===`quote_changed`){let e=`The total changed to ${i(o.quote.totalCents)}. Review it and pay again.`;a(o.quote,e),s(o.quote.totalCents),c({type:`quote_changed`});return}if(o.kind===`payment_failed`){Ge(t,null),c({error:o.message,type:`retryable_failure`});return}if(o.kind===`payment_unresolved`){c({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),Ke(n,{paymentReference:o.paymentReference,reason:o.reason});return}a(o.quote),Ge(t,null),c({message:o.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),r(e,qe(o.payment,{email:o.email,lineItems:o.quote.lineItems}))}function $e(e){let{catalog:t,checkoutItems:n,client:i,elements:a,email:o,fieldValues:s,metadata:c,onPaymentComplete:l,onResumePaymentFailed:u,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,onStateChange:h,quote:g,resumePayment:_,stripe:v,stripeConnectedAccountId:y,stripeLoadFailed:b,paymentState:x,updateState:C}=e,[T,E]=A(g.totalCents),[D,O]=A(),j=k(!1),M=k(0),N=k(0),P=S(e=>C(e,!0),[C]),F=S(()=>{let e=N.current+1;return N.current=e,()=>N.current===e},[]);w(()=>()=>{N.current+=1,M.current+=1},[]);let{parsedTip:I,totalCents:L}=Pe(t,s,g);w(()=>{L!==null&&(E(L),L>0&&a?.update({amount:L}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,a,s.includeServiceFee,L,g.serviceFeeCents,g.tipCents,g.totalCents,g.subtotalCents]),w(()=>{if(!_||j.current||x.status!==`recovering`)return;j.current=!0;let e=F();return h(he(x)),we(i,_.paymentReference,v).then(t=>{if(e()&&!Je(t,v,b)){if(t.kind===`failed`){Ge(f,null),u(),P({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){P({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),Ke(p,{paymentReference:t.paymentReference,reason:t.reason});return}Ge(f,null),P({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),r(l,qe(t.payment,{email:null,lineItems:null}))}}),()=>{e()&&(N.current+=1),j.current=!1}},[i,l,u,f,p,h,_,v,b,F,P,x]);let R=S((e=!1,t=!1)=>{t||(M.current+=1),e&&O(void 0),C({type:`field_changed`})},[C]);async function z(e=!1,r=!1){let a=ve({email:o.trim().toLowerCase(),phone:``},!1);if(!(I.success&&(a.value||e)))return;M.current+=1;let c=M.current;C({type:`quote_refresh_started`});try{let e=await i.calculateTotal({...Ne(t,s,a.value?.email??``,I.cents),catalog:t,items:n});if(c!==M.current)return;Xe({nextQuote:e,onQuoteChange:m,setDisplayedTotalCents:E,setPromoError:O,updateState:C,validatePromo:r})}catch(e){if(c!==M.current)return;if(Ye(e)){C({type:`sold_out`});return}Ze({error:e,setPromoError:O,updateState:C,validatePromo:r})}}async function B(){O(void 0),await z(!0,!0)}async function V({addresses:e,phone:r}){P({type:`submission_started`});let u=F();try{let d=await We({addresses:e,catalog:t,checkoutItems:n,client:i,elements:a,email:o,fieldValues:s,isAttemptActive:u,locallyPreviewedTotalCents:T,metadata:c,onPaymentRecoveryChange:f,phone:r,quote:g,stripe:v,stripeConnectedAccountId:y});if(!u())return;Qe({dispatchState:P,onPaymentComplete:l,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,result:d,setDisplayedTotalCents:E})}catch(e){if(!u())return;if(Ge(f,null),Ye(e)){P({type:`sold_out`});return}let t=e instanceof re?d(e.serverCode):void 0;if(t)return P({type:`submission_validation_failed`}),{phoneError:t};P({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let ee=x.status===`succeeded`||x.status===`unresolved`?x.message:void 0;return{commands:{applyPromo:B,fieldChanged:R,refreshAuthoritativeTotal:z,reportStripeLoadError:e=>P({error:e,type:`retryable_failure`}),reportValidationFailure:()=>P({type:`validation_failed`}),submit:V},state:{displayedTotalCents:T,isRecovering:x.status===`recovering`,isRefreshingQuote:x.status===`refreshing_quote`,isSubmitting:ge(x),parsedTip:I,paymentError:me(x),promoError:D,terminalMessage:ee}}}const et=new Map,tt=(e,t)=>{let n=t?.stripeAccount??null,r=et.get(e);r||(r=new Map,et.set(e,r));let i=r.get(n);if(i)return i;let a=b(e,t).catch(()=>(r?.get(n)===a&&(r.delete(n),r.size===0&&et.delete(e)),null));return r.set(n,a),a};function nt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return tt(n,t?{stripeAccount:t}:void 0)}function rt(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}function it(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function at({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:d,resumePayment:f,onStateChange:p,stripeLoader:m,theme:h,visualStyle:_}){let[v,y]=A(()=>fe(!!f)),b=k(v);b.current=v;let x=S((e,t=!1)=>{let n=pe(b.current,e);n!==b.current&&(b.current=n,y(n),t&&p(he(n)))},[p]),C=it(t,d,f),T=k({connectedAccountId:C,paymentOption:d.paymentOption});v.status!==`submitting`&&v.status!==`recovering`&&(T.current={connectedAccountId:C,paymentOption:d.paymentOption});let{connectedAccountId:E,paymentOption:O}=T.current,j=D(()=>m(t.payment.publishableKey,E?{stripeAccount:E}:void 0).catch(()=>null),[t.payment.publishableKey,E,m]),[M,N]=A(!1);return w(()=>{let e=!0;return N(!1),j.then(t=>{e&&t===null&&N(!0)}),()=>{e=!1}},[j]),U(g,{options:{amount:Math.max(d.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:h===`light`?`stripe`:`night`,variables:{borderRadius:_?.[`--lockerverse-radius`]??`10px`,colorBackground:_?.[`--lockerverse-control`]??(h===`light`?`#f5f6f7`:`#121212`),colorDanger:_?.[`--lockerverse-danger`]??(h===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:_?.[`--lockerverse-text`]??(h===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:_?.[`--lockerverse-placeholder`]??(h===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:_?.[`--lockerverse-muted`]??(h===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:O===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:j,children:U(gt,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:p,paymentState:v,quote:d,resumePayment:f,stripeConnectedAccountId:E,stripeLoadFailed:M,updateState:x})},`${t.payment.publishableKey}:${E??`platform`}:${O}`)}function ot({label:e}){return W(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[U(`p`,{children:e}),W(`div`,{"aria-hidden":`true`,children:[U(`span`,{}),U(`span`,{}),U(`span`,{})]})]})}function st({onError:e,onReady:t,ready:n}){return W(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:U(ot,{label:`Loading payment form...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(_,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function ct({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return W(`div`,{className:`lockerverse-payment__address`,children:[U(`h2`,{children:e}),W(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:U(ot,{label:`Loading ${e.toLowerCase()}...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(h,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function lt({message:e}){return e?U(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function ut({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return W(ne,{children:[f?U(st,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?U(ct,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?W(`div`,{className:`lockerverse-payment__shipping`,children:[U(le,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:U(ct,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function dt({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let a=rt(r.paymentOption),o=Math.max(0,e-r.subtotalCents+r.discountCents);return W(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[U(`h2`,{children:`Order summary`}),U(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>W(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[W(`span`,{children:[e.productName,e.quantity>1?W(ne,{children:[` `,W(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?U(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?U(`small`,{children:` · Annual`}):null]}),U(`strong`,{children:i(e.subtotalCents)})]},e.listingId))}),W(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[o>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[U(`span`,{children:`Service fee`}),U(`strong`,{children:i(o)})]}):null,r.discountCents>0&&r.appliedDiscount?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[W(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),W(`strong`,{children:[`-`,i(r.discountCents)]})]}):null,t>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[U(`span`,{children:`Tip`}),U(`strong`,{children:i(t)})]}):null,W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[U(`span`,{children:a?`${a.label} total`:`Total`}),U(`strong`,{children:i(n)})]})]})]})}function ft({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:a,isRequiredShippingReady:o,isSubmitting:s,onFieldValuesChange:c,quote:l}){let u=t===0,d=u?!e.widget.fields.shipping||r&&o:a&&r&&o,f=rt(l.paymentOption),p=u?`Complete order`:`Pay ${i(t)}`;!u&&f&&(p=`Subscribe for ${i(t)}/${f.interval}`),s&&(p=u?`Completing…`:`Processing…`);let m=`Process payment for ${i(t)} total`;return u?m=`Complete order`:f&&(m=`Start ${f.label.toLowerCase()} subscription for ${i(t)}`),W(`div`,{className:`lockerverse-payment__actions`,children:[U(de,{amountCents:l.serviceFeeCents||Math.round(l.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:c,values:n}),U(`button`,{"aria-busy":s,"aria-label":m,disabled:s||!d,type:`submit`,children:p})]})}function pt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function mt({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&pt(n,`custom:${o}`)}function ht({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:f,phoneErrorId:m,phoneId:h,phoneRef:g}){return W(`div`,{className:`lockerverse-payment__contact`,children:[U(`label`,{htmlFor:r,children:`Email`}),U(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?U(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:W(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),f?W(ne,{children:[U(`label`,{htmlFor:h,children:`Phone`}),W(`div`,{className:`lockerverse-payment__phone-control`,children:[U(se,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:p,value:d}),U(`input`,{"aria-describedby":a.phone?m:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:h,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:g,type:`tel`,value:u})]}),a.phone?U(`p`,{className:`lockerverse-payment__field-message`,id:m,children:a.phone}):null]}):null]})}function gt({catalog:e,checkoutItems:t,client:n,metadata:r,onPaymentComplete:i,onResumePaymentFailed:a,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:u,onStateChange:d,quote:p,resumePayment:m,stripeConnectedAccountId:h,stripeLoadFailed:g,paymentState:_,updateState:b}){let[x,S]=A(``),[C,E]=A(``),[D,O]=A(`US`),[j,M]=A({}),[N,P]=A({}),[F,I]=A(),[L,R]=A(!1),[z,B]=A(!1),[V,ee]=A(!1),[H,te]=A({customFields:f(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),ne=k({billing:null,shipping:null}),re=k(null),ie=k(null),G=k(null),ae=k(p.totalCents>0),K=$e({catalog:e,checkoutItems:t,client:n,elements:v(),email:x,fieldValues:H,metadata:r,onPaymentComplete:i,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:u,onResumePaymentFailed:a,onStateChange:d,paymentState:_,quote:p,resumePayment:m,stripe:y(),stripeConnectedAccountId:h,stripeLoadFailed:g,updateState:b}),{displayedTotalCents:q,isRecovering:oe,isRefreshingQuote:se,isSubmitting:J,parsedTip:Y,paymentError:X,promoError:le,terminalMessage:de}=K.state,fe=`lockerverse-${T()}`,Z=`${fe}-email`,pe=`${Z}-error`,me=`${fe}-phone`,he=`${me}-error`,ge=`${fe}-tip-error`,_e=(Y.success?Y.cents:null)??0,ye=q-_e,be=!e.widget.fields.shipping||H.shippingMatchesBilling||V;w(()=>{J&&G.current?.focus({preventScroll:!0})},[J]),w(()=>{J||j.email||!j.phone||ie.current?.focus()},[j.email,j.phone,J]),w(()=>{let e=q>0;e&&!ae.current&&(R(!1),B(!1)),ae.current=e},[q]);function xe(e){K.commands.fieldChanged(!1,e!==`email`),M(t=>{let n={...t};return delete n[e],n})}function Q(e){let t=e.promoCode!==H.promoCode,n=e.includeServiceFee!==H.includeServiceFee;K.commands.fieldChanged(t,!(t||n)),te(e),P({}),I(void 0)}async function Se(t){t.preventDefault();let n=l(C,D),r=ve({email:x,phone:n},e.widget.fields.phone),i=o(e.widget.customFields,H.customFields);if(!(r.value&&Y.success)||Object.keys(i).length>0){M(r.errors),P(i),I(Y.success?void 0:Y.message),K.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{mt({customFieldErrors:i,emailRef:re,form:e,parsedTipSuccess:Y.success,phoneRef:ie,validationErrors:r.errors})});return}M({}),P({});let a=await K.commands.submit({addresses:ne.current,phone:n});a?.phoneError&&M({phone:a.phoneError})}return de?U(`p`,{className:`lockerverse-payment__payment-status`,ref:G,role:`status`,tabIndex:-1,children:de}):oe?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):W(`form`,{"aria-busy":J,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Se,children:[U(`div`,{"data-lockerverse-input-region":``,inert:J?!0:void 0,children:W(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:J,children:[U(dt,{displayedBaseCents:ye,displayedTipCents:_e,displayedTotalCents:q,quote:p}),U(ce,{enabled:e.widget.fields.tipping,error:F,errorId:ge,onChange:Q,values:H}),U(ht,{email:x,emailDiscountPercentOff:p.appliedDiscount?.source===`email_list`?p.appliedDiscount.percentageOff:void 0,emailErrorId:pe,emailId:Z,emailRef:re,errors:j,onEmailBlur:()=>K.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{S(e),xe(`email`)},onPhoneChange:e=>{E(e),xe(`phone`)},onPhoneCountryChange:e=>{O(e),K.commands.fieldChanged(!1,!0),requestAnimationFrame(()=>ie.current?.focus())},phone:C,phoneCountry:D,phoneEnabled:e.widget.fields.phone,phoneErrorId:he,phoneId:me,phoneRef:ie}),U(ut,{catalog:e,displayedTotalCents:q,fieldValues:H,isBillingAddressReady:z,isPaymentReady:L,isShippingAddressReady:V,onAddressChange:(e,t)=>{ne.current[e]=t},onFieldValuesChange:Q,onStripeLoadError:K.commands.reportStripeLoadError,setIsBillingAddressReady:B,setIsPaymentReady:R,setIsShippingAddressReady:ee}),U(ue,{customFields:e.widget.customFields,errors:N,fields:e.widget.fields,idPrefix:fe,isPromoApplying:se,memberIdLabel:e.community?.memberIdLabel,onApplyPromo:K.commands.applyPromo,onChange:Q,promoError:le,values:H}),U(ft,{catalog:e,displayedTotalCents:q,fieldValues:H,isBillingAddressReady:z,isPaymentReady:L,isRequiredShippingReady:be,isSubmitting:J,onFieldValuesChange:Q,quote:p})]})}),J?U(`p`,{className:`lockerverse-payment__sr-only`,ref:G,role:`status`,tabIndex:-1,children:q===0?`Completing order…`:`Processing payment…`}):null,U(lt,{message:X})]})}function _t(){return U(s,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function vt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return xt(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t){return e===t}function yt({checkout:e}){return{displayedQuote:e,type:`ready`}}function bt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function xt(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function St(e,t){let n=e.widget.fields.serviceFee;return ie(e,{includeServiceFee:n,selection:t})}function Ct(e,t){try{return xt(St(e,t),1)}catch(e){return{failure:bt(e),phase:`error`,revision:0}}}function wt({catalog:e,client:t,paymentState:n,selection:r}){let i=Ae(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=D(()=>i.success?i.value:[],[i.success,a]),[s,c]=O(vt,void 0,()=>i.success?Ct(e,o):{phase:`loading`,revision:0}),l=k(void 0),u=k(0),d=k(s.phase===`ready`?a:void 0),f=k(s.phase===`error`?a:void 0),p=n===`submitting`||n===`success`||n===`unresolved`;w(()=>{if(!i.success||p||$(f.current,a)||$(l.current,a))return;let n=!0;l.current=a;let r=d.current===a;r||c({type:`loading`});function s(e){n&&c(e)}function m(){n&&(l.current=void 0,f.current=a)}let h;function g(e){if(!n||(l.current=void 0,f.current=a,r&&h!==void 0&&u.current!==h))return;let t=bt(e);if(t===`This option is sold out.`){c({failure:t,type:`error`});return}c(r?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!r){let t=St(e,o);r=!0,d.current=a,s(yt({checkout:t}))}let i=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});m(),u.current===h&&s({checkout:i,type:`checkout`})}catch(e){g(e)}}return _(),()=>{n=!1,$(l.current,a)&&(l.current=void 0)}},[e,t,i.success,p,a,o]);let m=$(d.current,a)||$(f.current,a)||$(l.current,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}function Tt(e,t){let n=m(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),r=c(n),i={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(i[`--lockerverse-accent`]=n),r&&e?.[`--lockerverse-accent-contrast`]===void 0&&(i[`--lockerverse-accent-contrast`]=r),{accent:n,rootStyle:i}}function Et({catalog:e,client:t,...n}){let{branding:r,className:i,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,resumePayment:l,selection:u,style:d,stripeLoader:f=tt,theme:p=`dark`,...m}=n,[h,g]=A(l),_=k(null),[v,y]=A(),[b,x]=A(`idle`),C=k(void 0),{selectionError:T,session:D,updateCheckout:O}=wt({catalog:e,client:t,paymentState:b,selection:u}),j=D.phase===`ready`?D.revision:void 0,M=S(e=>{j!==void 0&&(C.current=j),x(e)},[j]),N=S(e=>s?.(e),[s]),P=S(()=>{g(void 0)},[]);w(()=>{D.phase===`loading`&&y(void 0)},[D.phase]),E(()=>{D.phase===`ready`&&C.current!==D.revision&&x(e=>e===`success`||e===`unresolved`?e:`idle`)},[D.phase,D.revision]);let F=[`lockerverse-payment`,i].filter(Boolean).join(` `),I=r??e.community,{accent:L,rootStyle:R}=Tt(d,I);return T?U(`section`,{...m,className:F,"data-lockerverse-theme":p,role:`alert`,style:R,children:T}):D.phase===`error`&&D.failure===`This option is sold out.`||b===`sold_out`?W(`section`,{...m,className:F,"data-lockerverse-theme":p,role:`alert`,style:R,children:[U(`h1`,{children:`Sold out`}),U(`p`,{children:`This option is sold out.`})]}):D.phase===`error`?U(`section`,{...m,className:F,"data-lockerverse-theme":p,style:R,children:U(`p`,{role:`alert`,children:D.failure})}):D.phase===`ready`?W(`section`,{...m,"aria-label":`Payment`,className:F,"data-lockerverse-theme":p,"data-payment-state":b,ref:_,style:R,children:[W(`header`,{children:[e.widget.showCommunityBranding&&I?W(`div`,{className:`lockerverse-payment__branding`,children:[I.imageUrl?U(`img`,{alt:I.name,height:`48`,src:I.imageUrl,width:`48`}):null,U(`strong`,{children:I.name})]}):null,U(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?U(`p`,{children:e.widget.description}):null]}),v?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:v}):null,D.quoteFailure?W(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[U(`span`,{children:D.quoteFailure}),U(`span`,{children:` The final total will be checked when you submit.`})]}):null,U(K,{container:_,children:U(at,{accentColor:L,catalog:e,checkoutItems:D.checkoutItems,client:t,fontFamily:d?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:N,onPaymentUncertain:c,onQuoteChange:(e,t)=>{y(t),O(e)},onResumePaymentFailed:P,onStateChange:M,quote:D.displayedQuote,resumePayment:h,stripeLoader:f,theme:p,visualStyle:R},D.revision)})]}):U(`section`,{...m,"aria-busy":`true`,"aria-label":`Payment`,className:F,"data-lockerverse-theme":p,style:R,children:U(_t,{})})}function Dt({children:e,loading:t=!1,viewProps:n}){let{branding:r,className:i,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:s,onPaymentUncertain:l,resumePayment:u,selection:d,stripeLoader:f,style:p,theme:h=`dark`,...g}=n,_=m(p?.[`--lockerverse-accent`]??r?.accentColor??`#38d77a`),v=c(_),y={...p};return(p?.[`--lockerverse-accent`]!==void 0||r?.accentColor)&&(y[`--lockerverse-accent`]=_),v&&p?.[`--lockerverse-accent-contrast`]===void 0&&(y[`--lockerverse-accent-contrast`]=v),U(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,i].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function Ot({widget:e,...t}){return e.error?W(Dt,{viewProps:t,children:[U(`p`,{role:`alert`,children:e.error.message}),U(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?U(Dt,{loading:!0,viewProps:t,children:U(_t,{})}):U(Et,{catalog:e.catalog,client:e.client,...t})}export{nt as n,Ot as t};
1
+ import{c as e,i as t,s as n,t as r}from"./host-callback.js";import{a as i,c as a,i as o,l as s,n as c,o as l,r as u,s as d,t as f,u as p}from"./phone.js";import{AddressElement as m,Elements as h,PaymentElement as g,useElements as _,useStripe as v}from"@stripe/react-stripe-js";import{loadStripe as y}from"@stripe/stripe-js/pure/index.js";import{createContext as b,useCallback as x,useContext as S,useEffect as C,useId as w,useLayoutEffect as T,useMemo as E,useReducer as D,useRef as O,useState as k}from"react";import{array as A,minLength as j,minValue as M,nonEmpty as N,number as P,object as F,pipe as I,regex as L,safeInteger as R,safeParse as z,strictObject as B,string as V,trim as ee,union as H}from"valibot";import{Fragment as te,jsx as U,jsxs as W}from"react/jsx-runtime";import{LockerverseSdkError as ne,estimateLockerverseCheckout as re}from"@lockerverse/sdk/checkout";import{Select as G}from"@base-ui/react/select";const ie=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`});function K(e){return ie.format(e/100)}const q=b(void 0);function J({children:e,container:t}){return U(q.Provider,{value:t,children:e})}function ae(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m4 6 4 4 4-4`})})}function oe(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m3 8 3 3 7-7`})})}function Y({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=S(q),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return U(`div`,{className:d,children:W(G.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[W(G.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[U(G.Value,{}),U(G.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:U(ae,{})})]}),U(G.Portal,{container:u,children:U(G.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:U(G.Popup,{className:`lockerverse-payment__select-popup`,children:U(G.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>W(G.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[U(G.ItemText,{children:e.label}),U(G.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:U(oe,{})})]},e.value))})})})})]})})}const X=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],se=[`15`,`12`,`10`,`5`],Z=[...se,`custom`];function ce({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=Z.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%Z.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+Z.length)%Z.length;break;case`Home`:r=0;break;case`End`:r=Z.length-1;break;default:return}e.preventDefault();let i=Z[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return W(`div`,{className:`lockerverse-payment__tip-box`,children:[U(`p`,{children:`Add a tip to support the Lockerverse platform`}),W(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[se.map(e=>W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),W(`span`,{children:[e,`%`]})]},e)),W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),U(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?W(`label`,{children:[U(`span`,{children:`Custom tip`}),W(`span`,{className:`lockerverse-payment__money-input`,children:[U(`span`,{"aria-hidden":`true`,children:`$`}),U(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?U(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):U(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function le({checked:e,children:t,name:n,onChange:r}){return W(`label`,{className:`lockerverse-payment__check-row`,children:[U(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),U(`span`,{children:t})]})}function ue({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:a,memberIdLabel:o,onChange:s,onApplyPromo:c,promoError:l,values:u}){let d=e=>s({...u,...e});return W(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?W(`label`,{children:[U(`span`,{children:o?.trim()||`Member ID`}),U(`input`,{name:`memberId`,onChange:e=>d({memberId:e.currentTarget.value}),placeholder:`Optional`,value:u.memberId})]}):null,n.merchSize?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${r}-merch-size-label`,children:`Size`}),U(Y,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=X.find(t=>t===e);t&&d({merchSize:t})},options:X.map(e=>({label:e,value:e})),value:u.merchSize})]}):null,n.promoCode?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),W(`div`,{className:`lockerverse-payment__promo-control`,children:[U(`input`,{"aria-describedby":l?`${r}-promo-code-error`:void 0,"aria-invalid":l?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>d({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:u.promoCode}),U(`button`,{disabled:!u.promoCode.trim()||a,onClick:c,type:`button`,children:a?`Applying…`:`Apply`})]}),l?U(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:l}):null]}):null,U(i,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>d({customFields:e}),values:u.customFields})]})}function de({amountCents:e,enabled:t,onChange:n,values:r}){return t?W(le,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,K(e),` to help cover processing fees`]}):null}function fe(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function Q(e,t,n){return t.includes(e.status)?{...e,...n}:e}function pe(e,t){if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return Q(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return Q(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return Q(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return Q(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return Q(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return Q(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return Q(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return Q(e,[`submitting`],{status:`editing`});case`retryable_failure`:return Q(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return Q(e,[`recovering`],{error:t.error,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return Q(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return Q(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function me(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function he(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:me(e)?`error`:`idle`}function ge(e){return e.status===`submitting`}function _e(e){return t(e)}function ve(t,r){let i=r?{...t,phone:_e(t.phone)}:t,a=F(r?{email:n,phone:e}:{email:n}),o=z(a,i);if(o.success)return{errors:{},value:o.output};let s={};for(let e of o.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}const ye=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],be=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function xe(e,t,n,r){return(n===t.totalCents?be:ye).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function Se(e){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function Ce(e,t,n){if(t.checkoutStatus!==`action_required`)return Se(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return Se(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function we(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof ne&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return Ce(e,r,n)}async function Te(e,t,n){try{return Ce(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Ee=I(V(),ee(),N()),De=I(P(),R(),M(1)),Oe=I(A(H([B({amountCents:De,productSlug:Ee}),B({productSlug:Ee,quantity:De}),B({productSlug:Ee})])),j(1)),ke=I(V(),ee(),L(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Ae(e){let t=z(ke,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function je(e){let t=z(Oe,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const Me=`This promo code is invalid or cannot be applied.`;function Ne(e,t){return t.tipPercent===`custom`?t.customTip.trim()?Ae(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Pe(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Fe(e,t,n){let r=e.widget.fields.tipping?Ne(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Ie(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?Me:void 0}}function Le(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?Me:void 0}}function Re(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function ze(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Re(r.shipping,`Shipping`)}function Be({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function Ve({catalog:e,confirmationToken:t,email:n,fieldValues:r,metadata:i,phone:a,shippingAddress:o}){let s={customFieldAnswers:l(e.widget.customFields,r.customFields),email:n};if(t&&(s.confirmationToken=t),i&&(s.metadata=i),e.widget.fields.memberId&&r.memberId.trim()&&(s.memberId=r.memberId.trim()),e.widget.fields.merchSize&&(s.merchSize=r.merchSize),e.widget.fields.phone&&(s.phone=a),o){let e={city:o.address.city??``,country:o.address.country,line1:o.address.line1??``,postal_code:o.address.postal_code??``,state:o.address.state??``};o.address.line2&&(e.line2=o.address.line2),s.shipping={address:e,name:o.name}}return s}function He(e){if(!e())throw Error(`Payment component is no longer active.`)}function Ue(e,t){r(e,t)}function We(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function Ge({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=_e(d),_=Ne(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...Pe(t,o,h,_.cents),catalog:t,items:n});if(He(s),v.totalCents>0&&xe(f,v,c,m))return{kind:`quote_changed`,quote:v};let y,b;if(v.totalCents===0)t.widget.fields.shipping&&(y=ze(t,o,Re(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),He(s);let n=await i.submit();if(He(s),n.error)throw Error(n.error.message);let r=Re(e.billing,`Billing`);y=ze(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Be({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:y})});if(He(s),a.error)throw Error(a.error.message);b=a.confirmationToken.id}Ue(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let x=await we(r,{checkout:v,submission:Ve({catalog:t,confirmationToken:b,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:y})},p);return He(s),We(x,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function Ke(e,t){r(e,t)}function qe(e,t){r(e,t)}function Je(e,t){return{...e,...t}}function Ye(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}function Xe(e){return e instanceof ne&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function Ze({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Ie(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Qe({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Le(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function $e({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:i,result:a,setDisplayedTotalCents:o,dispatchState:s}){if(a.kind===`quote_changed`){let e=`The total changed to ${K(a.quote.totalCents)}. Review it and pay again.`;i(a.quote,e),o(a.quote.totalCents),s({type:`quote_changed`});return}if(a.kind===`payment_failed`){Ke(t,null),s({error:a.message,type:`retryable_failure`});return}if(a.kind===`payment_unresolved`){s({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),qe(n,{paymentReference:a.paymentReference,reason:a.reason});return}i(a.quote),Ke(t,null),s({message:a.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),r(e,Je(a.payment,{email:a.email,lineItems:a.quote.lineItems}))}function et(e){let{catalog:t,checkoutItems:n,client:i,elements:a,email:o,fieldValues:s,metadata:c,onPaymentComplete:l,onResumePaymentFailed:d,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,onStateChange:h,quote:g,resumePayment:_,stripe:v,stripeConnectedAccountId:y,stripeLoadFailed:b,paymentState:S,updateState:w}=e,[T,E]=k(g.totalCents),[D,A]=k(),j=O(!1),M=O(0),N=O(0),P=x(e=>w(e,!0),[w]),F=x(()=>{let e=N.current+1;return N.current=e,()=>N.current===e},[]);C(()=>()=>{N.current+=1,M.current+=1},[]);let{parsedTip:I,totalCents:L}=Fe(t,s,g);C(()=>{L!==null&&(E(L),L>0&&a?.update({amount:L}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,a,s.includeServiceFee,L,g.serviceFeeCents,g.tipCents,g.totalCents,g.subtotalCents]),C(()=>{if(!_||j.current||S.status!==`recovering`)return;j.current=!0;let e=F();return h(he(S)),Te(i,_.paymentReference,v).then(t=>{if(e()&&!Ye(t,v,b)){if(t.kind===`failed`){Ke(f,null),d(),P({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){P({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),qe(p,{paymentReference:t.paymentReference,reason:t.reason});return}Ke(f,null),P({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),r(l,Je(t.payment,{email:null,lineItems:null}))}}),()=>{e()&&(N.current+=1),j.current=!1}},[i,l,d,f,p,h,_,v,b,F,P,S]);let R=x((e=!1,t=!1)=>{t||(M.current+=1),e&&A(void 0),w({type:`field_changed`})},[w]);async function z(e=!1,r=!1){let a=ve({email:o.trim().toLowerCase(),phone:``},!1);if(!(I.success&&(a.value||e)))return;M.current+=1;let c=M.current;w({type:`quote_refresh_started`});try{let e=await i.calculateTotal({...Pe(t,s,a.value?.email??``,I.cents),catalog:t,items:n});if(c!==M.current)return;Ze({nextQuote:e,onQuoteChange:m,setDisplayedTotalCents:E,setPromoError:A,updateState:w,validatePromo:r})}catch(e){if(c!==M.current)return;if(Xe(e)){w({type:`sold_out`});return}Qe({error:e,setPromoError:A,updateState:w,validatePromo:r})}}async function B(){A(void 0),await z(!0,!0)}async function V({addresses:e,phone:r}){P({type:`submission_started`});let d=F();try{let u=await Ge({addresses:e,catalog:t,checkoutItems:n,client:i,elements:a,email:o,fieldValues:s,isAttemptActive:d,locallyPreviewedTotalCents:T,metadata:c,onPaymentRecoveryChange:f,phone:r,quote:g,stripe:v,stripeConnectedAccountId:y});if(!d())return;$e({dispatchState:P,onPaymentComplete:l,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,result:u,setDisplayedTotalCents:E})}catch(e){if(!d())return;if(Ke(f,null),Xe(e)){P({type:`sold_out`});return}let t=e instanceof ne?u(e.serverCode):void 0;if(t)return P({type:`submission_validation_failed`}),{phoneError:t};P({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let ee=S.status===`succeeded`||S.status===`unresolved`?S.message:void 0;return{commands:{applyPromo:B,fieldChanged:R,refreshAuthoritativeTotal:z,reportStripeLoadError:e=>P({error:e,type:`retryable_failure`}),reportValidationFailure:()=>P({type:`validation_failed`}),submit:V},state:{displayedTotalCents:T,isRecovering:S.status===`recovering`,isRefreshingQuote:S.status===`refreshing_quote`,isSubmitting:ge(S),parsedTip:I,paymentError:me(S),promoError:D,terminalMessage:ee}}}const tt=new Map,nt=(e,t)=>{let n=t?.stripeAccount??null,r=tt.get(e);r||(r=new Map,tt.set(e,r));let i=r.get(n);if(i)return i;let a=y(e,t).catch(()=>(r?.get(n)===a&&(r.delete(n),r.size===0&&tt.delete(e)),null));return r.set(n,a),a};function rt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return nt(n,t?{stripeAccount:t}:void 0)}function it(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}function at(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function ot({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:d,resumePayment:f,onStateChange:p,stripeLoader:m,theme:g,visualStyle:_}){let[v,y]=k(()=>fe(!!f)),b=O(v);b.current=v;let S=x((e,t=!1)=>{let n=pe(b.current,e);n!==b.current&&(b.current=n,y(n),t&&p(he(n)))},[p]),w=at(t,d,f),T=O({connectedAccountId:w,paymentOption:d.paymentOption});v.status!==`submitting`&&v.status!==`recovering`&&(T.current={connectedAccountId:w,paymentOption:d.paymentOption});let{connectedAccountId:D,paymentOption:A}=T.current,j=E(()=>m(t.payment.publishableKey,D?{stripeAccount:D}:void 0).catch(()=>null),[t.payment.publishableKey,D,m]),[M,N]=k(!1);return C(()=>{let e=!0;return N(!1),j.then(t=>{e&&t===null&&N(!0)}),()=>{e=!1}},[j]),U(h,{options:{amount:Math.max(d.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:g===`light`?`stripe`:`night`,variables:{borderRadius:_?.[`--lockerverse-radius`]??`10px`,colorBackground:_?.[`--lockerverse-control`]??(g===`light`?`#f5f6f7`:`#121212`),colorDanger:_?.[`--lockerverse-danger`]??(g===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:_?.[`--lockerverse-text`]??(g===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:_?.[`--lockerverse-placeholder`]??(g===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:_?.[`--lockerverse-muted`]??(g===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:A===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:j,children:U(_t,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:p,paymentState:v,quote:d,resumePayment:f,stripeConnectedAccountId:D,stripeLoadFailed:M,updateState:S})},`${t.payment.publishableKey}:${D??`platform`}:${A}`)}function st({label:e}){return W(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[U(`p`,{children:e}),W(`div`,{"aria-hidden":`true`,children:[U(`span`,{}),U(`span`,{}),U(`span`,{})]})]})}function ct({onError:e,onReady:t,ready:n}){return W(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:U(st,{label:`Loading payment form...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(g,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function lt({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return W(`div`,{className:`lockerverse-payment__address`,children:[U(`h2`,{children:e}),W(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:U(st,{label:`Loading ${e.toLowerCase()}...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(m,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function ut({message:e}){return e?U(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function dt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return W(te,{children:[f?U(ct,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?U(lt,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?W(`div`,{className:`lockerverse-payment__shipping`,children:[U(le,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:U(lt,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ft({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=it(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return W(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[U(`h2`,{children:`Order summary`}),U(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>W(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[W(`span`,{children:[e.productName,e.quantity>1?W(te,{children:[` `,W(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?U(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?U(`small`,{children:` · Annual`}):null]}),U(`strong`,{children:K(e.subtotalCents)})]},e.listingId))}),W(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[U(`span`,{children:`Service fee`}),U(`strong`,{children:K(a)})]}):null,r.discountCents>0&&r.appliedDiscount?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[W(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),W(`strong`,{children:[`-`,K(r.discountCents)]})]}):null,t>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[U(`span`,{children:`Tip`}),U(`strong`,{children:K(t)})]}):null,W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[U(`span`,{children:i?`${i.label} total`:`Total`}),U(`strong`,{children:K(n)})]})]})]})}function pt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=it(c.paymentOption),f=l?`Complete order`:`Pay ${K(t)}`;!l&&d&&(f=`Subscribe for ${K(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${K(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${K(t)}`),W(`div`,{className:`lockerverse-payment__actions`,children:[U(de,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),U(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function mt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function ht({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&mt(n,`custom:${o}`)}function gt({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:p,phoneErrorId:m,phoneId:h,phoneRef:g}){return W(`div`,{className:`lockerverse-payment__contact`,children:[U(`label`,{htmlFor:r,children:`Email`}),U(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?U(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:W(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),p?W(te,{children:[U(`label`,{htmlFor:h,children:`Phone`}),W(`div`,{className:`lockerverse-payment__phone-control`,children:[U(Y,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:f,value:d}),U(`input`,{"aria-describedby":a.phone?m:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:h,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:g,type:`tel`,value:u})]}),a.phone?U(`p`,{className:`lockerverse-payment__field-message`,id:m,children:a.phone}):null]}):null]})}function _t({catalog:e,checkoutItems:t,client:n,metadata:r,onPaymentComplete:i,onResumePaymentFailed:o,onPaymentRecoveryChange:s,onPaymentUncertain:l,onQuoteChange:u,onStateChange:f,quote:p,resumePayment:m,stripeConnectedAccountId:h,stripeLoadFailed:g,paymentState:y,updateState:b}){let[x,S]=k(``),[T,E]=k(``),[D,A]=k(`US`),[j,M]=k({}),[N,P]=k({}),[F,I]=k(),[L,R]=k(!1),[z,B]=k(!1),[V,ee]=k(!1),[H,te]=k({customFields:d(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),ne=O({billing:null,shipping:null}),re=O(null),G=O(null),ie=O(null),K=O(p.totalCents>0),q=et({catalog:e,checkoutItems:t,client:n,elements:_(),email:x,fieldValues:H,metadata:r,onPaymentComplete:i,onPaymentRecoveryChange:s,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:o,onStateChange:f,paymentState:y,quote:p,resumePayment:m,stripe:v(),stripeConnectedAccountId:h,stripeLoadFailed:g,updateState:b}),{displayedTotalCents:J,isRecovering:ae,isRefreshingQuote:oe,isSubmitting:Y,parsedTip:X,paymentError:se,promoError:Z,terminalMessage:le}=q.state,de=`lockerverse-${w()}`,fe=`${de}-email`,Q=`${fe}-error`,pe=`${de}-phone`,me=`${pe}-error`,he=`${de}-tip-error`,ge=(X.success?X.cents:null)??0,_e=J-ge,ye=!e.widget.fields.shipping||H.shippingMatchesBilling||V;C(()=>{Y&&ie.current?.focus({preventScroll:!0})},[Y]),C(()=>{Y||j.email||!j.phone||G.current?.focus()},[j.email,j.phone,Y]),C(()=>{let e=J>0;e&&!K.current&&(R(!1),B(!1)),K.current=e},[J]);function be(e){q.commands.fieldChanged(!1,e!==`email`),M(t=>{let n={...t};return delete n[e],n})}function xe(e){let t=e.promoCode!==H.promoCode,n=e.includeServiceFee!==H.includeServiceFee;q.commands.fieldChanged(t,!(t||n)),te(e),P({}),I(void 0)}async function Se(t){t.preventDefault();let n=c(T,D),r=ve({email:x,phone:n},e.widget.fields.phone),i=a(e.widget.customFields,H.customFields);if(!(r.value&&X.success)||Object.keys(i).length>0){M(r.errors),P(i),I(X.success?void 0:X.message),q.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{ht({customFieldErrors:i,emailRef:re,form:e,parsedTipSuccess:X.success,phoneRef:G,validationErrors:r.errors})});return}M({}),P({});let o=await q.commands.submit({addresses:ne.current,phone:n});o?.phoneError&&M({phone:o.phoneError})}return le?U(`p`,{className:`lockerverse-payment__payment-status`,ref:ie,role:`status`,tabIndex:-1,children:le}):ae?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):W(`form`,{"aria-busy":Y,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Se,children:[U(`div`,{"data-lockerverse-input-region":``,inert:Y?!0:void 0,children:W(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Y,children:[U(ft,{displayedBaseCents:_e,displayedTipCents:ge,displayedTotalCents:J,quote:p}),U(ce,{enabled:e.widget.fields.tipping,error:F,errorId:he,onChange:xe,values:H}),U(gt,{email:x,emailDiscountPercentOff:p.appliedDiscount?.source===`email_list`?p.appliedDiscount.percentageOff:void 0,emailErrorId:Q,emailId:fe,emailRef:re,errors:j,onEmailBlur:()=>q.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{S(e),be(`email`)},onPhoneChange:e=>{E(e),be(`phone`)},onPhoneCountryChange:e=>{A(e),q.commands.fieldChanged(!1,!0),requestAnimationFrame(()=>G.current?.focus())},phone:T,phoneCountry:D,phoneEnabled:e.widget.fields.phone,phoneErrorId:me,phoneId:pe,phoneRef:G}),U(dt,{catalog:e,displayedTotalCents:J,fieldValues:H,isBillingAddressReady:z,isPaymentReady:L,isShippingAddressReady:V,onAddressChange:(e,t)=>{ne.current[e]=t},onFieldValuesChange:xe,onStripeLoadError:q.commands.reportStripeLoadError,setIsBillingAddressReady:B,setIsPaymentReady:R,setIsShippingAddressReady:ee}),U(ue,{customFields:e.widget.customFields,errors:N,fields:e.widget.fields,idPrefix:de,isPromoApplying:oe,memberIdLabel:e.community?.memberIdLabel,onApplyPromo:q.commands.applyPromo,onChange:xe,promoError:Z,values:H}),U(pt,{catalog:e,displayedTotalCents:J,fieldValues:H,isBillingAddressReady:z,isPaymentReady:L,isRequiredShippingReady:ye,isSubmitting:Y,onFieldValuesChange:xe,quote:p})]})}),Y?U(`p`,{className:`lockerverse-payment__sr-only`,ref:ie,role:`status`,tabIndex:-1,children:J===0?`Completing order…`:`Processing payment…`}):null,U(ut,{message:se})]})}function vt(){return U(o,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function yt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return St(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t){return e===t}function bt({checkout:e}){return{displayedQuote:e,type:`ready`}}function xt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function St(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function Ct(e,t){let n=e.widget.fields.serviceFee;return re(e,{includeServiceFee:n,selection:t})}function wt(e,t){try{return St(Ct(e,t),1)}catch(e){return{failure:xt(e),phase:`error`,revision:0}}}function Tt({catalog:e,client:t,paymentState:n,selection:r}){let i=je(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=E(()=>i.success?i.value:[],[i.success,a]),[s,c]=D(yt,void 0,()=>i.success?wt(e,o):{phase:`loading`,revision:0}),l=O(void 0),u=O(0),d=O(s.phase===`ready`?a:void 0),f=O(s.phase===`error`?a:void 0),p=n===`submitting`||n===`success`||n===`unresolved`;C(()=>{if(!i.success||p||$(f.current,a)||$(l.current,a))return;let n=!0;l.current=a;let r=d.current===a;r||c({type:`loading`});function s(e){n&&c(e)}function m(){n&&(l.current=void 0,f.current=a)}let h;function g(e){if(!n||(l.current=void 0,f.current=a,r&&h!==void 0&&u.current!==h))return;let t=xt(e);if(t===`This option is sold out.`){c({failure:t,type:`error`});return}c(r?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!r){let t=Ct(e,o);r=!0,d.current=a,s(bt({checkout:t}))}let i=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});m(),u.current===h&&s({checkout:i,type:`checkout`})}catch(e){g(e)}}return _(),()=>{n=!1,$(l.current,a)&&(l.current=void 0)}},[e,t,i.success,p,a,o]);let m=$(d.current,a)||$(f.current,a)||$(l.current,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}function Et(e,t){let n=p(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),r=s(n),i={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(i[`--lockerverse-accent`]=n),r&&e?.[`--lockerverse-accent-contrast`]===void 0&&(i[`--lockerverse-accent-contrast`]=r),{accent:n,rootStyle:i}}function Dt({catalog:e,client:t,...n}){let{branding:r,className:i,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,resumePayment:l,selection:u,style:d,stripeLoader:f=nt,theme:p=`dark`,...m}=n,[h,g]=k(l),_=O(null),[v,y]=k(),[b,S]=k(`idle`),w=O(void 0),{selectionError:E,session:D,updateCheckout:A}=Tt({catalog:e,client:t,paymentState:b,selection:u}),j=D.phase===`ready`?D.revision:void 0,M=x(e=>{j!==void 0&&(w.current=j),S(e)},[j]),N=x(e=>s?.(e),[s]),P=x(()=>{g(void 0)},[]);C(()=>{D.phase===`loading`&&y(void 0)},[D.phase]),T(()=>{D.phase===`ready`&&w.current!==D.revision&&S(e=>e===`success`||e===`unresolved`?e:`idle`)},[D.phase,D.revision]);let F=[`lockerverse-payment`,i].filter(Boolean).join(` `),I=r??e.community,{accent:L,rootStyle:R}=Et(d,I);return E?U(`section`,{...m,className:F,"data-lockerverse-theme":p,role:`alert`,style:R,children:E}):D.phase===`error`&&D.failure===`This option is sold out.`||b===`sold_out`?W(`section`,{...m,className:F,"data-lockerverse-theme":p,role:`alert`,style:R,children:[U(`h1`,{children:`Sold out`}),U(`p`,{children:`This option is sold out.`})]}):D.phase===`error`?U(`section`,{...m,className:F,"data-lockerverse-theme":p,style:R,children:U(`p`,{role:`alert`,children:D.failure})}):D.phase===`ready`?W(`section`,{...m,"aria-label":`Payment`,className:F,"data-lockerverse-theme":p,"data-payment-state":b,ref:_,style:R,children:[W(`header`,{children:[e.widget.showCommunityBranding&&I?W(`div`,{className:`lockerverse-payment__branding`,children:[I.imageUrl?U(`img`,{alt:I.name,height:`48`,src:I.imageUrl,width:`48`}):null,U(`strong`,{children:I.name})]}):null,U(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?U(`p`,{children:e.widget.description}):null]}),v?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:v}):null,D.quoteFailure?W(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[U(`span`,{children:D.quoteFailure}),U(`span`,{children:` The final total will be checked when you submit.`})]}):null,U(J,{container:_,children:U(ot,{accentColor:L,catalog:e,checkoutItems:D.checkoutItems,client:t,fontFamily:d?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:N,onPaymentUncertain:c,onQuoteChange:(e,t)=>{y(t),A(e)},onResumePaymentFailed:P,onStateChange:M,quote:D.displayedQuote,resumePayment:h,stripeLoader:f,theme:p,visualStyle:R},D.revision)})]}):U(`section`,{...m,"aria-busy":`true`,"aria-label":`Payment`,className:F,"data-lockerverse-theme":p,style:R,children:U(vt,{})})}function Ot({children:e,loading:t=!1,viewProps:n}){let{branding:r,className:i,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,resumePayment:u,selection:d,stripeLoader:f,style:m,theme:h=`dark`,...g}=n,_=p(m?.[`--lockerverse-accent`]??r?.accentColor??`#38d77a`),v=s(_),y={...m};return(m?.[`--lockerverse-accent`]!==void 0||r?.accentColor)&&(y[`--lockerverse-accent`]=_),v&&m?.[`--lockerverse-accent-contrast`]===void 0&&(y[`--lockerverse-accent-contrast`]=v),U(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,i].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function kt({widget:e,...t}){return e.error?W(Ot,{viewProps:t,children:[U(`p`,{role:`alert`,children:e.error.message}),U(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?U(Ot,{loading:!0,viewProps:t,children:U(vt,{})}):U(Dt,{catalog:e.catalog,client:e.client,...t})}export{rt as n,kt as t};
2
2
  //# sourceMappingURL=lockerverse-payment.js.map