@thorprovider/storefront 0.7.0 → 0.9.0

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.
Files changed (151) hide show
  1. package/README.md +22 -2
  2. package/assets/templates/AGENTS.md +14 -2
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
  6. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +621 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +346 -38
  11. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +26 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  15. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +18 -0
  16. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  17. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  18. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  21. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  22. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  33. package/assets/templates/features/checkout/handlers.ts +24 -4
  34. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  35. package/assets/templates/features/customer-addresses/state.ts +33 -0
  36. package/assets/templates/features/customer-auth/state.ts +10 -0
  37. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  38. package/assets/templates/features/customer-profile/state.ts +18 -0
  39. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  40. package/assets/templates/views/account/assembly/assembly.json +41 -0
  41. package/assets/templates/views/account/assembly/index.skeleton.tsx +229 -0
  42. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1116 -0
  43. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  44. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  45. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  46. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  50. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/catalog.part +5 -0
  51. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/element.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/registry.part +1 -0
  53. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  56. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  63. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  67. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  70. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  73. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  76. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  79. package/assets/templates/views/account/content.ts +326 -0
  80. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  81. package/assets/templates/views/account/index.tsx +218 -35
  82. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  83. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  84. package/assets/templates/views/account/orders-advanced.client.tsx +166 -0
  85. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  86. package/assets/templates/views/account/registry.tsx +944 -369
  87. package/assets/templates/views/account/schema.ts +50 -0
  88. package/assets/templates/views/account/sections-data.ts +2 -0
  89. package/assets/templates/views/cart/content.ts +1 -0
  90. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  91. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  92. package/assets/templates/views/category/content.ts +2 -0
  93. package/assets/templates/views/category/index.tsx +2 -0
  94. package/assets/templates/views/category/sections-data.ts +2 -0
  95. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  96. package/assets/templates/views/checkout/content.ts +51 -0
  97. package/assets/templates/views/checkout/index.tsx +1 -1
  98. package/assets/templates/views/checkout/props.ts +10 -2
  99. package/assets/templates/views/checkout/registry.tsx +104 -42
  100. package/assets/templates/views/checkout/schema.ts +76 -1
  101. package/assets/templates/views/home/assembly/assembly.json +22 -1
  102. package/assets/templates/views/home/assembly/index.skeleton.tsx +1 -0
  103. package/assets/templates/views/home/content.ts +2 -0
  104. package/assets/templates/views/home/index.tsx +1 -0
  105. package/assets/templates/views/home/sections-data.ts +2 -0
  106. package/assets/templates/views/product/content.ts +1 -0
  107. package/assets/templates/views/static/content.ts +1 -0
  108. package/bin/storefront.js +343 -13
  109. package/package.json +2 -1
  110. package/recipes/adapter-surface.json +158 -0
  111. package/recipes/archetypes.json +38 -3
  112. package/recipes/catalog.json +138 -1
  113. package/recipes/feature.schema.json +9 -0
  114. package/recipes/features.json +72 -1
  115. package/recipes/manifest.schema.json +5 -0
  116. package/recipes/recipe.schema.json +13 -1
  117. package/recipes/recipes.json +34 -5
  118. package/recipes/section.schema.json +112 -0
  119. package/recipes/sections.json +281 -4
  120. package/recipes/validate.mjs +83 -1
  121. package/scripts/adapter-surface.mjs +41 -0
  122. package/scripts/agent-blocks.mjs +700 -0
  123. package/scripts/block-validator.mjs +45 -0
  124. package/scripts/candidate.mjs +5 -4
  125. package/scripts/composers.mjs +7 -2
  126. package/scripts/default-sections.mjs +78 -0
  127. package/scripts/file-classes.mjs +14 -0
  128. package/scripts/generate-adapter-surface.mjs +148 -0
  129. package/scripts/operations.mjs +100 -0
  130. package/scripts/reconcile.mjs +67 -39
  131. package/scripts/section-configure.mjs +316 -0
  132. package/scripts/sync-assets.mjs +1 -0
  133. package/scripts/view-assembly.mjs +101 -14
  134. package/skills/sf-feature/SKILL.md +19 -0
  135. package/skills/sf-view-gen/SKILL.md +73 -7
  136. package/skills/sf-view-gen/assets/recipes/archetypes.json +38 -3
  137. package/skills/sf-view-gen/assets/recipes/catalog.json +138 -1
  138. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  139. package/skills/sf-view-gen/assets/recipes/recipes.json +34 -5
  140. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  141. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  142. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  143. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  144. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  145. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  146. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  147. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  148. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  149. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  150. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  151. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
