'use client' import * as React from 'react' import { Circle, Globe, Mail, Phone, Star, ThumbsUp, type LucideIcon } from 'lucide-react' import { Button } from '@open-mercato/ui/primitives/button' import { Input } from '@open-mercato/ui/primitives/input' import { Textarea } from '@open-mercato/ui/primitives/textarea' import { CheckboxField } from '@open-mercato/ui/primitives/checkbox-field' import { SwitchField } from '@open-mercato/ui/primitives/switch-field' import { Alert } from '@open-mercato/ui/primitives/alert' import { Tag } from '@open-mercato/ui/primitives/tag' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@open-mercato/ui/primitives/select' import { DatePicker } from '@open-mercato/ui/backend/inputs/DatePicker' import { DateTimePicker } from '@open-mercato/ui/backend/inputs/DateTimePicker' import { apiCall } from '@open-mercato/ui/backend/utils/apiCall' import { useT, type TranslateFn } from '@open-mercato/shared/lib/i18n/context' import { evaluateFormLogic, type LogicState, type JumpTarget } from '../services/form-logic-evaluator' import { partitionPages } from '../services/form-version-compiler' import { compileFieldValidationRules, validateFieldValue, } from '../services/field-validation-service' import { COUNTRY_OPTIONS, resolveCountryName, } from '../schema/address-countries' import { RankingField } from './RankingField' import { MatrixField, type MatrixFieldColumn, type MatrixFieldRow } from './MatrixField' import type { FieldNode } from '../backend/forms/[id]/studio/schema-helpers' export type FormRunnerProps = { formId: string formVersionId: string schema: Record uiSchema: Record hidden: Record locale: string /** Optional URL to POST submissions to (defaults to /api/forms/:id/run/submissions). */ submitEndpoint?: string } export function FormRunner({ formId, formVersionId, schema, hidden, locale, submitEndpoint, }: FormRunnerProps) { const t = useT() const sections = React.useMemo(() => readSections(schema), [schema]) const pages = React.useMemo(() => partitionPages(sections), [sections]) const [answers, setAnswers] = React.useState>({}) const [pageIndex, setPageIndex] = React.useState(0) const [endingKey, setEndingKey] = React.useState(null) const [submitting, setSubmitting] = React.useState(false) const [submitError, setSubmitError] = React.useState(null) const [submitted, setSubmitted] = React.useState(false) const state: LogicState = React.useMemo( () => evaluateFormLogic(schema, { answers, hidden, locale }), [schema, answers, hidden, locale], ) const currentPage = pages[pageIndex] const isLastPage = pageIndex >= pages.length - 1 const isFirstPage = pageIndex === 0 const handleAnswerChange = React.useCallback((fieldKey: string, value: unknown) => { setAnswers((current) => ({ ...current, [fieldKey]: value })) }, []) const handleNext = React.useCallback(async () => { if (!currentPage) return const currentPageKey = currentPage.sectionKeys.find((key) => sections.find((s) => s.key === key && (s.kind === 'page' || s.kind === undefined))) ?? currentPage.sectionKeys[0] if (!currentPageKey) return const target: JumpTarget = state.nextTarget(currentPageKey) if (target.type === 'ending') { setEndingKey(target.endingKey) await submitToServer(target.endingKey) return } if (target.type === 'submit') { await submitToServer(null) return } if (target.type === 'page') { const idx = pages.findIndex((page) => page.sectionKeys.includes(target.pageKey)) if (idx >= 0) { setPageIndex(idx) return } } if (isLastPage) { await submitToServer(null) return } setPageIndex((current) => Math.min(pages.length - 1, current + 1)) }, [currentPage, isLastPage, pages, sections, state]) const submitToServer = async (claimedEndingKey: string | null) => { setSubmitting(true) setSubmitError(null) try { const endpoint = submitEndpoint ?? `/api/forms/${encodeURIComponent(formId)}/run/submissions` await apiCall(endpoint, { method: 'POST', body: JSON.stringify({ formVersionId, answers, hidden, endingKey: claimedEndingKey, locale, }), headers: { 'content-type': 'application/json' }, }) setSubmitted(true) if (claimedEndingKey) { const endingSection = sections.find((entry) => entry.key === claimedEndingKey && entry.kind === 'ending') const redirectUrl = endingSection?.['x-om-redirect-url'] if (typeof redirectUrl === 'string' && redirectUrl.length > 0 && typeof window !== 'undefined') { window.location.assign(redirectUrl) } } } catch (error) { setSubmitError(error instanceof Error ? error.message : t('forms.runner.submit.error')) } finally { setSubmitting(false) } } if (submitted && endingKey) { const endingSection = sections.find((entry) => entry.key === endingKey && entry.kind === 'ending') if (endingSection) { const title = state.resolveRecall(endingSection.title as Record, locale) return (
{t('forms.runner.actions.submit')}

