create-brainerce-store 1.33.2 → 1.34.2

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,528 +1,528 @@
1
- 'use client';
2
-
3
- /**
4
- * Contact form — fully driven by the merchant's dashboard configuration.
5
- *
6
- * The merchant configures the form in the Brainerce dashboard under
7
- * Customers → Contact Forms → <form>
8
- *
9
- * From there they can:
10
- * • edit the title, description, submit button label, success message
11
- * • add/remove/reorder/hide any field (TEXT/TEXTAREA/EMAIL/PHONE/NUMBER/SELECT/
12
- * MULTI_SELECT/CHECKBOX/URL/DATE)
13
- * • toggle required, set placeholder/helpText/enumValues/validation
14
- * • provide per-locale translations for every label/placeholder/helpText/successMessage
15
- * • set field width (FULL/HALF/THIRD) for multi-column layouts
16
- *
17
- * Everything below is generic rendering logic — it adapts automatically to any
18
- * form shape returned by the API, so **you should not hardcode field keys or
19
- * labels here**. If you want a different visual layout, change the markup
20
- * inside `DynamicField` (keep the behavior) and keep using `schema.fields` as
21
- * the source of truth.
22
- *
23
- * API contract the page relies on:
24
- * 1. `GET /stores/{storeId}/contact-forms/main?locale={locale}` → `ContactFormPublic`
25
- * (see `brainerce` SDK type). Server pre-resolves translations for the
26
- * requested locale and strips any field with `isVisible=false`.
27
- * 2. `POST /stores/{storeId}/inquiries` with `{ formKey, fields, locale }` →
28
- * `CreateInquiryResponse`. Unknown keys are stripped server-side.
29
- *
30
- * Rate limit: 3 submissions / 60s per IP. Honeypot field below blocks naive bots.
31
- * If the merchant has more than one form (e.g. 'main' + 'newsletter'), you can
32
- * list them via `client.contactForms.list()` and pick by `key`.
33
- */
34
-
35
- import { useEffect, useMemo, useState } from 'react';
36
- import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
37
- import { getClient } from '@/lib/brainerce';
38
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
39
- import { useTranslations } from '@/lib/translations';
40
-
41
- type FieldValue = string | string[] | boolean;
42
-
43
- function defaultValueFor(field: ContactFormPublicField): FieldValue {
44
- if (field.type === 'CHECKBOX') return false;
45
- if (field.type === 'MULTI_SELECT') return [];
46
- return field.defaultValue ?? '';
47
- }
48
-
49
- function isEmpty(v: FieldValue): boolean {
50
- if (typeof v === 'string') return v.trim().length === 0;
51
- if (Array.isArray(v)) return v.length === 0;
52
- return v === false;
53
- }
54
-
55
- /** Map field.width → Tailwind col-span utilities (6-column grid). */
56
- function widthColSpan(width?: string): string {
57
- switch (width) {
58
- case 'HALF':
59
- return 'col-span-6 sm:col-span-3';
60
- case 'THIRD':
61
- return 'col-span-6 sm:col-span-2';
62
- default:
63
- return 'col-span-6';
64
- }
65
- }
66
-
67
- const inputClass =
68
- 'border-border bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary/20 focus:border-primary h-10 w-full rounded border px-3 text-sm focus:outline-none focus:ring-2';
69
-
70
- const inputErrorClass =
71
- 'border-red-400 bg-background text-foreground placeholder:text-muted-foreground focus:ring-red-200 focus:border-red-500 h-10 w-full rounded border px-3 text-sm focus:outline-none focus:ring-2';
72
-
73
- const textareaClass =
74
- 'border-border bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary/20 focus:border-primary w-full rounded border px-3 py-2 text-sm focus:outline-none focus:ring-2';
75
-
76
- const textareaErrorClass =
77
- 'border-red-400 bg-background text-foreground placeholder:text-muted-foreground focus:ring-red-200 focus:border-red-500 w-full rounded border px-3 py-2 text-sm focus:outline-none focus:ring-2';
78
-
79
- export default function ContactPage() {
80
- const t = useTranslations('contact');
81
- const [schema, setSchema] = useState<ContactFormPublic | null>(null);
82
- const [schemaError, setSchemaError] = useState<string | null>(null);
83
- const [values, setValues] = useState<Record<string, FieldValue>>({});
84
- const [errors, setErrors] = useState<Record<string, string>>({});
85
- const [honeypot, setHoneypot] = useState('');
86
- const [loading, setLoading] = useState(false);
87
- const [sent, setSent] = useState(false);
88
- const [submitError, setSubmitError] = useState<string | null>(null);
89
-
90
- const locale = useMemo(() => {
91
- if (typeof document !== 'undefined') return document.documentElement.lang || undefined;
92
- return undefined;
93
- }, []);
94
-
95
- useEffect(() => {
96
- let cancelled = false;
97
- (async () => {
98
- try {
99
- const client = getClient();
100
- const form = await client.contactForms.get('main', locale);
101
- if (cancelled) return;
102
- setSchema(form);
103
- const initial: Record<string, FieldValue> = {};
104
- for (const field of form.fields) initial[field.key] = defaultValueFor(field);
105
- setValues(initial);
106
- } catch (err) {
107
- if (cancelled) return;
108
- setSchemaError(err instanceof Error ? err.message : t('genericError'));
109
- }
110
- })();
111
- return () => {
112
- cancelled = true;
113
- };
114
- }, [t, locale]);
115
-
116
- function updateValue(key: string, value: FieldValue) {
117
- setValues((prev) => ({ ...prev, [key]: value }));
118
- // Clear field error on input change
119
- if (errors[key]) {
120
- setErrors((prev) => {
121
- const next = { ...prev };
122
- delete next[key];
123
- return next;
124
- });
125
- }
126
- }
127
-
128
- async function handleSubmit(e: React.FormEvent) {
129
- e.preventDefault();
130
- if (loading || !schema) return;
131
-
132
- if (honeypot.trim().length > 0) {
133
- setSent(true);
134
- return;
135
- }
136
-
137
- // ── Client-side required-field validation ──
138
- const newErrors: Record<string, string> = {};
139
- for (const field of schema.fields) {
140
- if (field.isRequired && isEmpty(values[field.key] ?? defaultValueFor(field))) {
141
- newErrors[field.key] = t('fieldRequired', { label: field.label });
142
- }
143
- }
144
- if (Object.keys(newErrors).length > 0) {
145
- setErrors(newErrors);
146
- return; // block submission — do NOT send to server
147
- }
148
- setErrors({});
149
-
150
- try {
151
- setLoading(true);
152
- setSubmitError(null);
153
-
154
- const payload: Record<string, unknown> = {};
155
- for (const field of schema.fields) {
156
- const raw = values[field.key];
157
- if (isEmpty(raw)) continue;
158
- payload[field.key] = typeof raw === 'string' ? raw.trim() : raw;
159
- }
160
-
161
- await getClient().createInquiry({
162
- formKey: schema.key,
163
- fields: payload,
164
- locale,
165
- });
166
-
167
- setSent(true);
168
- const reset: Record<string, FieldValue> = {};
169
- for (const field of schema.fields) reset[field.key] = defaultValueFor(field);
170
- setValues(reset);
171
- setHoneypot('');
172
- } catch (err) {
173
- setSubmitError(err instanceof Error ? err.message : t('genericError'));
174
- } finally {
175
- setLoading(false);
176
- }
177
- }
178
-
179
- if (schemaError) {
180
- return (
181
- <div className="mx-auto max-w-2xl px-4 py-12 sm:px-6 lg:px-8">
182
- <div className="bg-destructive/10 border-destructive/20 text-destructive rounded-lg border px-4 py-3 text-sm">
183
- {schemaError}
184
- </div>
185
- </div>
186
- );
187
- }
188
-
189
- if (!schema) {
190
- return (
191
- <div className="mx-auto flex max-w-2xl items-center justify-center px-4 py-24 sm:px-6 lg:px-8">
192
- <LoadingSpinner />
193
- </div>
194
- );
195
- }
196
-
197
- return (
198
- <div className="mx-auto max-w-2xl px-4 py-12 sm:px-6 lg:px-8">
199
- <div className="mb-8 text-center">
200
- <h1 className="text-foreground text-3xl font-bold">{schema.name || t('title')}</h1>
201
- {schema.description ? (
202
- <p className="text-muted-foreground mt-2 text-sm">{schema.description}</p>
203
- ) : (
204
- <p className="text-muted-foreground mt-2 text-sm">{t('subtitle')}</p>
205
- )}
206
- </div>
207
-
208
- {submitError && (
209
- <div className="bg-destructive/10 border-destructive/20 text-destructive mb-6 rounded-lg border px-4 py-3 text-sm">
210
- {submitError}
211
- </div>
212
- )}
213
-
214
- {sent ? (
215
- <div className="rounded-lg border border-green-200 bg-green-50 px-4 py-6 text-center text-sm text-green-800 dark:border-green-800 dark:bg-green-950/30 dark:text-green-300">
216
- <p className="font-medium">{t('thanksTitle')}</p>
217
- <p className="mt-1">{schema.successMessage || t('thanksBody')}</p>
218
- <button
219
- type="button"
220
- onClick={() => setSent(false)}
221
- className="text-primary mt-4 text-sm font-medium hover:underline"
222
- >
223
- {t('sendAnother')}
224
- </button>
225
- </div>
226
- ) : (
227
- <form onSubmit={handleSubmit} className="space-y-2" noValidate>
228
- <div
229
- aria-hidden="true"
230
- className="pointer-events-none absolute -start-[10000px] h-0 w-0 overflow-hidden"
231
- >
232
- <label htmlFor="contact-honeypot">Leave this field empty</label>
233
- <input
234
- id="contact-honeypot"
235
- type="text"
236
- tabIndex={-1}
237
- autoComplete="off"
238
- value={honeypot}
239
- onChange={(e) => setHoneypot(e.target.value)}
240
- />
241
- </div>
242
-
243
- {/* 6-column grid — FULL=span 6, HALF=span 3, THIRD=span 2; stacks on mobile */}
244
- <div className="grid grid-cols-6 gap-4">
245
- {schema.fields.map((field) => (
246
- <DynamicField
247
- key={field.key}
248
- field={field}
249
- value={values[field.key] ?? defaultValueFor(field)}
250
- error={errors[field.key]}
251
- onChange={(v) => updateValue(field.key, v)}
252
- t={t}
253
- />
254
- ))}
255
- </div>
256
-
257
- <button
258
- type="submit"
259
- disabled={loading}
260
- className="bg-primary text-primary-foreground flex h-10 w-full items-center justify-center gap-2 rounded text-sm font-medium transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
261
- >
262
- {loading ? (
263
- <>
264
- <LoadingSpinner
265
- size="sm"
266
- className="border-primary-foreground/30 border-t-primary-foreground"
267
- />
268
- {t('sending')}
269
- </>
270
- ) : (
271
- schema.submitButton || t('send')
272
- )}
273
- </button>
274
- </form>
275
- )}
276
- </div>
277
- );
278
- }
279
-
280
- function DynamicField({
281
- field,
282
- value,
283
- error,
284
- onChange,
285
- t,
286
- }: {
287
- field: ContactFormPublicField;
288
- value: FieldValue;
289
- error?: string;
290
- onChange: (v: FieldValue) => void;
291
- t: (key: string, values?: Record<string, string>) => string;
292
- }) {
293
- const id = `contact-${field.key}`;
294
- const hasError = !!error;
295
- const label = (
296
- <label htmlFor={id} className="text-foreground mb-1.5 block text-sm font-medium">
297
- {field.label}
298
- {field.isRequired ? (
299
- <span className="text-red-500 ms-0.5" aria-hidden>*</span>
300
- ) : (
301
- <span className="text-muted-foreground ms-1">({t('optional')})</span>
302
- )}
303
- </label>
304
- );
305
- const help = field.helpText ? (
306
- <p className="text-muted-foreground mt-1 text-xs">{field.helpText}</p>
307
- ) : null;
308
- const errorEl = error ? (
309
- <p className="text-red-500 mt-1 text-xs">{error}</p>
310
- ) : null;
311
-
312
- const maxLength = field.validation?.maxLength;
313
- const minLength = field.validation?.minLength;
314
- const min = field.validation?.min;
315
- const max = field.validation?.max;
316
- const pattern = field.validation?.pattern;
317
- const strVal = typeof value === 'string' ? value : '';
318
- const iClass = hasError ? inputErrorClass : inputClass;
319
- const tClass = hasError ? textareaErrorClass : textareaClass;
320
-
321
- switch (field.type) {
322
- case 'TEXTAREA':
323
- return (
324
- <div className={widthColSpan(field.width)}>
325
- {label}
326
- <textarea
327
- id={id}
328
- required={field.isRequired}
329
- maxLength={maxLength}
330
- minLength={minLength}
331
- rows={6}
332
- placeholder={field.placeholder}
333
- value={strVal}
334
- onChange={(e) => onChange(e.target.value)}
335
- className={tClass}
336
- />
337
- {help}
338
- {errorEl}
339
- </div>
340
- );
341
-
342
- case 'SELECT':
343
- return (
344
- <div className={widthColSpan(field.width)}>
345
- {label}
346
- <select
347
- id={id}
348
- required={field.isRequired}
349
- value={strVal}
350
- onChange={(e) => onChange(e.target.value)}
351
- className={iClass}
352
- >
353
- <option value="">—</option>
354
- {field.enumValues?.map((opt) => (
355
- <option key={opt.value} value={opt.value}>
356
- {opt.label}
357
- </option>
358
- ))}
359
- </select>
360
- {help}
361
- {errorEl}
362
- </div>
363
- );
364
-
365
- case 'MULTI_SELECT': {
366
- const arr = Array.isArray(value) ? value : [];
367
- return (
368
- <div className={widthColSpan(field.width)}>
369
- {label}
370
- <div className="space-y-2">
371
- {field.enumValues?.map((opt) => {
372
- const checked = arr.includes(opt.value);
373
- return (
374
- <label key={opt.value} className="flex items-center gap-2 text-sm">
375
- <input
376
- type="checkbox"
377
- checked={checked}
378
- onChange={(e) => {
379
- if (e.target.checked) onChange([...arr, opt.value]);
380
- else onChange(arr.filter((v) => v !== opt.value));
381
- }}
382
- />
383
- <span>{opt.label}</span>
384
- </label>
385
- );
386
- })}
387
- </div>
388
- {help}
389
- {errorEl}
390
- </div>
391
- );
392
- }
393
-
394
- case 'CHECKBOX':
395
- return (
396
- <div className={widthColSpan(field.width)}>
397
- <label htmlFor={id} className="flex items-start gap-2 text-sm">
398
- <input
399
- id={id}
400
- type="checkbox"
401
- required={field.isRequired}
402
- checked={value === true}
403
- onChange={(e) => onChange(e.target.checked)}
404
- className="mt-0.5"
405
- />
406
- <span className="text-foreground">{field.label}</span>
407
- </label>
408
- {help}
409
- {errorEl}
410
- </div>
411
- );
412
-
413
- case 'NUMBER':
414
- return (
415
- <div className={widthColSpan(field.width)}>
416
- {label}
417
- <input
418
- id={id}
419
- type="number"
420
- required={field.isRequired}
421
- min={min}
422
- max={max}
423
- placeholder={field.placeholder}
424
- value={strVal}
425
- onChange={(e) => onChange(e.target.value)}
426
- className={iClass}
427
- />
428
- {help}
429
- {errorEl}
430
- </div>
431
- );
432
-
433
- case 'EMAIL':
434
- return (
435
- <div className={widthColSpan(field.width)}>
436
- {label}
437
- <input
438
- id={id}
439
- type="email"
440
- required={field.isRequired}
441
- autoComplete="email"
442
- placeholder={field.placeholder}
443
- value={strVal}
444
- onChange={(e) => onChange(e.target.value)}
445
- className={iClass}
446
- />
447
- {help}
448
- {errorEl}
449
- </div>
450
- );
451
-
452
- case 'PHONE':
453
- return (
454
- <div className={widthColSpan(field.width)}>
455
- {label}
456
- <input
457
- id={id}
458
- type="tel"
459
- required={field.isRequired}
460
- autoComplete="tel"
461
- placeholder={field.placeholder}
462
- value={strVal}
463
- onChange={(e) => onChange(e.target.value)}
464
- className={iClass}
465
- />
466
- {help}
467
- {errorEl}
468
- </div>
469
- );
470
-
471
- case 'URL':
472
- return (
473
- <div className={widthColSpan(field.width)}>
474
- {label}
475
- <input
476
- id={id}
477
- type="url"
478
- required={field.isRequired}
479
- placeholder={field.placeholder}
480
- value={strVal}
481
- onChange={(e) => onChange(e.target.value)}
482
- className={iClass}
483
- />
484
- {help}
485
- {errorEl}
486
- </div>
487
- );
488
-
489
- case 'DATE':
490
- return (
491
- <div className={widthColSpan(field.width)}>
492
- {label}
493
- <input
494
- id={id}
495
- type="date"
496
- required={field.isRequired}
497
- value={strVal}
498
- onChange={(e) => onChange(e.target.value)}
499
- className={iClass}
500
- />
501
- {help}
502
- {errorEl}
503
- </div>
504
- );
505
-
506
- case 'TEXT':
507
- default:
508
- return (
509
- <div className={widthColSpan(field.width)}>
510
- {label}
511
- <input
512
- id={id}
513
- type="text"
514
- required={field.isRequired}
515
- maxLength={maxLength}
516
- minLength={minLength}
517
- pattern={pattern}
518
- placeholder={field.placeholder}
519
- value={strVal}
520
- onChange={(e) => onChange(e.target.value)}
521
- className={iClass}
522
- />
523
- {help}
524
- {errorEl}
525
- </div>
526
- );
527
- }
528
- }
1
+ 'use client';
2
+
3
+ /**
4
+ * Contact form — fully driven by the merchant's dashboard configuration.
5
+ *
6
+ * The merchant configures the form in the Brainerce dashboard under
7
+ * Customers → Contact Forms → <form>
8
+ *
9
+ * From there they can:
10
+ * • edit the title, description, submit button label, success message
11
+ * • add/remove/reorder/hide any field (TEXT/TEXTAREA/EMAIL/PHONE/NUMBER/SELECT/
12
+ * MULTI_SELECT/CHECKBOX/URL/DATE)
13
+ * • toggle required, set placeholder/helpText/enumValues/validation
14
+ * • provide per-locale translations for every label/placeholder/helpText/successMessage
15
+ * • set field width (FULL/HALF/THIRD) for multi-column layouts
16
+ *
17
+ * Everything below is generic rendering logic — it adapts automatically to any
18
+ * form shape returned by the API, so **you should not hardcode field keys or
19
+ * labels here**. If you want a different visual layout, change the markup
20
+ * inside `DynamicField` (keep the behavior) and keep using `schema.fields` as
21
+ * the source of truth.
22
+ *
23
+ * API contract the page relies on:
24
+ * 1. `GET /stores/{storeId}/contact-forms/main?locale={locale}` → `ContactFormPublic`
25
+ * (see `brainerce` SDK type). Server pre-resolves translations for the
26
+ * requested locale and strips any field with `isVisible=false`.
27
+ * 2. `POST /stores/{storeId}/inquiries` with `{ formKey, fields, locale }` →
28
+ * `CreateInquiryResponse`. Unknown keys are stripped server-side.
29
+ *
30
+ * Rate limit: 3 submissions / 60s per IP. Honeypot field below blocks naive bots.
31
+ * If the merchant has more than one form (e.g. 'main' + 'newsletter'), you can
32
+ * list them via `client.contactForms.list()` and pick by `key`.
33
+ */
34
+
35
+ import { useEffect, useMemo, useState } from 'react';
36
+ import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
37
+ import { getClient } from '@/lib/brainerce';
38
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
39
+ import { useTranslations } from '@/lib/translations';
40
+
41
+ type FieldValue = string | string[] | boolean;
42
+
43
+ function defaultValueFor(field: ContactFormPublicField): FieldValue {
44
+ if (field.type === 'CHECKBOX') return false;
45
+ if (field.type === 'MULTI_SELECT') return [];
46
+ return field.defaultValue ?? '';
47
+ }
48
+
49
+ function isEmpty(v: FieldValue): boolean {
50
+ if (typeof v === 'string') return v.trim().length === 0;
51
+ if (Array.isArray(v)) return v.length === 0;
52
+ return v === false;
53
+ }
54
+
55
+ /** Map field.width → Tailwind col-span utilities (6-column grid). */
56
+ function widthColSpan(width?: string): string {
57
+ switch (width) {
58
+ case 'HALF':
59
+ return 'col-span-6 sm:col-span-3';
60
+ case 'THIRD':
61
+ return 'col-span-6 sm:col-span-2';
62
+ default:
63
+ return 'col-span-6';
64
+ }
65
+ }
66
+
67
+ const inputClass =
68
+ 'border-border bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary/20 focus:border-primary h-10 w-full rounded border px-3 text-sm focus:outline-none focus:ring-2';
69
+
70
+ const inputErrorClass =
71
+ 'border-red-400 bg-background text-foreground placeholder:text-muted-foreground focus:ring-red-200 focus:border-red-500 h-10 w-full rounded border px-3 text-sm focus:outline-none focus:ring-2';
72
+
73
+ const textareaClass =
74
+ 'border-border bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary/20 focus:border-primary w-full rounded border px-3 py-2 text-sm focus:outline-none focus:ring-2';
75
+
76
+ const textareaErrorClass =
77
+ 'border-red-400 bg-background text-foreground placeholder:text-muted-foreground focus:ring-red-200 focus:border-red-500 w-full rounded border px-3 py-2 text-sm focus:outline-none focus:ring-2';
78
+
79
+ export default function ContactPage() {
80
+ const t = useTranslations('contact');
81
+ const [schema, setSchema] = useState<ContactFormPublic | null>(null);
82
+ const [schemaError, setSchemaError] = useState<string | null>(null);
83
+ const [values, setValues] = useState<Record<string, FieldValue>>({});
84
+ const [errors, setErrors] = useState<Record<string, string>>({});
85
+ const [honeypot, setHoneypot] = useState('');
86
+ const [loading, setLoading] = useState(false);
87
+ const [sent, setSent] = useState(false);
88
+ const [submitError, setSubmitError] = useState<string | null>(null);
89
+
90
+ const locale = useMemo(() => {
91
+ if (typeof document !== 'undefined') return document.documentElement.lang || undefined;
92
+ return undefined;
93
+ }, []);
94
+
95
+ useEffect(() => {
96
+ let cancelled = false;
97
+ (async () => {
98
+ try {
99
+ const client = getClient();
100
+ const form = await client.contactForms.get('main', locale);
101
+ if (cancelled) return;
102
+ setSchema(form);
103
+ const initial: Record<string, FieldValue> = {};
104
+ for (const field of form.fields) initial[field.key] = defaultValueFor(field);
105
+ setValues(initial);
106
+ } catch (err) {
107
+ if (cancelled) return;
108
+ setSchemaError(err instanceof Error ? err.message : t('genericError'));
109
+ }
110
+ })();
111
+ return () => {
112
+ cancelled = true;
113
+ };
114
+ }, [t, locale]);
115
+
116
+ function updateValue(key: string, value: FieldValue) {
117
+ setValues((prev) => ({ ...prev, [key]: value }));
118
+ // Clear field error on input change
119
+ if (errors[key]) {
120
+ setErrors((prev) => {
121
+ const next = { ...prev };
122
+ delete next[key];
123
+ return next;
124
+ });
125
+ }
126
+ }
127
+
128
+ async function handleSubmit(e: React.FormEvent) {
129
+ e.preventDefault();
130
+ if (loading || !schema) return;
131
+
132
+ if (honeypot.trim().length > 0) {
133
+ setSent(true);
134
+ return;
135
+ }
136
+
137
+ // ── Client-side required-field validation ──
138
+ const newErrors: Record<string, string> = {};
139
+ for (const field of schema.fields) {
140
+ if (field.isRequired && isEmpty(values[field.key] ?? defaultValueFor(field))) {
141
+ newErrors[field.key] = t('fieldRequired', { label: field.label });
142
+ }
143
+ }
144
+ if (Object.keys(newErrors).length > 0) {
145
+ setErrors(newErrors);
146
+ return; // block submission — do NOT send to server
147
+ }
148
+ setErrors({});
149
+
150
+ try {
151
+ setLoading(true);
152
+ setSubmitError(null);
153
+
154
+ const payload: Record<string, unknown> = {};
155
+ for (const field of schema.fields) {
156
+ const raw = values[field.key];
157
+ if (isEmpty(raw)) continue;
158
+ payload[field.key] = typeof raw === 'string' ? raw.trim() : raw;
159
+ }
160
+
161
+ await getClient().createInquiry({
162
+ formKey: schema.key,
163
+ fields: payload,
164
+ locale,
165
+ });
166
+
167
+ setSent(true);
168
+ const reset: Record<string, FieldValue> = {};
169
+ for (const field of schema.fields) reset[field.key] = defaultValueFor(field);
170
+ setValues(reset);
171
+ setHoneypot('');
172
+ } catch (err) {
173
+ setSubmitError(err instanceof Error ? err.message : t('genericError'));
174
+ } finally {
175
+ setLoading(false);
176
+ }
177
+ }
178
+
179
+ if (schemaError) {
180
+ return (
181
+ <div className="mx-auto max-w-2xl px-4 py-12 sm:px-6 lg:px-8">
182
+ <div className="bg-destructive/10 border-destructive/20 text-destructive rounded-lg border px-4 py-3 text-sm">
183
+ {schemaError}
184
+ </div>
185
+ </div>
186
+ );
187
+ }
188
+
189
+ if (!schema) {
190
+ return (
191
+ <div className="mx-auto flex max-w-2xl items-center justify-center px-4 py-24 sm:px-6 lg:px-8">
192
+ <LoadingSpinner />
193
+ </div>
194
+ );
195
+ }
196
+
197
+ return (
198
+ <div className="mx-auto max-w-2xl px-4 py-12 sm:px-6 lg:px-8">
199
+ <div className="mb-8 text-center">
200
+ <h1 className="text-foreground text-3xl font-bold">{schema.name || t('title')}</h1>
201
+ {schema.description ? (
202
+ <p className="text-muted-foreground mt-2 text-sm">{schema.description}</p>
203
+ ) : (
204
+ <p className="text-muted-foreground mt-2 text-sm">{t('subtitle')}</p>
205
+ )}
206
+ </div>
207
+
208
+ {submitError && (
209
+ <div className="bg-destructive/10 border-destructive/20 text-destructive mb-6 rounded-lg border px-4 py-3 text-sm">
210
+ {submitError}
211
+ </div>
212
+ )}
213
+
214
+ {sent ? (
215
+ <div className="rounded-lg border border-green-200 bg-green-50 px-4 py-6 text-center text-sm text-green-800 dark:border-green-800 dark:bg-green-950/30 dark:text-green-300">
216
+ <p className="font-medium">{t('thanksTitle')}</p>
217
+ <p className="mt-1">{schema.successMessage || t('thanksBody')}</p>
218
+ <button
219
+ type="button"
220
+ onClick={() => setSent(false)}
221
+ className="text-primary mt-4 text-sm font-medium hover:underline"
222
+ >
223
+ {t('sendAnother')}
224
+ </button>
225
+ </div>
226
+ ) : (
227
+ <form onSubmit={handleSubmit} className="space-y-2" noValidate>
228
+ <div
229
+ aria-hidden="true"
230
+ className="pointer-events-none absolute -start-[10000px] h-0 w-0 overflow-hidden"
231
+ >
232
+ <label htmlFor="contact-honeypot">Leave this field empty</label>
233
+ <input
234
+ id="contact-honeypot"
235
+ type="text"
236
+ tabIndex={-1}
237
+ autoComplete="off"
238
+ value={honeypot}
239
+ onChange={(e) => setHoneypot(e.target.value)}
240
+ />
241
+ </div>
242
+
243
+ {/* 6-column grid — FULL=span 6, HALF=span 3, THIRD=span 2; stacks on mobile */}
244
+ <div className="grid grid-cols-6 gap-4">
245
+ {schema.fields.map((field) => (
246
+ <DynamicField
247
+ key={field.key}
248
+ field={field}
249
+ value={values[field.key] ?? defaultValueFor(field)}
250
+ error={errors[field.key]}
251
+ onChange={(v) => updateValue(field.key, v)}
252
+ t={t}
253
+ />
254
+ ))}
255
+ </div>
256
+
257
+ <button
258
+ type="submit"
259
+ disabled={loading}
260
+ className="bg-primary text-primary-foreground flex h-10 w-full items-center justify-center gap-2 rounded text-sm font-medium transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
261
+ >
262
+ {loading ? (
263
+ <>
264
+ <LoadingSpinner
265
+ size="sm"
266
+ className="border-primary-foreground/30 border-t-primary-foreground"
267
+ />
268
+ {t('sending')}
269
+ </>
270
+ ) : (
271
+ schema.submitButton || t('send')
272
+ )}
273
+ </button>
274
+ </form>
275
+ )}
276
+ </div>
277
+ );
278
+ }
279
+
280
+ function DynamicField({
281
+ field,
282
+ value,
283
+ error,
284
+ onChange,
285
+ t,
286
+ }: {
287
+ field: ContactFormPublicField;
288
+ value: FieldValue;
289
+ error?: string;
290
+ onChange: (v: FieldValue) => void;
291
+ t: (key: string, values?: Record<string, string>) => string;
292
+ }) {
293
+ const id = `contact-${field.key}`;
294
+ const hasError = !!error;
295
+ const label = (
296
+ <label htmlFor={id} className="text-foreground mb-1.5 block text-sm font-medium">
297
+ {field.label}
298
+ {field.isRequired ? (
299
+ <span className="ms-0.5 text-red-500" aria-hidden>
300
+ *
301
+ </span>
302
+ ) : (
303
+ <span className="text-muted-foreground ms-1">({t('optional')})</span>
304
+ )}
305
+ </label>
306
+ );
307
+ const help = field.helpText ? (
308
+ <p className="text-muted-foreground mt-1 text-xs">{field.helpText}</p>
309
+ ) : null;
310
+ const errorEl = error ? <p className="mt-1 text-xs text-red-500">{error}</p> : null;
311
+
312
+ const maxLength = field.validation?.maxLength;
313
+ const minLength = field.validation?.minLength;
314
+ const min = field.validation?.min;
315
+ const max = field.validation?.max;
316
+ const pattern = field.validation?.pattern;
317
+ const strVal = typeof value === 'string' ? value : '';
318
+ const iClass = hasError ? inputErrorClass : inputClass;
319
+ const tClass = hasError ? textareaErrorClass : textareaClass;
320
+
321
+ switch (field.type) {
322
+ case 'TEXTAREA':
323
+ return (
324
+ <div className={widthColSpan(field.width)}>
325
+ {label}
326
+ <textarea
327
+ id={id}
328
+ required={field.isRequired}
329
+ maxLength={maxLength}
330
+ minLength={minLength}
331
+ rows={6}
332
+ placeholder={field.placeholder}
333
+ value={strVal}
334
+ onChange={(e) => onChange(e.target.value)}
335
+ className={tClass}
336
+ />
337
+ {help}
338
+ {errorEl}
339
+ </div>
340
+ );
341
+
342
+ case 'SELECT':
343
+ return (
344
+ <div className={widthColSpan(field.width)}>
345
+ {label}
346
+ <select
347
+ id={id}
348
+ required={field.isRequired}
349
+ value={strVal}
350
+ onChange={(e) => onChange(e.target.value)}
351
+ className={iClass}
352
+ >
353
+ <option value="">—</option>
354
+ {field.enumValues?.map((opt) => (
355
+ <option key={opt.value} value={opt.value}>
356
+ {opt.label}
357
+ </option>
358
+ ))}
359
+ </select>
360
+ {help}
361
+ {errorEl}
362
+ </div>
363
+ );
364
+
365
+ case 'MULTI_SELECT': {
366
+ const arr = Array.isArray(value) ? value : [];
367
+ return (
368
+ <div className={widthColSpan(field.width)}>
369
+ {label}
370
+ <div className="space-y-2">
371
+ {field.enumValues?.map((opt) => {
372
+ const checked = arr.includes(opt.value);
373
+ return (
374
+ <label key={opt.value} className="flex items-center gap-2 text-sm">
375
+ <input
376
+ type="checkbox"
377
+ checked={checked}
378
+ onChange={(e) => {
379
+ if (e.target.checked) onChange([...arr, opt.value]);
380
+ else onChange(arr.filter((v) => v !== opt.value));
381
+ }}
382
+ />
383
+ <span>{opt.label}</span>
384
+ </label>
385
+ );
386
+ })}
387
+ </div>
388
+ {help}
389
+ {errorEl}
390
+ </div>
391
+ );
392
+ }
393
+
394
+ case 'CHECKBOX':
395
+ return (
396
+ <div className={widthColSpan(field.width)}>
397
+ <label htmlFor={id} className="flex items-start gap-2 text-sm">
398
+ <input
399
+ id={id}
400
+ type="checkbox"
401
+ required={field.isRequired}
402
+ checked={value === true}
403
+ onChange={(e) => onChange(e.target.checked)}
404
+ className="mt-0.5"
405
+ />
406
+ <span className="text-foreground">{field.label}</span>
407
+ </label>
408
+ {help}
409
+ {errorEl}
410
+ </div>
411
+ );
412
+
413
+ case 'NUMBER':
414
+ return (
415
+ <div className={widthColSpan(field.width)}>
416
+ {label}
417
+ <input
418
+ id={id}
419
+ type="number"
420
+ required={field.isRequired}
421
+ min={min}
422
+ max={max}
423
+ placeholder={field.placeholder}
424
+ value={strVal}
425
+ onChange={(e) => onChange(e.target.value)}
426
+ className={iClass}
427
+ />
428
+ {help}
429
+ {errorEl}
430
+ </div>
431
+ );
432
+
433
+ case 'EMAIL':
434
+ return (
435
+ <div className={widthColSpan(field.width)}>
436
+ {label}
437
+ <input
438
+ id={id}
439
+ type="email"
440
+ required={field.isRequired}
441
+ autoComplete="email"
442
+ placeholder={field.placeholder}
443
+ value={strVal}
444
+ onChange={(e) => onChange(e.target.value)}
445
+ className={iClass}
446
+ />
447
+ {help}
448
+ {errorEl}
449
+ </div>
450
+ );
451
+
452
+ case 'PHONE':
453
+ return (
454
+ <div className={widthColSpan(field.width)}>
455
+ {label}
456
+ <input
457
+ id={id}
458
+ type="tel"
459
+ required={field.isRequired}
460
+ autoComplete="tel"
461
+ placeholder={field.placeholder}
462
+ value={strVal}
463
+ onChange={(e) => onChange(e.target.value)}
464
+ className={iClass}
465
+ />
466
+ {help}
467
+ {errorEl}
468
+ </div>
469
+ );
470
+
471
+ case 'URL':
472
+ return (
473
+ <div className={widthColSpan(field.width)}>
474
+ {label}
475
+ <input
476
+ id={id}
477
+ type="url"
478
+ required={field.isRequired}
479
+ placeholder={field.placeholder}
480
+ value={strVal}
481
+ onChange={(e) => onChange(e.target.value)}
482
+ className={iClass}
483
+ />
484
+ {help}
485
+ {errorEl}
486
+ </div>
487
+ );
488
+
489
+ case 'DATE':
490
+ return (
491
+ <div className={widthColSpan(field.width)}>
492
+ {label}
493
+ <input
494
+ id={id}
495
+ type="date"
496
+ required={field.isRequired}
497
+ value={strVal}
498
+ onChange={(e) => onChange(e.target.value)}
499
+ className={iClass}
500
+ />
501
+ {help}
502
+ {errorEl}
503
+ </div>
504
+ );
505
+
506
+ case 'TEXT':
507
+ default:
508
+ return (
509
+ <div className={widthColSpan(field.width)}>
510
+ {label}
511
+ <input
512
+ id={id}
513
+ type="text"
514
+ required={field.isRequired}
515
+ maxLength={maxLength}
516
+ minLength={minLength}
517
+ pattern={pattern}
518
+ placeholder={field.placeholder}
519
+ value={strVal}
520
+ onChange={(e) => onChange(e.target.value)}
521
+ className={iClass}
522
+ />
523
+ {help}
524
+ {errorEl}
525
+ </div>
526
+ );
527
+ }
528
+ }