import { loadPersonaDraft } from './drafts' import { getPersonaById } from './creations' import { normalizePersonaFormRecord } from './personaFormModel' import { isPersonaFormFieldKey, PERSONA_FIELD_STEP } from './personaWizardFieldStep' const STEPNAMES = ['You & the advisor', 'Creativity & expertise', 'Voice & guidelines', 'Review'] export type PersonaWizardSnapshot = { editingId: string | null data: Record step: number } /** Read draft + URL in one place so useState(initializer) matches the load effect (avoids empty save wiping localStorage). */ export function readPersonaWizardState(searchParams: URLSearchParams): PersonaWizardSnapshot { const focusRaw = searchParams.get('focus') const focusKey = focusRaw && isPersonaFormFieldKey(focusRaw) ? focusRaw : null const stepFromFocus = focusKey != null ? PERSONA_FIELD_STEP[focusKey] : null const stepParam = searchParams.get('step') let parsedStep: number | null = null if (stepParam != null) { const n = Number.parseInt(stepParam, 10) if (!Number.isNaN(n) && n >= 0 && n < STEPNAMES.length) parsedStep = n } const edit = searchParams.get('edit') if (edit) { const p = getPersonaById(edit) if (p) { const normalized = normalizePersonaFormRecord(p as unknown as Record) let step = 0 if (stepFromFocus != null) step = stepFromFocus else if (parsedStep != null) step = parsedStep return { editingId: edit, data: normalized, step, } } } const d = loadPersonaDraft() as Record let step = 0 const ws = d._wizardStep if (typeof ws === 'number' && ws >= 0 && ws < STEPNAMES.length) step = ws if (stepFromFocus != null) step = stepFromFocus else if (parsedStep != null) step = parsedStep const normalized = normalizePersonaFormRecord(d) const savedId = typeof d._editingId === 'string' && d._editingId ? d._editingId : null const editingId = savedId && getPersonaById(savedId) ? savedId : null return { editingId, data: normalized, step, } }