@@ -0,0 +1,1116 @@
1
+ 'use client'
2
+
3
+ // Thor Commerce view registry fragment: account
4
+ // Client boundary for the account view. Imports value bindings from
5
+ // @json-render/react and components from @thorprovider/blocks — both must stay
6
+ // on the client side of the RSC graph. Kept separate from index.tsx so the view
7
+ // spec (elements/catalog/route/loader) stays a pure Server Component module.
8
+ //
9
+ // Security invariant: the block-owned credential payload (email/password) is
10
+ // passed straight from the block callback to the Server Action and is NEVER
11
+ // written to the json-render state store, so no password reaches client state,
12
+ // HTML, or logs. Only the non-secret result (customer/error) is stored.
13
+ //
14
+ // The account modules (profile, addresses) are installed as separate features.
15
+ // Their presence flag lives in the feature's state slice, so an uninstalled
16
+ // module has no flag, no navigation entry, and performs no backend read. The
17
+ // frame owns the shape (stack/tabs) and the module navigation; tab visibility is
18
+ // runtime state so the element tree stays static and assemblable.
19
+
20
+ import { useCallback, useEffect, useRef } from 'react'
21
+ import type { ReactNode } from 'react'
22
+ import { usePathname, useRouter } from 'next/navigation'
23
+ import { Button } from '@thorprovider/blocks/ui/button'
24
+ import {
25
+ AccountFrame as AccountFrameBlock,
26
+ AddressBook as AddressBookBlock,
27
+ AddressForm as AddressFormBlock,
28
+ CustomerAccountOverview as AccountOverviewBlock,
29
+ CustomerAccountPlaceholder as ModulePlaceholderBlock,
30
+ CustomerAccountV1 as AccountShellBlock,
31
+ LoginPage as LoginPageBlock,
32
+ OrderHistory as OrderHistoryBlock,
33
+ ProfileForm as ProfileFormBlock,
34
+ SignUpPage1 as SignUpBlock,
35
+ formatMoney,
36
+ } from '@thorprovider/blocks'
37
+ import type {
38
+ AddressBookLabels,
39
+ CustomerAccountOverviewProps,
40
+ CustomerAccountPlaceholderProps,
41
+ CustomerAccountV1Props,
42
+ OrderHistoryLabels,
43
+ OrderHistoryOrder,
44
+ OrderHistoryStatusTone,
45
+ } from '@thorprovider/blocks'
46
+ @@BLOCK_IMPORTS@@
47
+ import { useStateStore } from '@json-render/react'
48
+ import type { Customer } from '@thorprovider/types'
49
+ import {
50
+ createAccountAddressAction,
51
+ deleteAccountAddressAction,
52
+ loadAccountAddressesAction,
53
+ loadOrdersPageAction,
54
+ setDefaultAccountAddressAction,
55
+ updateAccountAddressAction,
56
+ updateAccountProfileAction,
57
+ } from '../../actions'
58
+ import { ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE, accountIdentityKey, buildAccountProfileFields, isAccountModuleVisible } from '../../account-private.core'
59
+ import { AccountBoundary } from '../../account-boundary.client'
60
+ import { useAccountLifecycle } from '../../account-lifecycle.client'
61
+ import type { AccountAddressView, AccountOrderView } from '../../state.core'
62
+ import type { ViewRegistry } from '../types'
63
+ import { accountContent } from './content'
64
+ import { AccountOrderDetailPanel } from './order-detail.client'
65
+ import {
66
+ accountAddressPropsSchema,
67
+ accountFramePropsSchema,
68
+ accountLoginPropsSchema,
69
+ accountOrdersPropsSchema,
70
+ accountProfilePropsSchema,
71
+ accountRegisterPropsSchema,
72
+ } from './schema'
73
+
74
+ /** Bounded page size for the account order-history window. */
75
+ const ORDERS_PAGE_SIZE = ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE
76
+
77
+ type PanelProps = {
78
+ props: Record<string, unknown>
79
+ emit: (event: string) => void
80
+ }
81
+
82
+ type AccountState = Record<string, unknown>
83
+
84
+ // The installed account modules, in render order. `orders` is part of the auth
85
+ // host; `profile` and `addresses` exist only when their feature is installed
86
+ // (the presence flag comes from the feature state slice).
87
+ function installedModules(state: AccountState): { id: string; label: string }[] {
88
+ const modules = [{ id: 'orders', label: accountContent.modules.orders }]
89
+ if (state.accountProfileAvailable === true) {
90
+ modules.push({ id: 'profile', label: accountContent.modules.profile })
91
+ }
92
+ if (state.accountAddressesAvailable === true) {
93
+ modules.push({ id: 'addresses', label: accountContent.modules.addresses })
94
+ }
95
+ return modules
96
+ }
97
+
98
+ const SHELL_OVERVIEW_ID = 'overview'
99
+ const SHELL_FAVORITES_ID = 'lists'
100
+
101
+ // `views/account/content.ts` is user-owned and is never rewritten by sync. An
102
+ // existing store therefore has no shell keys when this registry lands; the
103
+ // defaults keep the cutover from crashing and can be overridden per store.
104
+ const SHELL_DEFAULTS = {
105
+ shell: {
106
+ loading: 'Cargando tu cuenta…',
107
+ retry: 'Reintentar',
108
+ reference: 'Referencia: {reference}',
109
+ backToAccount: 'Mi cuenta',
110
+ errorTitle: 'No pudimos cargar tu cuenta',
111
+ errorBody: 'Vuelve a intentarlo en unos segundos.',
112
+ header: {
113
+ greeting: 'Hola, {name}',
114
+ signOut: 'Cerrar sesión',
115
+ verified: 'Correo verificado',
116
+ memberSince: 'Cliente desde {date}',
117
+ },
118
+ },
119
+ overview: {
120
+ sections: 'Secciones de tu cuenta',
121
+ },
122
+ placeholder: {
123
+ badge: 'Próximamente',
124
+ upcoming: 'Qué encontrarás aquí',
125
+ },
126
+ shellModules: {
127
+ overview: {
128
+ label: 'Mi cuenta',
129
+ description: 'Todas las secciones de tu cuenta en un solo lugar.',
130
+ },
131
+ orders: {
132
+ label: 'Mis pedidos',
133
+ description: 'Consulta tus compras, entregas y devoluciones.',
134
+ },
135
+ profile: {
136
+ label: 'Mi perfil',
137
+ description: 'Administra tus datos personales y de contacto.',
138
+ },
139
+ addresses: {
140
+ label: 'Direcciones',
141
+ description: 'Administra tus direcciones de envío y facturación.',
142
+ },
143
+ favorites: {
144
+ label: 'Listas de compras',
145
+ description: 'Guarda productos para comprarlos después.',
146
+ planned: [
147
+ 'Listas con nombre y productos guardados',
148
+ 'Mover productos a la cesta',
149
+ 'Listas compartidas cuando la tienda lo permita',
150
+ ],
151
+ note: 'Se activa cuando las listas de compras están habilitadas.',
152
+ },
153
+ },
154
+ shellCards: {
155
+ orders: {
156
+ description: 'Consulta tus compras, entregas y devoluciones.',
157
+ },
158
+ profile: {
159
+ description: 'Administra tus datos personales y de contacto.',
160
+ },
161
+ addresses: {
162
+ description: 'Administra tus direcciones de envío y facturación.',
163
+ },
164
+ favorites: {
165
+ description: 'Guarda productos para comprarlos después.',
166
+ },
167
+ },
168
+ }
169
+
170
+ type ShellContent = typeof SHELL_DEFAULTS
171
+
172
+ const accountContentCompat = accountContent as typeof accountContent & Partial<ShellContent>
173
+ const shellContent = {
174
+ shell: {
175
+ ...SHELL_DEFAULTS.shell,
176
+ ...(accountContentCompat.shell ?? {}),
177
+ header: {
178
+ ...SHELL_DEFAULTS.shell.header,
179
+ ...(accountContentCompat.shell?.header ?? {}),
180
+ },
181
+ },
182
+ overview: {
183
+ ...SHELL_DEFAULTS.overview,
184
+ ...(accountContentCompat.overview ?? {}),
185
+ },
186
+ placeholder: {
187
+ ...SHELL_DEFAULTS.placeholder,
188
+ ...(accountContentCompat.placeholder ?? {}),
189
+ },
190
+ shellModules: {
191
+ overview: {
192
+ ...SHELL_DEFAULTS.shellModules.overview,
193
+ ...(accountContentCompat.shellModules?.overview ?? {}),
194
+ },
195
+ orders: {
196
+ ...SHELL_DEFAULTS.shellModules.orders,
197
+ ...(accountContentCompat.shellModules?.orders ?? {}),
198
+ },
199
+ profile: {
200
+ ...SHELL_DEFAULTS.shellModules.profile,
201
+ ...(accountContentCompat.shellModules?.profile ?? {}),
202
+ },
203
+ addresses: {
204
+ ...SHELL_DEFAULTS.shellModules.addresses,
205
+ ...(accountContentCompat.shellModules?.addresses ?? {}),
206
+ },
207
+ favorites: {
208
+ ...SHELL_DEFAULTS.shellModules.favorites,
209
+ ...(accountContentCompat.shellModules?.favorites ?? {}),
210
+ },
211
+ },
212
+ shellCards: {
213
+ orders: {
214
+ ...SHELL_DEFAULTS.shellCards.orders,
215
+ ...(accountContentCompat.shellCards?.orders ?? {}),
216
+ },
217
+ profile: {
218
+ ...SHELL_DEFAULTS.shellCards.profile,
219
+ ...(accountContentCompat.shellCards?.profile ?? {}),
220
+ },
221
+ addresses: {
222
+ ...SHELL_DEFAULTS.shellCards.addresses,
223
+ ...(accountContentCompat.shellCards?.addresses ?? {}),
224
+ },
225
+ favorites: {
226
+ ...SHELL_DEFAULTS.shellCards.favorites,
227
+ ...(accountContentCompat.shellCards?.favorites ?? {}),
228
+ },
229
+ },
230
+ }
231
+
232
+ function shellCapabilities(state: AccountState): CustomerAccountV1Props['context']['capabilities'] {
233
+ return {
234
+ orderHistory: state.accountAuthenticated === true,
235
+ profile: state.accountProfileAvailable === true,
236
+ addressBook: state.accountAddressesAvailable === true,
237
+ // The planner entry is explicit: the card opens a documented placeholder,
238
+ // never a fake favorites list.
239
+ shoppingLists: true,
240
+ }
241
+ }
242
+
243
+ function shellModules(): CustomerAccountV1Props['context']['modules'] {
244
+ return [
245
+ {
246
+ id: SHELL_OVERVIEW_ID,
247
+ label: shellContent.shellModules.overview.label,
248
+ status: 'ready',
249
+ description: shellContent.shellModules.overview.description,
250
+ planned: [],
251
+ },
252
+ {
253
+ id: 'orders',
254
+ label: shellContent.shellModules.orders.label,
255
+ status: 'ready',
256
+ capability: 'orderHistory',
257
+ description: shellContent.shellModules.orders.description,
258
+ planned: [],
259
+ },
260
+ {
261
+ id: 'profile',
262
+ label: shellContent.shellModules.profile.label,
263
+ status: 'ready',
264
+ capability: 'profile',
265
+ description: shellContent.shellModules.profile.description,
266
+ planned: [],
267
+ },
268
+ {
269
+ id: 'addresses',
270
+ label: shellContent.shellModules.addresses.label,
271
+ status: 'ready',
272
+ capability: 'addressBook',
273
+ description: shellContent.shellModules.addresses.description,
274
+ planned: [],
275
+ },
276
+ {
277
+ id: SHELL_FAVORITES_ID,
278
+ label: shellContent.shellModules.favorites.label,
279
+ status: 'planned',
280
+ capability: 'shoppingLists',
281
+ description: shellContent.shellModules.favorites.description,
282
+ planned: shellContent.shellModules.favorites.planned,
283
+ ...(shellContent.shellModules.favorites.note === undefined
284
+ ? {}
285
+ : { note: shellContent.shellModules.favorites.note }),
286
+ },
287
+ ]
288
+ }
289
+
290
+ function shellCards(): CustomerAccountOverviewProps['model']['cards'] {
291
+ return [
292
+ {
293
+ id: 'orders',
294
+ title: shellContent.shellModules.orders.label,
295
+ description: shellContent.shellCards.orders.description,
296
+ icon: 'orders',
297
+ capability: 'orderHistory',
298
+ order: 1,
299
+ },
300
+ {
301
+ id: 'profile',
302
+ title: shellContent.shellModules.profile.label,
303
+ description: shellContent.shellCards.profile.description,
304
+ icon: 'profile',
305
+ capability: 'profile',
306
+ order: 2,
307
+ },
308
+ {
309
+ id: 'addresses',
310
+ title: shellContent.shellModules.addresses.label,
311
+ description: shellContent.shellCards.addresses.description,
312
+ icon: 'addresses',
313
+ capability: 'addressBook',
314
+ order: 3,
315
+ },
316
+ {
317
+ id: SHELL_FAVORITES_ID,
318
+ title: shellContent.shellModules.favorites.label,
319
+ description: shellContent.shellCards.favorites.description,
320
+ icon: 'lists',
321
+ capability: 'shoppingLists',
322
+ order: 4,
323
+ },
324
+ ]
325
+ }
326
+
327
+ function shellModuleRoute(moduleId: string): string {
328
+ switch (moduleId) {
329
+ case 'orders':
330
+ return '/account/orders'
331
+ case 'profile':
332
+ return '/account/profile'
333
+ case 'addresses':
334
+ return '/account/addresses'
335
+ case SHELL_FAVORITES_ID:
336
+ return '/account/favorites'
337
+ default:
338
+ return '/account'
339
+ }
340
+ }
341
+
342
+ function shellActiveModule(pathname: string): string {
343
+ if (pathname === '/account/orders' || pathname.startsWith('/account/orders/')) {
344
+ return 'orders'
345
+ }
346
+ if (pathname === '/account/profile') return 'profile'
347
+ if (pathname === '/account/addresses') return 'addresses'
348
+ if (pathname === '/account/favorites') return SHELL_FAVORITES_ID
349
+ return SHELL_OVERVIEW_ID
350
+ }
351
+
352
+ function shellCustomer(customer: Customer): CustomerAccountV1Props['context']['customer'] {
353
+ const name =
354
+ [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.email
355
+ const initials =
356
+ name
357
+ .split(/\s+/)
358
+ .filter(Boolean)
359
+ .slice(0, 2)
360
+ .map((part) => part[0])
361
+ .join('')
362
+ .toUpperCase() || customer.email.slice(0, 2).toUpperCase()
363
+ return {
364
+ name,
365
+ email: customer.email,
366
+ initials,
367
+ ...(customer.phone ? { phone: customer.phone } : {}),
368
+ }
369
+ }
370
+
371
+ function shellState(state: AccountState): CustomerAccountV1Props['state'] {
372
+ if (state.accountReconciling === true) return { status: 'loading' }
373
+ if (state.accountResolution === 'unavailable') {
374
+ return {
375
+ status: 'error',
376
+ title: shellContent.shell.errorTitle,
377
+ message: shellContent.shell.errorBody,
378
+ }
379
+ }
380
+ return { status: 'ready' }
381
+ }
382
+
383
+ type ShellPanelProps = PanelProps & { children?: ReactNode }
384
+
385
+ function AccountShellPanel({ children }: ShellPanelProps) {
386
+ const { state } = useStateStore()
387
+ const pathname = usePathname()
388
+ const router = useRouter()
389
+ const lifecycle = useAccountLifecycle()
390
+ const customer = (state.accountCustomer ?? null) as Customer | null
391
+ const wrapperRef = useRef<HTMLDivElement | null>(null)
392
+
393
+ // A route change remounts the shell, so its own module-change focus effect
394
+ // cannot run. Focus the shell content region after a module route renders;
395
+ // the overview route restores focus to its originating card instead.
396
+ useEffect(() => {
397
+ if (pathname === '/account') return
398
+ const frame = requestAnimationFrame(() => {
399
+ wrapperRef.current
400
+ ?.querySelector<HTMLElement>('[role="region"][tabindex="-1"]')
401
+ ?.focus()
402
+ })
403
+ return () => cancelAnimationFrame(frame)
404
+ }, [pathname])
405
+
406
+ if (!state.accountAuthenticated || !customer) return null
407
+
408
+ return (
409
+ <div
410
+ ref={wrapperRef}
411
+ className="mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8"
412
+ >
413
+ <AccountShellBlock
414
+ context={{
415
+ customer: shellCustomer(customer),
416
+ capabilities: shellCapabilities(state),
417
+ modules: shellModules(),
418
+ activeModuleId: shellActiveModule(pathname),
419
+ locale: 'es-ES',
420
+ currency: 'EUR',
421
+ }}
422
+ labels={shellContent.shell}
423
+ state={shellState(state)}
424
+ lang="es"
425
+ onModuleSelect={(moduleId) => router.push(shellModuleRoute(moduleId))}
426
+ onSignOut={() => void lifecycle.logout()}
427
+ onRetry={() => void lifecycle.retryResolution()}
428
+ >
429
+ {children}
430
+ </AccountShellBlock>
431
+ </div>
432
+ )
433
+ }
434
+
435
+ function AccountOverviewPanel() {
436
+ const { state } = useStateStore()
437
+ const pathname = usePathname()
438
+ const router = useRouter()
439
+
440
+ useEffect(() => {
441
+ if (pathname !== '/account') return
442
+ const originCard = sessionStorage.getItem('account:origin-card')
443
+ if (!originCard) return
444
+ const frame = requestAnimationFrame(() => {
445
+ document.querySelector<HTMLElement>(`[data-module-id="${originCard}"]`)?.focus()
446
+ sessionStorage.removeItem('account:origin-card')
447
+ })
448
+ return () => cancelAnimationFrame(frame)
449
+ }, [pathname])
450
+
451
+ if (!state.accountAuthenticated) return null
452
+ return (
453
+ <AccountOverviewBlock
454
+ title={shellContent.shellModules.overview.label}
455
+ model={{ cards: shellCards(), summaries: {}, notice: null }}
456
+ capabilities={shellCapabilities(state)}
457
+ labels={{ sections: shellContent.overview.sections }}
458
+ onOpenCard={(cardId) => {
459
+ sessionStorage.setItem('account:origin-card', cardId)
460
+ router.push(shellModuleRoute(cardId))
461
+ }}
462
+ />
463
+ )
464
+ }
465
+
466
+ function AccountModulePlaceholderPanel() {
467
+ const { state } = useStateStore()
468
+ if (!state.accountAuthenticated) return null
469
+ const module = shellModules().find((entry) => entry.id === SHELL_FAVORITES_ID)
470
+ if (!module) return null
471
+ const labels: CustomerAccountPlaceholderProps['labels'] = shellContent.placeholder
472
+ return <ModulePlaceholderBlock module={module} labels={labels} />
473
+ }
474
+
475
+ // Tab visibility is runtime state: the element tree stays static, and only the
476
+ // frame decides which module is current. In the stacked shape every installed
477
+ // module renders in order.
478
+ function useModuleVisible(id: string): boolean {
479
+ const { state } = useStateStore()
480
+ return isAccountModuleVisible(
481
+ typeof state.accountShape === 'string' ? state.accountShape : null,
482
+ typeof state.accountTab === 'string' ? state.accountTab : null,
483
+ id,
484
+ )
485
+ }
486
+
487
+ // Non-secret status surface for the block pages, which expose no error/pending
488
+ // prop of their own. Renders nothing when there is no pending work or error.
489
+ function AuthNotice({ pending, error }: { pending: boolean; error: string | null }) {
490
+ if (!pending && !error) return null
491
+ return (
492
+ <div
493
+ role="alert"
494
+ aria-live="polite"
495
+ className="bg-background text-foreground fixed inset-x-0 top-4 z-50 mx-auto w-fit max-w-md rounded-md border px-4 py-2 text-center text-sm shadow-lg"
496
+ >
497
+ {pending ? 'Procesando…' : error}
498
+ </div>
499
+ )
500
+ }
501
+
502
+ // The page side of the auth contract. The blocks render only the form: the page
503
+ // — not the block — owns the viewport. This wrapper keeps the shopper-visible
504
+ // result of every auth surface unchanged and stays theme-driven.
505
+ function AuthCanvas({ stack = false, children }: { stack?: boolean; children: ReactNode }) {
506
+ return (
507
+ <section
508
+ className={`from-background to-muted/50 relative isolate flex min-h-dvh w-full items-center justify-center overflow-hidden bg-linear-to-br ${stack ? 'flex-col' : ''}`}
509
+ >
510
+ <div
511
+ className={`relative z-10 container mx-auto flex min-h-dvh items-center justify-center px-4 py-12 ${stack ? 'flex-col' : ''}`}
512
+ >
513
+ {children}
514
+ </div>
515
+ </section>
516
+ )
517
+ }
518
+
519
+ // Neutral pending surface shown while a cross-tab/foreground reconciliation is in
520
+ // flight. It replaces the previously held identity/orders so no stale private
521
+ // data is presented as current during the server round-trip.
522
+ function ReconcilingStatus() {
523
+ return (
524
+ <p
525
+ role="status"
526
+ aria-live="polite"
527
+ data-account-reconciling="1"
528
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
529
+ >
530
+ Actualizando tu cuenta…
531
+ </p>
532
+ )
533
+ }
534
+
535
+ // Backend order status → badge tone. The status model belongs to the host (the
536
+ // block never compares a status string), so this map is the storefront's own
537
+ // vocabulary; an unknown status keeps the neutral tone and its own label.
538
+ const ORDER_STATUS_TONES: Record<string, OrderHistoryStatusTone> = {
539
+ pending: 'outline',
540
+ processing: 'secondary',
541
+ completed: 'default',
542
+ cancelled: 'destructive',
543
+ refunded: 'outline',
544
+ }
545
+
546
+ function toOrderHistoryOrder(order: AccountOrderView): OrderHistoryOrder {
547
+ return {
548
+ id: order.id,
549
+ number: order.number,
550
+ date: order.date,
551
+ status: {
552
+ label: order.status,
553
+ tone: ORDER_STATUS_TONES[order.status] ?? 'secondary',
554
+ },
555
+ total: order.total,
556
+ items: order.items.map((item) => ({
557
+ id: item.id,
558
+ name: item.name,
559
+ ...(item.image === undefined ? {} : { image: item.image }),
560
+ ...(item.variant === undefined ? {} : { details: item.variant }),
561
+ quantity: item.quantity,
562
+ lineTotal: item.lineTotal,
563
+ })),
564
+ }
565
+ }
566
+
567
+ function OrderDetail({ order, onClose }: { order: AccountOrderView; onClose: () => void }) {
568
+ const amount = (value: AccountOrderView['total']) => formatMoney(value) ?? '—'
569
+ const totals = (
570
+ [
571
+ { label: 'Subtotal', value: order.subtotal },
572
+ { label: 'Impuestos', value: order.tax },
573
+ { label: 'Envío', value: order.shipping },
574
+ { label: 'Total', value: order.total },
575
+ ] as { label: string; value?: AccountOrderView['total'] }[]
576
+ ).filter(
577
+ (row): row is { label: string; value: AccountOrderView['total'] } => row.value !== undefined,
578
+ )
579
+ return (
580
+ <div className="mx-auto w-full max-w-7xl px-4 pb-12 sm:px-6 lg:px-8">
581
+ <div className="rounded-lg border p-6">
582
+ <div className="flex items-start justify-between gap-4">
583
+ <div>
584
+ <h3 className="text-lg font-semibold">Pedido {order.number}</h3>
585
+ <p className="text-muted-foreground mt-1 text-sm">
586
+ {order.date} · {order.status}
587
+ </p>
588
+ </div>
589
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
590
+ Cerrar
591
+ </Button>
592
+ </div>
593
+ {order.address ? (
594
+ <p className="text-muted-foreground mt-2 text-sm">{order.address}</p>
595
+ ) : null}
596
+ <ul className="mt-4 divide-y">
597
+ {order.items.map((item) => (
598
+ <li key={item.id} className="flex items-center justify-between py-2 text-sm">
599
+ <span>
600
+ {item.name}
601
+ {item.variant ? (
602
+ <span className="text-muted-foreground"> · {item.variant}</span>
603
+ ) : null}
604
+ <span className="text-muted-foreground"> × {item.quantity}</span>
605
+ </span>
606
+ <span>{amount(item.lineTotal)}</span>
607
+ </li>
608
+ ))}
609
+ </ul>
610
+ <dl className="mt-4 space-y-1 border-t pt-4 text-sm">
611
+ {totals.map((row) => (
612
+ <div key={row.label} className="flex justify-between">
613
+ <dt className="text-muted-foreground">{row.label}</dt>
614
+ <dd>{amount(row.value)}</dd>
615
+ </div>
616
+ ))}
617
+ </dl>
618
+ </div>
619
+ </div>
620
+ )
621
+ }
622
+
623
+ function AccountLoginPanel({ props, emit }: PanelProps) {
624
+ const { state } = useStateStore()
625
+ const lifecycle = useAccountLifecycle()
626
+ const parsed = accountLoginPropsSchema.parse(props)
627
+ const error = typeof state.accountError === 'string' ? state.accountError : null
628
+ const pending = Boolean(state.accountPending)
629
+ return (
630
+ <>
631
+ <AuthNotice pending={pending} error={error} />
632
+ <AuthCanvas>
633
+ <fieldset disabled={pending} aria-busy={pending} className="contents">
634
+ <LoginPageBlock
635
+ presentation="card"
636
+ logoText={parsed.logoText}
637
+ welcomeTitleLabel={parsed.welcomeTitleLabel}
638
+ welcomeDescriptionLabel={parsed.welcomeDescriptionLabel}
639
+ emailLabel={parsed.emailLabel}
640
+ passwordLabel={parsed.passwordLabel}
641
+ signInLabel={parsed.signInLabel}
642
+ createAccountLabel={parsed.createAccountLabel}
643
+ rememberMeLabel="Recuérdame"
644
+ onSubmit={(data) => {
645
+ void lifecycle.login({ email: data.email, password: data.password })
646
+ }}
647
+ onCreateAccount={() => emit('showRegister')}
648
+ />
649
+ </fieldset>
650
+ </AuthCanvas>
651
+ </>
652
+ )
653
+ }
654
+
655
+ function AccountRegisterPanel({ props, emit }: PanelProps) {
656
+ const { state } = useStateStore()
657
+ const lifecycle = useAccountLifecycle()
658
+ const parsed = accountRegisterPropsSchema.parse(props)
659
+ const error = typeof state.accountError === 'string' ? state.accountError : null
660
+ const pending = Boolean(state.accountPending)
661
+ return (
662
+ <>
663
+ <AuthNotice pending={pending} error={error} />
664
+ <AuthCanvas stack>
665
+ <fieldset disabled={pending} aria-busy={pending} className="contents">
666
+ <SignUpBlock
667
+ logoText={parsed.logoText}
668
+ createAccountTitleLabel={parsed.createAccountTitleLabel}
669
+ createAccountDescriptionLabel={parsed.createAccountDescriptionLabel}
670
+ fullNameLabel={parsed.fullNameLabel}
671
+ emailLabel={parsed.emailLabel}
672
+ passwordLabel={parsed.passwordLabel}
673
+ createAccountLabel={parsed.createAccountLabel}
674
+ signInLabel={parsed.signInLabel}
675
+ onSubmit={(data) => {
676
+ const parts = data.fullName.trim().split(/\s+/).filter(Boolean)
677
+ void lifecycle.register({
678
+ email: data.email,
679
+ password: data.password,
680
+ firstName: parts[0] ?? '',
681
+ lastName: parts.slice(1).join(' '),
682
+ })
683
+ }}
684
+ onSignIn={() => emit('showLogin')}
685
+ />
686
+ </fieldset>
687
+ </AuthCanvas>
688
+ </>
689
+ )
690
+ }
691
+
692
+ /**
693
+ * The account frame: the signed-in identity and the module navigation. It is
694
+ * rendered only for an authenticated shopper (the element visibility gate) and
695
+ * it seeds the shape/tab state the module panels read.
696
+ */
697
+ function AccountFramePanel({ props }: PanelProps) {
698
+ const { state, set } = useStateStore()
699
+ const parsed = accountFramePropsSchema.parse(props)
700
+ const presentation = parsed.presentation ?? 'stack'
701
+ const customer = (state.accountCustomer ?? null) as Customer | null
702
+ const modules = installedModules(state)
703
+ const activeModule = typeof state.accountTab === 'string' ? state.accountTab : undefined
704
+
705
+ useEffect(() => {
706
+ if (presentation === 'tabs') {
707
+ set('/accountShape', 'tabs')
708
+ if (!modules.some((module) => module.id === activeModule)) {
709
+ set('/accountTab', modules[0]?.id ?? 'orders')
710
+ }
711
+ } else {
712
+ set('/accountShape', 'stack')
713
+ set('/accountTab', null)
714
+ }
715
+ }, [presentation, modules.length, activeModule, set])
716
+
717
+ if (!state.accountAuthenticated || !customer) return null
718
+ const displayName =
719
+ [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.email
720
+ const labels = parsed.labels ?? {}
721
+ return (
722
+ <div className="mx-auto w-full max-w-7xl px-4 pt-10 sm:px-6 lg:px-8">
723
+ <AccountFrameBlock
724
+ displayName={displayName}
725
+ {...(customer.email ? { email: customer.email } : {})}
726
+ modules={modules}
727
+ {...(activeModule ? { activeModule } : {})}
728
+ presentation={presentation}
729
+ labels={labels}
730
+ onSelectModule={(id) => set('/accountTab', id)}
731
+ />
732
+ </div>
733
+ )
734
+ }
735
+
736
+ function AccountProfilePanel({ props }: PanelProps) {
737
+ const { state, set } = useStateStore()
738
+ const parsed = accountProfilePropsSchema.parse(props)
739
+ const customer = (state.accountCustomer ?? null) as Customer | null
740
+ const visible = useModuleVisible('profile')
741
+ if (state.accountProfileAvailable !== true || !visible || !customer) return null
742
+
743
+ const pending = Boolean(state.accountProfilePending)
744
+ const error = typeof state.accountProfileError === 'string' ? state.accountProfileError : null
745
+ const emailEditable = state.accountEmailEditable === true
746
+
747
+ return (
748
+ <div className="mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8" id="account-profile">
749
+ <ProfileFormBlock
750
+ fields={buildAccountProfileFields(customer, emailEditable)}
751
+ labels={parsed.labels}
752
+ pending={pending}
753
+ error={error}
754
+ onSubmit={(values) => {
755
+ set('/accountProfilePending', true)
756
+ set('/accountProfileError', null)
757
+ void updateAccountProfileAction({
758
+ firstName: values.firstName,
759
+ lastName: values.lastName,
760
+ phone: values.phone,
761
+ ...(emailEditable && values.email !== undefined ? { email: values.email } : {}),
762
+ }).then((result) => {
763
+ set('/accountProfilePending', false)
764
+ if (result.ok) {
765
+ set('/accountCustomer', { ...customer, ...result.customer })
766
+ return
767
+ }
768
+ set('/accountProfileError', result.error)
769
+ })
770
+ }}
771
+ />
772
+ </div>
773
+ )
774
+ }
775
+
776
+ function toAddressEntry(address: AccountAddressView): {
777
+ id: string
778
+ recipientName: string
779
+ lines: string[]
780
+ isDefaultShipping?: boolean
781
+ isDefaultBilling?: boolean
782
+ } {
783
+ const lines = [
784
+ address.address1,
785
+ address.address2,
786
+ [address.city, address.province, address.postalCode].filter(Boolean).join(', '),
787
+ address.countryCode,
788
+ ].filter((line): line is string => typeof line === 'string' && line.length > 0)
789
+ return {
790
+ id: address.id,
791
+ recipientName: [address.firstName, address.lastName].filter(Boolean).join(' '),
792
+ lines,
793
+ ...(address.isDefaultShipping ? { isDefaultShipping: true } : {}),
794
+ ...(address.isDefaultBilling ? { isDefaultBilling: true } : {}),
795
+ }
796
+ }
797
+
798
+ function AccountAddressesPanel({ props }: PanelProps) {
799
+ const { state, set } = useStateStore()
800
+ const parsed = accountAddressPropsSchema.parse(props)
801
+ const { identityKey } = useAccountLifecycle()
802
+ const visible = useModuleVisible('addresses')
803
+ const available = state.accountAddressesAvailable === true
804
+ const loadedKeyRef = useRef<string | null>(null)
805
+
806
+ const addresses = Array.isArray(state.accountAddresses)
807
+ ? (state.accountAddresses as AccountAddressView[])
808
+ : []
809
+ const pending = Boolean(state.accountAddressesPending)
810
+ const error = typeof state.accountAddressesError === 'string' ? state.accountAddressesError : null
811
+ const formOpen = Boolean(state.accountAddressFormOpen)
812
+ const editingId = typeof state.accountAddressEditingId === 'string' ? state.accountAddressEditingId : null
813
+ const mutationPending = Boolean(state.accountAddressMutationPending)
814
+ const mutationError =
815
+ typeof state.accountAddressMutationError === 'string' ? state.accountAddressMutationError : null
816
+ const fieldErrors =
817
+ state.accountAddressFieldErrors && typeof state.accountAddressFieldErrors === 'object'
818
+ ? (state.accountAddressFieldErrors as Record<string, string>)
819
+ : {}
820
+
821
+ const load = useCallback(() => {
822
+ set('/accountAddressesPending', true)
823
+ set('/accountAddressesError', null)
824
+ void loadAccountAddressesAction().then((result) => {
825
+ set('/accountAddressesPending', false)
826
+ if (result.ok) {
827
+ set('/accountAddresses', result.addresses)
828
+ return
829
+ }
830
+ set('/accountAddressesError', result.error)
831
+ })
832
+ }, [set])
833
+
834
+ useEffect(() => {
835
+ if (!available || !visible) return
836
+ if (loadedKeyRef.current === identityKey) return
837
+ // A new identity reloads its own address book; the previous identity's rows
838
+ // were already cleared by the account claim write path.
839
+ loadedKeyRef.current = identityKey
840
+ load()
841
+ }, [available, visible, identityKey, load])
842
+
843
+ if (!available || !visible) return null
844
+
845
+ const editing = editingId ? addresses.find((address) => address.id === editingId) ?? null : null
846
+ const labels = (parsed.labels ?? {}) as Partial<AddressBookLabels>
847
+ const closeForm = () => {
848
+ set('/accountAddressFormOpen', false)
849
+ set('/accountAddressEditingId', null)
850
+ set('/accountAddressMutationError', null)
851
+ set('/accountAddressFieldErrors', {})
852
+ }
853
+ const applyResult = (result: { ok: true; addresses: AccountAddressView[] } | { ok: false; error: string; fieldErrors?: Record<string, string> }) => {
854
+ set('/accountAddressMutationPending', false)
855
+ if (result.ok) {
856
+ set('/accountAddresses', result.addresses)
857
+ closeForm()
858
+ return
859
+ }
860
+ set('/accountAddressMutationError', result.error)
861
+ set('/accountAddressFieldErrors', result.fieldErrors ?? {})
862
+ }
863
+ const submitForm = (values: Record<string, string>) => {
864
+ set('/accountAddressMutationPending', true)
865
+ set('/accountAddressMutationError', null)
866
+ set('/accountAddressFieldErrors', {})
867
+ const input = {
868
+ firstName: values.firstName ?? '',
869
+ lastName: values.lastName ?? '',
870
+ address1: values.address1 ?? '',
871
+ address2: values.address2,
872
+ city: values.city ?? '',
873
+ province: values.province,
874
+ postalCode: values.postalCode,
875
+ countryCode: values.countryCode ?? '',
876
+ phone: values.phone,
877
+ label: values.label,
878
+ }
879
+ const request = editingId
880
+ ? updateAccountAddressAction({ ...input, id: editingId })
881
+ : createAccountAddressAction(input)
882
+ void request.then(applyResult)
883
+ }
884
+
885
+ return (
886
+ <div className="mx-auto w-full max-w-7xl px-4 pb-12 sm:px-6 lg:px-8" id="account-addresses">
887
+ {pending ? (
888
+ <p role="status" aria-live="polite" className="text-muted-foreground py-8 text-sm">
889
+ {accountContent.addresses.loadingLabel}
890
+ </p>
891
+ ) : error ? (
892
+ <div className="flex flex-col items-start gap-3 py-8">
893
+ <p role="alert" className="text-destructive text-sm">
894
+ {error}
895
+ </p>
896
+ <Button type="button" variant="outline" size="sm" onClick={load}>
897
+ {accountContent.addresses.retryLabel}
898
+ </Button>
899
+ </div>
900
+ ) : formOpen ? (
901
+ <AddressFormBlock
902
+ fields={accountContent.addressFields.map((field) => ({
903
+ ...field,
904
+ value: editing ? (editing as unknown as Record<string, string>)[field.name] ?? '' : '',
905
+ }))}
906
+ labels={labels}
907
+ pending={mutationPending}
908
+ error={mutationError}
909
+ fieldErrors={fieldErrors}
910
+ onSubmit={submitForm}
911
+ onCancel={closeForm}
912
+ />
913
+ ) : (
914
+ <AddressBookBlock
915
+ addresses={addresses.map(toAddressEntry)}
916
+ labels={labels}
917
+ onCreate={() => {
918
+ set('/accountAddressEditingId', null)
919
+ set('/accountAddressFormOpen', true)
920
+ }}
921
+ onEdit={(id) => {
922
+ set('/accountAddressEditingId', id)
923
+ set('/accountAddressFormOpen', true)
924
+ }}
925
+ onDelete={(id) => {
926
+ set('/accountAddressMutationPending', true)
927
+ void deleteAccountAddressAction({ id }).then(applyResult)
928
+ }}
929
+ onSetDefaultShipping={(id) => {
930
+ set('/accountAddressMutationPending', true)
931
+ void setDefaultAccountAddressAction({ id, kind: 'shipping' }).then(applyResult)
932
+ }}
933
+ onSetDefaultBilling={(id) => {
934
+ set('/accountAddressMutationPending', true)
935
+ void setDefaultAccountAddressAction({ id, kind: 'billing' }).then(applyResult)
936
+ }}
937
+ />
938
+ )}
939
+ </div>
940
+ )
941
+ }
942
+
943
+ function AccountOrdersPanel({ props }: PanelProps) {
944
+ const { state, set, getSnapshot } = useStateStore()
945
+ const parsed = accountOrdersPropsSchema.parse(props)
946
+ const { identityKey, reconciling } = useAccountLifecycle()
947
+ const visible = useModuleVisible('orders')
948
+
949
+ const generationRef = useRef(0)
950
+ const loadedKeyRef = useRef<string | null>(null)
951
+ const requestedPageRef = useRef(1)
952
+
953
+ const currentIdentityKey = useCallback(
954
+ () =>
955
+ accountIdentityKey(
956
+ (getSnapshot().accountCustomer ?? null) as { id?: string | null } | null,
957
+ ),
958
+ [getSnapshot],
959
+ )
960
+
961
+ const loadPage = (page: number) => {
962
+ const capturedKey = currentIdentityKey()
963
+ const capturedGeneration = generationRef.current
964
+ requestedPageRef.current = page
965
+ set('/accountOrdersPending', true)
966
+ set('/accountOrdersError', null)
967
+ void loadOrdersPageAction({ page, pageSize: ORDERS_PAGE_SIZE })
968
+ .then((result) => {
969
+ if (
970
+ currentIdentityKey() !== capturedKey ||
971
+ generationRef.current !== capturedGeneration
972
+ ) {
973
+ return
974
+ }
975
+ set('/accountOrdersPending', false)
976
+ if (result.ok) {
977
+ set('/accountOrders', result.orders)
978
+ set('/accountOrdersCount', result.count)
979
+ set('/accountOrdersPage', page)
980
+ set('/accountOrdersPageSize', result.limit)
981
+ set('/accountOrdersError', null)
982
+ loadedKeyRef.current = capturedKey
983
+ return
984
+ }
985
+ set('/accountOrdersError', result.error)
986
+ })
987
+ .catch((error) => {
988
+ if (
989
+ currentIdentityKey() !== capturedKey ||
990
+ generationRef.current !== capturedGeneration
991
+ ) {
992
+ return
993
+ }
994
+ console.error(
995
+ '[storefront/account] loadOrders failed',
996
+ error instanceof Error ? error.message : error,
997
+ )
998
+ set('/accountOrdersPending', false)
999
+ set('/accountOrdersError', parsed.errorLabel ?? 'No se pudieron cargar tus pedidos.')
1000
+ })
1001
+ }
1002
+
1003
+ useEffect(() => {
1004
+ if (loadedKeyRef.current !== identityKey) {
1005
+ generationRef.current += 1
1006
+ loadedKeyRef.current = null
1007
+ }
1008
+ if (identityKey === 'anonymous') return
1009
+ if (loadedKeyRef.current === identityKey) return
1010
+ loadPage(1)
1011
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1012
+ }, [identityKey])
1013
+
1014
+ if (!visible) return null
1015
+
1016
+ const pending = Boolean(state.accountOrdersPending)
1017
+ const error = typeof state.accountOrdersError === 'string' ? state.accountOrdersError : null
1018
+ const allOrders = Array.isArray(state.accountOrders)
1019
+ ? (state.accountOrders as AccountOrderView[])
1020
+ : []
1021
+ const orders = loadedKeyRef.current === identityKey ? allOrders : []
1022
+ const count = typeof state.accountOrdersCount === 'number' ? state.accountOrdersCount : orders.length
1023
+ const page = typeof state.accountOrdersPage === 'number' ? state.accountOrdersPage : 1
1024
+ const pageSize =
1025
+ typeof state.accountOrdersPageSize === 'number' && state.accountOrdersPageSize > 0
1026
+ ? state.accountOrdersPageSize
1027
+ : ORDERS_PAGE_SIZE
1028
+ const selectedId =
1029
+ typeof state.accountSelectedOrderId === 'string' ? state.accountSelectedOrderId : null
1030
+ const selected = selectedId ? orders.find((order) => order.id === selectedId) ?? null : null
1031
+ const labels: Partial<OrderHistoryLabels> = {
1032
+ ...(parsed.labels ?? {}),
1033
+ ...(parsed.titleLabel === undefined ? {} : { title: parsed.titleLabel }),
1034
+ ...(parsed.descriptionLabel === undefined ? {} : { description: parsed.descriptionLabel }),
1035
+ ...(parsed.emptyLabel === undefined ? {} : { emptyLabel: parsed.emptyLabel }),
1036
+ }
1037
+
1038
+ if (reconciling) return <ReconcilingStatus />
1039
+ if (pending) {
1040
+ return (
1041
+ <p
1042
+ role="status"
1043
+ aria-live="polite"
1044
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
1045
+ >
1046
+ {parsed.loadingLabel ?? 'Cargando pedidos…'}
1047
+ </p>
1048
+ )
1049
+ }
1050
+ if (error) {
1051
+ return (
1052
+ <div className="mx-auto flex w-full max-w-7xl flex-col items-start gap-3 px-4 py-8 sm:px-6 lg:px-8">
1053
+ <p role="alert" className="text-destructive text-sm">
1054
+ {error}
1055
+ </p>
1056
+ <Button
1057
+ type="button"
1058
+ variant="outline"
1059
+ size="sm"
1060
+ disabled={pending}
1061
+ onClick={() => loadPage(requestedPageRef.current)}
1062
+ >
1063
+ Reintentar
1064
+ </Button>
1065
+ </div>
1066
+ )
1067
+ }
1068
+ const totalPages = Math.max(1, Math.ceil(count / pageSize))
1069
+ return (
1070
+ <div id="account-orders">
1071
+ <OrderHistoryBlock
1072
+ orders={orders.map(toOrderHistoryOrder)}
1073
+ presentation="cards"
1074
+ labels={labels}
1075
+ onViewOrder={(id) => set('/accountSelectedOrderId', id)}
1076
+ />
1077
+ {count > pageSize ? (
1078
+ <div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-4 px-4 pb-6 sm:px-6 lg:px-8">
1079
+ <p className="text-muted-foreground text-sm" role="status" aria-live="polite">
1080
+ {`${count} pedidos · página ${page} de ${totalPages}`}
1081
+ </p>
1082
+ <div className="flex gap-2">
1083
+ <Button
1084
+ variant="outline"
1085
+ size="sm"
1086
+ disabled={pending || page <= 1}
1087
+ onClick={() => loadPage(page - 1)}
1088
+ >
1089
+ Anterior
1090
+ </Button>
1091
+ <Button
1092
+ variant="outline"
1093
+ size="sm"
1094
+ disabled={pending || page >= totalPages}
1095
+ onClick={() => loadPage(page + 1)}
1096
+ >
1097
+ Siguiente
1098
+ </Button>
1099
+ </div>
1100
+ </div>
1101
+ ) : null}
1102
+ {selected ? (
1103
+ <OrderDetail order={selected} onClose={() => set('/accountSelectedOrderId', null)} />
1104
+ ) : null}
1105
+ </div>
1106
+ )
1107
+ }
1108
+
1109
+ export const registry: ViewRegistry = {
1110
+ AccountOrderDetail: (ctx) => <AccountOrderDetailPanel {...ctx} />,
1111
+ AccountShell: (ctx) => <AccountShellPanel {...ctx} />,
1112
+ AccountOverview: () => <AccountOverviewPanel />,
1113
+ AccountModulePlaceholder: () => <AccountModulePlaceholderPanel />,
1114
+ AccountOrders: (ctx) => <AccountOrdersPanel {...ctx} />,
1115
+ @@REGISTRY@@
1116
+ }