{title || endingSection.key}

{endingSection.fieldKeys.map((fieldKey) => { const node = (schema.properties as Record>)?.[fieldKey] if (!node) return null const label = state.resolveRecall(node['x-om-label'] as Record, locale) const help = state.resolveRecall(node['x-om-help'] as Record, locale) return (
{label ?

{label}

: null} {help ?

{help}

: null}
) })}
) } } if (submitted) { return (
{t('forms.runner.completion.title')}

{t('forms.runner.completion.subtitle')}

) } const visibleSections = currentPage ? currentPage.sectionKeys .map((key) => sections.find((entry) => entry.key === key)) .filter((entry): entry is RunnerSection => Boolean(entry)) .filter((entry) => state.visibleSectionKeys.has(entry.key) && entry.kind !== 'ending') : [] return (
{submitError ? {submitError} : null} {visibleSections.map((section) => { const title = state.resolveRecall(section.title as Record, locale) return (
{!section.hideTitle && title ? (

{title}

) : null}
{section.fieldKeys.map((fieldKey) => { if (!state.visibleFieldKeys.has(fieldKey)) return null return ( >)?.[fieldKey] ?? {}} value={answers[fieldKey]} onChange={(value) => handleAnswerChange(fieldKey, value)} state={state} locale={locale} required={Array.isArray(schema.required) && (schema.required as string[]).includes(fieldKey)} t={t} /> ) })}
) })}
) } type RunnerSection = { key: string kind?: 'page' | 'section' | 'ending' title?: Record fieldKeys: string[] hideTitle?: boolean 'x-om-redirect-url'?: string | null } function readSections(schema: Record): RunnerSection[] { const raw = schema['x-om-sections'] if (!Array.isArray(raw)) return [] const result: RunnerSection[] = [] for (const entry of raw) { if (!entry || typeof entry !== 'object') continue const candidate = entry as Record if (typeof candidate.key !== 'string') continue result.push({ key: candidate.key, kind: candidate.kind as RunnerSection['kind'], title: candidate.title as Record, fieldKeys: Array.isArray(candidate.fieldKeys) ? (candidate.fieldKeys as string[]) : [], hideTitle: candidate.hideTitle === true, 'x-om-redirect-url': typeof candidate['x-om-redirect-url'] === 'string' ? (candidate['x-om-redirect-url'] as string) : null, }) } return result } const padRunner2 = (input: number): string => String(input).padStart(2, '0') // Date pickers exchange `Date`; submissions persist the native // `YYYY-MM-DD` / `YYYY-MM-DDTHH:mm` strings, so adapt without altering bytes. function parseRunnerDateOnly(value: string): Date | null { const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value) if (!match) return null const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])) return Number.isNaN(date.getTime()) ? null : date } function formatRunnerDateOnly(date: Date | null): string | undefined { if (!date) return undefined return `${date.getFullYear()}-${padRunner2(date.getMonth() + 1)}-${padRunner2(date.getDate())}` } function parseRunnerDateTimeLocal(value: string): Date | null { const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(value) if (!match) return null const date = new Date( Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), ) return Number.isNaN(date.getTime()) ? null : date } function formatRunnerDateTimeLocal(date: Date | null): string | undefined { if (!date) return undefined return ( `${date.getFullYear()}-${padRunner2(date.getMonth() + 1)}-${padRunner2(date.getDate())}` + `T${padRunner2(date.getHours())}:${padRunner2(date.getMinutes())}` ) } type FieldRunnerRowProps = { fieldKey: string node: Record value: unknown onChange: (value: unknown) => void state: LogicState locale: string required: boolean t: TranslateFn } function FieldRunnerRow({ fieldKey, node, value, onChange, state, locale, required, t }: FieldRunnerRowProps) { const omType = String(node['x-om-type'] ?? 'text') const label = state.resolveRecall(node['x-om-label'] as Record, locale) || fieldKey const help = state.resolveRecall(node['x-om-help'] as Record, locale) if (omType === 'info_block') { return (
{label ?

{label}

: null} {help ?

{help}

: null}
) } const requiredMark = required ? ( ) : null if (omType === 'boolean') { return ( onChange(next === true)} label={<>{label}{requiredMark}} description={help || undefined} /> ) } if (omType === 'yes_no') { return ( onChange(Boolean(next))} label={<>{label}{requiredMark}} description={help || undefined} /> ) } if (omType === 'yes_no_buttons') { const selectedYes = value === true const selectedNo = value === false return (
{label} {requiredMark}
{help ?

{help}

: null}
) } const stringValue = typeof value === 'string' ? value : value === undefined || value === null ? '' : String(value) const options = Array.isArray(node['x-om-options']) ? (node['x-om-options'] as Array<{ value: string; label?: Record }>) : [] return (
{help ?

{help}

: null} {(() => { switch (omType) { case 'textarea': return