(() => {
    'use strict';

    window.FotogenicAI = window.FotogenicAI || {};
    const Studio = window.FotogenicAI.Studio = window.FotogenicAI.Studio || {};
    const { __, _n, sprintf } = Studio.i18n;
    const { isRecord, clone } = Studio.store;
    const { element, requestState } = Studio.viewModel;
	const icons = window.FotogenicAI.Shared?.ui?.icon;
	if (!icons) throw new Error('Fotogenic AI shared icon helper is required.');

    const humanize = (name) => String(name || '')
        .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
        .replace(/[_-]+/g, ' ')
        .replace(/^./, (value) => value.toUpperCase());

    const FIELD_LABELS = Object.freeze({
        count: __( 'Number of images', 'fotogenic-ai' ),
        quality: __( 'Quality', 'fotogenic-ai' ),
        customInstructions: __( 'Instructions for this run', 'fotogenic-ai' ),
        applyGlobalInstructions: __( 'Saved account guidance', 'fotogenic-ai' ),
        autoConfigUsed: __( 'Auto configuration', 'fotogenic-ai' ),
        autoConfigDescription: __( 'Auto configuration notes', 'fotogenic-ai' ),
        personPresence: __( 'Presence', 'fotogenic-ai' ),
        includeFace: __( 'Show face', 'fotogenic-ai' ),
        includeBody: __( 'Show body', 'fotogenic-ai' ),
        lookAtCamera: __( 'Look at camera', 'fotogenic-ai' ),
        selections: __( 'Image direction', 'fotogenic-ai' ),
        emotion: __( 'Emotion', 'fotogenic-ai' ),
        styling: __( 'Styling', 'fotogenic-ai' ),
        clothing: __( 'Clothing', 'fotogenic-ai' ),
        action: __( 'Action', 'fotogenic-ai' ),
        expression: __( 'Expression', 'fotogenic-ai' ),
        grip: __( 'Grip', 'fotogenic-ai' ),
        framing: __( 'Framing', 'fotogenic-ai' ),
        setting: __( 'Setting', 'fotogenic-ai' ),
        focus: __( 'Focus', 'fotogenic-ai' ),
        bgElements: __( 'Background elements', 'fotogenic-ai' ),
        lighting: __( 'Lighting', 'fotogenic-ai' ),
        atmosphere: __( 'Atmosphere', 'fotogenic-ai' ),
        angle: __( 'Angle', 'fotogenic-ai' ),
        shotSize: __( 'Shot size', 'fotogenic-ai' ),
        aspectRatio: __( 'Aspect ratio', 'fotogenic-ai' ),
        subjectImageId: __( 'Model reference', 'fotogenic-ai' ),
        inspirationImageId: __( 'Inspiration reference', 'fotogenic-ai' ),
        environmentImageId: __( 'Environment reference', 'fotogenic-ai' ),
        subjectAttachmentId: __( 'Model reference', 'fotogenic-ai' ),
        environmentAttachmentId: __( 'Environment reference', 'fotogenic-ai' ),
        style: __( 'Style', 'fotogenic-ai' ),
        styleId: __( 'Style', 'fotogenic-ai' ),
    });
    const INTERNAL_FIELDS = new Set(['version', 'autoConfigUsed', 'autoConfigDescription']);
    const GENERATE_SECTIONS = Object.freeze([
        Object.freeze({
            id: 'subject',
            label: __( 'Subject & model', 'fotogenic-ai' ),
            helper: __( 'Use a model when a person should appear. Only supported controls are shown.', 'fotogenic-ai' ),
            paths: Object.freeze([
                'personPresence',
                'subjectImageId',
                'subjectAttachmentId',
                'includeFace',
                'includeBody',
                'lookAtCamera',
                'selections.expression',
                'selections.action',
                'selections.grip',
                'selections.clothing',
                'selections.styling',
            ]),
        }),
        Object.freeze({
            id: 'look',
            label: __( 'Look & feel', 'fotogenic-ai' ),
            helper: __( 'Styling, light, and atmosphere.', 'fotogenic-ai' ),
            paths: Object.freeze(['style', 'styleId', 'selections.emotion', 'selections.lighting', 'selections.atmosphere']),
        }),
        Object.freeze({
            id: 'scene',
            label: __( 'Scene & environment', 'fotogenic-ai' ),
            helper: __( 'Setting and background direction.', 'fotogenic-ai' ),
            paths: Object.freeze(['selections.setting', 'selections.bgElements', 'environmentImageId', 'environmentAttachmentId']),
        }),
        Object.freeze({
            id: 'camera',
            label: __( 'Camera & composition', 'fotogenic-ai' ),
            helper: __( 'Framing, focus, and format.', 'fotogenic-ai' ),
            paths: Object.freeze([
                'selections.framing',
                'selections.focus',
                'selections.angle',
                'selections.shotSize',
                'selections.aspectRatio',
                'aspectRatio',
            ]),
        }),
        Object.freeze({
            id: 'guidance',
            label: __( 'Guidance', 'fotogenic-ai' ),
            helper: __( 'Choose reusable guidance or add direction for this run.', 'fotogenic-ai' ),
            paths: Object.freeze(['inspirationImageId', 'applyGlobalInstructions', 'customInstructions']),
        }),
    ]);
    const GENERATE_DELIVERY_SECTION = Object.freeze({
        id: 'delivery',
        label: __( 'Product delivery', 'fotogenic-ai' ),
        helper: __( 'Choose source images and what happens after generated files are saved.', 'fotogenic-ai' ),
        paths: Object.freeze([]),
        entries: Object.freeze([]),
    });
	const CAMPAIGN_SECTION_HELPERS = Object.freeze({
		subject: __( 'Optional model reference.', 'fotogenic-ai' ),
		look: __( 'Optional coordinated campaign style.', 'fotogenic-ai' ),
		scene: __( 'Optional environment reference.', 'fotogenic-ai' ),
		camera: __( 'Optional aspect ratio.', 'fotogenic-ai' ),
		guidance: __( 'Choose reusable guidance or add direction for this run.', 'fotogenic-ai' ),
	});
    const fieldLabel = (name) => FIELD_LABELS[name] || humanize(name);

    const getAtPath = (object, path) => path.reduce((value, key) => value?.[key], object);

    const setAtPath = (object, path, value) => {
        const next = isRecord(object) ? clone(object) : {};
        let cursor = next;
        path.forEach((key, index) => {
            if (index === path.length - 1) {
                if (value === undefined || value === '' || (isRecord(value) && Object.keys(value).length === 0)) {
                    delete cursor[key];
                } else {
                    cursor[key] = value;
                }
                return;
            }
            if (!isRecord(cursor[key])) {
                cursor[key] = {};
            }
            cursor = cursor[key];
        });
        for (let index = path.length - 2; index >= 0; index -= 1) {
            const parentPath = path.slice(0, index);
            const parent = parentPath.length ? getAtPath(next, parentPath) : next;
            const key = path[index];
            if (isRecord(parent?.[key]) && Object.keys(parent[key]).length === 0) {
                delete parent[key];
            }
        }
        return next;
    };

    const routeApplies = (field, route) => (
        (!Array.isArray(field.sources) || field.sources.includes(route.sourceType))
        && (!Array.isArray(field.scopes) || field.scopes.includes(route.scope))
    );

    const requirementsMet = (field, recipe) => {
        if (!isRecord(field.requires)) return true;
        return Object.entries(field.requires).every(([key, expected]) => {
            const actual = recipe?.[key];
            if (expected === 'positive-integer') {
                return Number.isInteger(actual) && actual > 0;
            }
            return actual === expected;
        });
    };

    const fieldApplies = (field, route, recipe = {}) => field.exposed !== false
        && routeApplies(field, route)
        && requirementsMet(field, recipe);

    const fieldEntryAtPath = (recipeSchema, path) => {
        const parts = String(path || '').split('.').filter(Boolean);
        let fields = recipeSchema?.fields;
        let field = null;
        parts.forEach((part) => {
            field = isRecord(fields) ? fields[part] : null;
            fields = field?.type === 'object' && !field.optionSource ? field.fields : null;
        });
        return field ? { name: parts.at(-1), path: parts.slice(0, -1), field } : null;
    };

    const flattenFieldEntries = (fields, path = []) => Object.entries(fields || {}).flatMap(([name, field]) => {
        if (INTERNAL_FIELDS.has(name)) return [];
        if (field?.type === 'object' && !field.optionSource) {
            return flattenFieldEntries(field.fields, [...path, name]);
        }
        return [{ name, path, field, key: [...path, name].join('.') }];
    });

    const generateSectionEntries = (recipeSchema, route) => {
        const assigned = new Set(['count', 'quality']);
        const sections = GENERATE_SECTIONS.map((section) => ({
            ...section,
			helper: route?.workflow === 'campaign_set'
				? (CAMPAIGN_SECTION_HELPERS[section.id] || section.helper)
				: section.helper,
            entries: section.paths.map((path) => {
                const entry = fieldEntryAtPath(recipeSchema, path);
                if (!entry || !routeApplies(entry.field, route)) return null;
                assigned.add(path);
                return { ...entry, key: path };
            }).filter(Boolean),
        })).filter((section) => section.entries.length);
        const unassigned = flattenFieldEntries(recipeSchema?.fields)
            .filter((entry) => !assigned.has(entry.key) && routeApplies(entry.field, route));
        if (['product_images', 'campaign_set'].includes(route?.workflow) && route.sourceType === 'product') {
            sections.push(GENERATE_DELIVERY_SECTION);
        }
        if (unassigned.length) {
            sections.push({
                id: 'additional',
                label: __( 'Additional options', 'fotogenic-ai' ),
                helper: __( 'Options supplied by the current workflow definition.', 'fotogenic-ai' ),
                paths: Object.freeze([]),
                entries: unassigned,
            });
        }
        return { sections, unassigned: [] };
    };

    const selectOptionState = (options, currentValue) => {
        const normalizedCurrent = currentValue === undefined || currentValue === null
            ? ''
            : String(currentValue);
        return {
            normalizedCurrent,
            unavailable: Boolean(
                normalizedCurrent
                && !options.some((option) => option.value === normalizedCurrent)
            ),
        };
    };

    const humanizeIssue = (issue) => {
        let message = String(issue || '').trim();
        if (message === 'Use a model requires a model reference.') {
            return __( 'Select a model reference, or choose Automatic or No person.', 'fotogenic-ai' );
        }
        Object.keys(FIELD_LABELS)
            .sort((left, right) => right.length - left.length)
            .forEach((key) => {
                message = message.replace(new RegExp(`\\b${key}\\b`, 'g'), fieldLabel(key));
            });
        return message.replace(/^./, (value) => value.toUpperCase());
    };

    const normalizeOptions = (options) => (Array.isArray(options) ? options : []).map((option) => {
        if (isRecord(option)) {
            const value = option.value ?? option.id;
            if (value === undefined) return null;
            const normalized = { value: String(value), label: String(option.label || option.name || value) };
            const description = String(option.description || '').trim();
            if (description) normalized.description = description;
            return normalized;
        }
        return { value: String(option), label: humanize(option) };
    }).filter(Boolean);

    const resolveOptions = (manifest, field, path) => {
        if (Array.isArray(field.enum)) {
            return normalizeOptions(field.enum);
        }
        if (Array.isArray(field.options)) {
            return normalizeOptions(field.options);
        }
        const sourceName = String(field.optionSource || '');
        const source = sourceName && isRecord(manifest.optionSources) ? manifest.optionSources[sourceName] : null;
        if (Array.isArray(source)) {
            return normalizeOptions(source);
        }
        if (isRecord(source)) {
            const pathKey = path.join('.');
            return normalizeOptions(source[pathKey] || source[path[path.length - 1]] || []);
        }
        return [];
    };

    const isMediaReference = (name, field) => (
        field.type === 'integer'
        && field.required !== true
        && /(ImageId|AttachmentId)$/i.test(name)
    );

    const REFERENCE_FIELDS = Object.freeze(['subjectImageId', 'inspirationImageId', 'environmentImageId']);
    const AUTO_PATCH_FIELDS = new Set([
        'selections',
        'customInstructions',
        'autoConfigUsed',
        'autoConfigDescription',
        'personPresence',
        'includeFace',
        'includeBody',
        'lookAtCamera',
    ]);
    const PERSON_PRESENCE = Object.freeze({
        automatic: 'automatic',
        none: 'none',
        model: 'model',
    });
    const FIELD_DESCRIPTIONS = Object.freeze({
        emotion: __( 'Choose the feeling the image should communicate.', 'fotogenic-ai' ),
        lighting: __( 'Choose how the subject and product should be lit.', 'fotogenic-ai' ),
        atmosphere: __( 'Choose the overall mood of the finished image.', 'fotogenic-ai' ),
        setting: __( 'Choose the location or context for the generated image.', 'fotogenic-ai' ),
        bgElements: __( 'Choose how much supporting detail appears around the subject.', 'fotogenic-ai' ),
        framing: __( 'Choose how tightly or loosely to frame the subject.', 'fotogenic-ai' ),
        shotSize: __( 'Choose how close or far the camera is.', 'fotogenic-ai' ),
        aspectRatio: __( "Choose the image's width-to-height proportion.", 'fotogenic-ai' ),
        angle: __( "Choose the camera's position relative to the subject.", 'fotogenic-ai' ),
        focus: __( 'Choose what should remain sharp.', 'fotogenic-ai' ),
        includeFace: __( 'Choose if the face is visible.', 'fotogenic-ai' ),
        includeBody: __( 'Choose if any part of the body is visible.', 'fotogenic-ai' ),
        lookAtCamera: __( 'Choose whether the model looks at the camera.', 'fotogenic-ai' ),
    });

    const personPresenceMode = (recipe) => (
        recipe?.personPresence === true
            ? PERSON_PRESENCE.model
            : (recipe?.personPresence === false ? PERSON_PRESENCE.none : PERSON_PRESENCE.automatic)
    );

    const routeKey = (route) => `${route.workflow}:${route.sourceType}:${route.scope}`;

    const createRecipeForm = ({
        mount,
		runSettingsMount = null,
		toolsMount = null,
        manifest,
        getState,
        getCanonical,
        onChange,
		onSourcePolicyChange,
		onResultPolicyChange,
		onSectionChange = null,
		onSectionReset = null,
		onRecipeReset = null,
		onAutomaticSettingsApplied = null,
		onBackToSelection = null,
		getRunItemCount = () => 0,
        getSelectedItems = () => [],
        transport,
        isAuthConnected = () => true,
        getConfigurationState = () => 'ready',
        onRetryConfiguration = null,
    } = {}) => {
		const recipeWorkspace = mount?.parentElement || null;
		const workspaceActions = recipeWorkspace?.querySelector(':scope > .fotogenic-ai-recipe-workspace-actions') || null;
        let route = null;
        let workflow = null;
        let controls = new Map();
        let presets = [];
        let activePresetUuid = '';
        let listBusy = false;
        let listError = '';
        let actionBusy = false;
        let listController = null;
        let listRequest = null;
        let listRequestRoute = '';
        let actionController = null;
        let autoController = null;
        let listToken = 0;
        let actionToken = 0;
        let autoToken = 0;
        let autoSignature = '';
        let toolsRoot = null;
        let toolsStatus = null;
        let toolsMessage = '';
        let toolsMessageState = '';
        let toolsDocumentHandler = null;
		let toolsCloseTimer = 0;
        let nameInput = null;
        let activeSectionId = 'subject';
		let activeSectionOwner = '';
		let renderedCampaignGroupSignature = '';
		let enhancementRunItemValue = null;
        let sectionButtons = new Map();
        let sectionPanels = new Map();
        let sectionNavigator = null;
        let sectionNavigatorObserver = null;
        let sectionNavigatorFrame = 0;
        let storedUnavailableOptions = new Map();
        let activeOverlay = null;
		let closingOverlay = null;
        let overlayController = null;
        let pendingAutoProposal = null;
        let pendingAutoSignature = '';
        let recipeIssues = [];
        const presetCache = new Map();
        const referenceItems = new Map();
        const referenceName = (item = {}, attachmentId = 0) => String(
            item.name
            || item.filename
            || item.title?.rendered
            || item.title
            || sprintf(__( 'Model %d', 'fotogenic-ai' ), attachmentId)
        ).replace(/\.[^.]+$/, '').replaceAll('-', ' ').replace(/^./, (character) => character.toUpperCase());
        const errorRegion = element('div', 'fotogenic-ai-recipe-validation');
        errorRegion.id = 'fotogenic-ai-recipe-validation';
        errorRegion.setAttribute('role', 'alert');
        errorRegion.setAttribute('aria-atomic', 'true');
        errorRegion.tabIndex = -1;
        errorRegion.hidden = true;
        const errorTitle = element('strong', '', __( 'Review these settings', 'fotogenic-ai' ));
        const errorList = element('ul');
        errorRegion.append(errorTitle, errorList);
        const unavailableRegion = element('div', 'fotogenic-ai-configuration-contract-status');
        unavailableRegion.setAttribute('role', 'status');
        unavailableRegion.setAttribute('aria-live', 'polite');
        unavailableRegion.setAttribute('aria-atomic', 'true');
        unavailableRegion.hidden = true;

		const canonicalDraft = () => {
            const canonical = typeof getCanonical === 'function' ? getCanonical() : null;
			return canonical?.draft || getState()?.draft || {};
		};

		const campaignGroups = (draft = getState()?.draft) => (
			Array.isArray(draft?.sourcePolicy?.groups) ? draft.sourcePolicy.groups : []
		);

		const campaignGroup = (draft = getState()?.draft) => {
			const groups = campaignGroups(draft);
			return groups[0] || null;
		};

		const editableRecipe = () => (
			workflow?.id === 'campaign_set'
				? (campaignGroup()?.recipe || {})
				: (getState()?.draft?.recipe || {})
		);

		const canonicalRecipe = () => (
			workflow?.id === 'campaign_set'
				? (campaignGroup(canonicalDraft())?.recipe || {})
				: (canonicalDraft().recipe || {})
		);

		const commitRecipe = (recipe) => {
			if (workflow?.id !== 'campaign_set') {
				onChange(recipe);
				return;
			}
			if (!campaignGroups().length) return;
			onSourcePolicyChange?.({
				groups: campaignGroups().map((group) => ({ ...group, recipe: clone(recipe) })),
			});
		};

		const commitCampaignResultPolicy = (resultPolicy) => {
			if (!campaignGroups().length) return;
			onSourcePolicyChange?.({
				groups: campaignGroups().map((group) => ({ ...group, resultPolicy: clone(resultPolicy) })),
			});
		};

        const applyValue = (path, value) => {
			commitRecipe(setAtPath(editableRecipe(), path, value));
		};

        const setPersonPresenceMode = (mode) => {
            let recipe = editableRecipe();
            if (mode === PERSON_PRESENCE.automatic) {
                recipe = setAtPath(recipe, ['personPresence'], undefined);
                recipe = setAtPath(recipe, ['subjectImageId'], undefined);
            } else if (mode === PERSON_PRESENCE.none) {
                recipe = setAtPath(recipe, ['personPresence'], false);
                recipe = setAtPath(recipe, ['subjectImageId'], undefined);
            } else {
                recipe = setAtPath(recipe, ['personPresence'], true);
            }
            if (mode !== PERSON_PRESENCE.model) {
                ['includeFace', 'includeBody', 'lookAtCamera'].forEach((field) => {
                    recipe = setAtPath(recipe, [field], undefined);
                });
                ['styling', 'clothing', 'action', 'expression', 'grip'].forEach((field) => {
                    recipe = setAtPath(recipe, ['selections', field], undefined);
                });
            }
            commitRecipe(recipe);
        };


        const syncRecipeControls = () => {
			const recipe = canonicalRecipe();
			controls.forEach((entry) => entry.sync(recipe));
        };

        const overlayFocusables = (panel) => [...panel.querySelectorAll(
            'button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
        )].filter((node) => !node.hidden && node.getClientRects().length && !node.closest('[inert]'));

        const restoreOverlayIsolation = (isolated = []) => {
            isolated.forEach(({ node, inert, ariaHidden }) => {
                if (inert) node.setAttribute('inert', '');
                else node.removeAttribute('inert');
                if (ariaHidden === null) node.removeAttribute('aria-hidden');
                else node.setAttribute('aria-hidden', ariaHidden);
            });
        };

        const refreshOverlayIsolation = (overlay = activeOverlay) => {
            if (!overlay) return;
            restoreOverlayIsolation(overlay.isolated);
            overlay.isolated = [];
            const nestedModal = [...overlay.layer.querySelectorAll('[aria-modal="true"]')].at(-1);
            let activeNode = nestedModal || overlay.panel || overlay.layer;
            while (activeNode?.parentElement && activeNode !== document.body) {
                const parent = activeNode.parentElement;
                [...parent.children].forEach((sibling) => {
                    if (sibling === activeNode || sibling.matches?.('.global-toast-stack, .sr-only, script, style')) return;
                    overlay.isolated.push({
                        node: sibling,
                        inert: sibling.hasAttribute('inert'),
                        ariaHidden: sibling.getAttribute('aria-hidden'),
                    });
                    sibling.setAttribute('inert', '');
                    sibling.setAttribute('aria-hidden', 'true');
                });
                activeNode = parent;
            }
        };

		const finalizeContainedOverlay = (overlay, { restoreFocus = true } = {}) => {
			if (!overlay) return;
			if (overlay.closeTimer) window.clearTimeout(overlay.closeTimer);
			document.removeEventListener('keydown', overlay.keyHandler, true);
			restoreOverlayIsolation(overlay.isolated);
			document.documentElement.style.overflow = overlay.previousViewport.htmlOverflow;
			document.documentElement.style.overscrollBehavior = overlay.previousViewport.htmlOverscroll;
			document.body.style.overflow = overlay.previousViewport.bodyOverflow;
			document.body.style.overscrollBehavior = overlay.previousViewport.bodyOverscroll;
			document.body.style.paddingInlineEnd = overlay.previousViewport.bodyPaddingInlineEnd;
			overlay.layer.remove();
			if (activeOverlay === overlay) activeOverlay = null;
			if (closingOverlay === overlay) closingOverlay = null;
			if (restoreFocus && overlay.returnFocus?.isConnected) {
				window.requestAnimationFrame(() => overlay.returnFocus.focus({ preventScroll: true }));
			}
		};

		const closeContainedOverlay = ({ restoreFocus = true, immediate = false } = {}) => {
			const overlay = activeOverlay || closingOverlay;
			if (!overlay || (closingOverlay === overlay && !immediate)) return;
			activeOverlay = null;
			if (!overlay.closeHandled) {
				overlay.closeHandled = true;
				overlay.onClose?.();
			}
			overlayController?.abort?.();
			overlayController = null;
			document.removeEventListener('keydown', overlay.keyHandler, true);
			if (immediate || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
				finalizeContainedOverlay(overlay, { restoreFocus });
				return;
			}
			closingOverlay = overlay;
			overlay.layer.classList.remove('is-open');
			overlay.layer.classList.add('is-closing');
			overlay.closeTimer = window.setTimeout(
				() => finalizeContainedOverlay(overlay, { restoreFocus }),
				220
			);
        };

        const openContainedOverlay = ({
            className,
            title,
            description,
            headingTag = 'h2',
            closeLabel = __( 'Close dialog', 'fotogenic-ai' ),
            returnFocus = document.activeElement,
			initialFocus = 'heading',
			renderBody,
			renderFooter,
			onClose = null,
		}) => {
			closeContainedOverlay({ restoreFocus: false, immediate: true });
            closeTools();
            const layer = element('div', `fotogenic-ai-configuration-layer fotogenic-ai-contained-overlay ${className || ''}`.trim());
            const panel = element('aside', 'fotogenic-ai-configuration-drawer fotogenic-ai-contained-overlay__panel');
            panel.setAttribute('role', 'dialog');
            panel.setAttribute('aria-modal', 'true');
            const titleId = `fotogenic-ai-configuration-overlay-${Date.now()}`;
            panel.setAttribute('aria-labelledby', titleId);
            const header = element('header', 'fotogenic-ai-configuration-drawer__header');
            const headingCopy = element('div');
            const heading = element(headingTag, '', title);
            heading.id = titleId;
            heading.tabIndex = -1;
            const descriptionNode = element('p', '', description);
            headingCopy.append(heading, descriptionNode);
            const close = element('button', 'fotogenic-ai-configuration-drawer__close');
            close.type = 'button';
            close.setAttribute('aria-label', closeLabel);
			const closeIcon = icons.create('x', { weight: 'regular', size: 20 });
            close.appendChild(closeIcon);
            close.addEventListener('click', () => closeContainedOverlay());
            header.append(headingCopy, close);
            const body = element('div', 'fotogenic-ai-configuration-drawer__body');
            const footer = element('footer', 'fotogenic-ai-configuration-drawer__footer');
            panel.append(header, body);
            if (typeof renderFooter === 'function') panel.appendChild(footer);
            layer.appendChild(panel);
            (mount.parentElement || mount).appendChild(layer);
            const previousViewport = {
                htmlOverflow: document.documentElement.style.overflow,
                htmlOverscroll: document.documentElement.style.overscrollBehavior,
                bodyOverflow: document.body.style.overflow,
                bodyOverscroll: document.body.style.overscrollBehavior,
				bodyPaddingInlineEnd: document.body.style.paddingInlineEnd,
            };
			const scrollbarWidth = Math.max(0, window.innerWidth - document.documentElement.clientWidth);
			const bodyPaddingInlineEnd = Number.parseFloat(getComputedStyle(document.body).paddingInlineEnd) || 0;
            document.documentElement.style.overflow = 'hidden';
            document.documentElement.style.overscrollBehavior = 'none';
            document.body.style.overflow = 'hidden';
            document.body.style.overscrollBehavior = 'none';
			if (scrollbarWidth) document.body.style.paddingInlineEnd = `${bodyPaddingInlineEnd + scrollbarWidth}px`;
            const keyHandler = (event) => {
                if (!activeOverlay || activeOverlay.layer !== layer) return;
                if (activeOverlay.suspended) return;
                const nestedDialog = activeOverlay.deleteConfirmation?.node;
                if (event.key === 'Escape') {
                    event.preventDefault();
                    event.stopImmediatePropagation();
                    if (nestedDialog) activeOverlay.deleteConfirmation.close();
                    else closeContainedOverlay();
                    return;
                }
                if (event.key !== 'Tab') return;
                const focusScope = nestedDialog || panel;
                const focusable = overlayFocusables(focusScope);
                if (!focusable.length) {
                    event.preventDefault();
                    (nestedDialog || heading).focus({ preventScroll: true });
                    return;
                }
                const first = focusable[0];
                const last = focusable.at(-1);
                if (!focusScope.contains(document.activeElement) || !focusable.includes(document.activeElement)) {
                    event.preventDefault();
                    (event.shiftKey ? last : first).focus({ preventScroll: true });
                } else if (event.shiftKey && document.activeElement === first) {
                    event.preventDefault();
                    last.focus({ preventScroll: true });
                } else if (!event.shiftKey && document.activeElement === last) {
                    event.preventDefault();
                    first.focus({ preventScroll: true });
                }
            };
            document.addEventListener('keydown', keyHandler, true);
            layer.addEventListener('mousedown', (event) => {
                if (event.target === layer) closeContainedOverlay();
            });
            activeOverlay = {
                layer,
                panel,
                header,
                headingCopy,
                body,
                footer,
                heading,
                descriptionNode,
                close,
                returnFocus,
                isolated: [],
				keyHandler,
				previousViewport,
				onClose,
				closeHandled: false,
			};
            if (typeof renderBody === 'function') renderBody(body, activeOverlay);
            if (typeof renderFooter === 'function') renderFooter(footer, activeOverlay);
            refreshOverlayIsolation(activeOverlay);
            window.requestAnimationFrame(() => {
                layer.classList.add('is-open');
                (initialFocus === 'close' ? close : heading).focus({ preventScroll: true });
            });
            return activeOverlay;
        };

        const productDestinationScope = () => {
            const targets = (Array.isArray(getSelectedItems?.()) ? getSelectedItems() : [])
                .map((item) => item?.target?.targetType)
                .filter((targetType) => ['product', 'variation'].includes(targetType));
            const variationCount = targets.filter((targetType) => targetType === 'variation').length;
            const productCount = targets.filter((targetType) => targetType === 'product').length;
            return variationCount && productCount ? 'mixed' : (variationCount ? 'variations' : 'products');
        };

        const assignmentLabel = (assignmentMode) => {
            const scope = productDestinationScope();
            const labels = {
                review: __( 'Review before product changes', 'fotogenic-ai' ),
                gallery_append: __( 'Append results to product gallery', 'fotogenic-ai' ),
                featured_replace: __( 'Replace featured image after review', 'fotogenic-ai' ),
            };
            if (scope === 'variations') {
                return assignmentMode === 'gallery_append'
                    ? __( 'Review variation images after saving', 'fotogenic-ai' )
                    : (assignmentMode === 'featured_replace'
                        ? __( 'Replace variation images after review', 'fotogenic-ai' )
                        : __( 'Review variation images', 'fotogenic-ai' ));
            }
            if (scope === 'mixed') {
                if (assignmentMode === 'gallery_append') return __( 'Append parent galleries; review variation images', 'fotogenic-ai' );
                if (assignmentMode === 'featured_replace') return __( 'Review featured and variation image replacements', 'fotogenic-ai' );
                return __( 'Review parent Products and variation images', 'fotogenic-ai' );
            }
            return labels[assignmentMode] || labels.review;
        };

        const normalizeLibraryPayload = (payload) => {
            const seen = new Set();
            const items = [];
            (Array.isArray(payload?.items) ? payload.items : []).some((item) => {
                const id = Math.floor(Number(item?.attachmentId));
                const name = String(item?.name || '').trim().slice(0, 180);
                const thumbUrl = String(item?.thumbUrl || '').trim();
                const fullUrl = String(item?.fullUrl || '').trim();
                if (id <= 0 || seen.has(id)) return false;
                seen.add(id);
                items.push({ id, name, thumbUrl, fullUrl });
                return items.length >= 48;
            });
            return {
                items,
                page: Math.max(1, Math.floor(Number(payload?.page)) || 1),
                perPage: Math.min(48, Math.max(1, Math.floor(Number(payload?.perPage)) || 12)),
                total: Math.max(0, Math.floor(Number(payload?.total)) || 0),
            };
        };

        const openNativeMedia = ({ title, trigger, onSelect, uploadMode = false }) => {
            if (typeof window.wp?.media !== 'function') return;
            if (activeOverlay) {
                activeOverlay.suspended = true;
                activeOverlay.panel.removeAttribute('aria-modal');
            }
            const frame = window.wp.media({
                title,
                button: { text: __( 'Use selected media', 'fotogenic-ai' ) },
                library: { type: 'image' },
                multiple: false,
            });
            frame.on('open', () => frame.content?.mode?.(uploadMode ? 'upload' : 'browse'));
            frame.on('select', () => {
                const selected = frame.state()?.get?.('selection')?.first?.()?.toJSON?.() || {};
                const id = Math.floor(Number(selected.id));
                if (id > 0) onSelect?.(id, selected);
            });
            frame.on('close', () => window.setTimeout(() => {
                frame.off?.();
                frame.remove?.();
                if (activeOverlay) {
                    activeOverlay.suspended = false;
                    activeOverlay.panel.setAttribute('aria-modal', 'true');
                }
                trigger?.focus?.({ preventScroll: true });
            }, 0));
            frame.open();
        };

        const openReferenceLibrary = ({ type, path, currentValue, returnFocus, initialMedia = false }) => {
            const model = type === 'model';
			if (initialMedia) {
				openNativeMedia({
					title: model ? __( 'Add a model reference', 'fotogenic-ai' ) : __( 'Add an environment reference', 'fotogenic-ai' ),
					trigger: returnFocus,
					onSelect: async (id) => {
						const saved = typeof transport?.addLibraryItem === 'function'
							? await transport.addLibraryItem(type, id)
							: { ok: false, message: __( 'The reference could not be saved.', 'fotogenic-ai' ) };
						if (!saved.ok) {
							Studio.notify?.error?.(saved.message || __( 'The reference could not be saved.', 'fotogenic-ai' ), {
								title: __( 'Reference not saved', 'fotogenic-ai' ),
								persistent: true,
							});
							return;
						}
						applyValue(path, id);
						render(workflow, route);
						window.requestAnimationFrame(() => {
							controls.get(path.join('.'))?.focusControl?.focus?.({ preventScroll: true });
						});
					},
				});
				return;
			}
            let draftId = Math.max(0, Math.floor(Number(currentValue)) || 0);
            let page = 1;
			let view = 'collection';

            const updateDrawerHeader = (overlay) => {
                overlay.header.querySelector('.fotogenic-ai-configuration-drawer__back')?.remove();
                const collection = view === 'collection';
                overlay.heading.textContent = collection
                    ? (model ? __( 'Choose a model', 'fotogenic-ai' ) : __( 'Choose an environment', 'fotogenic-ai' ))
                    : (model ? __( 'Create a custom model', 'fotogenic-ai' ) : __( 'Media library', 'fotogenic-ai' ));
                overlay.descriptionNode.textContent = collection
                    ? (model
                        ? __( 'Select one reference for this recipe.', 'fotogenic-ai' )
                        : __( 'Select one previously used reference for this recipe.', 'fotogenic-ai' ))
                    : (model
                        ? __( 'Add one reusable person reference.', 'fotogenic-ai' )
                        : __( 'Choose one platform image to reuse as an environment reference.', 'fotogenic-ai' ));
                overlay.footer.hidden = model && !collection;
                if (collection) return;
                const back = element('button', 'fotogenic-ai-configuration-drawer__back');
                back.type = 'button';
                back.setAttribute('aria-label', model
                    ? __( 'Back to My models', 'fotogenic-ai' )
                    : __( 'Back to previously used environments', 'fotogenic-ai' ));
				const icon = icons.create('arrow-left', { weight: 'bold', size: 18 });
                back.appendChild(icon);
                back.addEventListener('click', () => {
                    view = 'collection';
                    renderLibrary(overlay.body, overlay);
                    window.requestAnimationFrame(() => overlay.heading.focus({ preventScroll: true }));
                });
                overlay.header.insertBefore(back, overlay.headingCopy);
            };

            const saveNativeReference = async (id, body, overlay, trigger) => {
                trigger.disabled = true;
                overlayController = typeof AbortController === 'function' ? new AbortController() : null;
                const saved = typeof transport?.addLibraryItem === 'function'
                    ? await transport.addLibraryItem(type, id, { signal: overlayController?.signal })
                    : { ok: false, message: __( 'The reference could not be saved.', 'fotogenic-ai' ) };
                if (!activeOverlay || activeOverlay !== overlay || saved.aborted) return;
                overlayController = null;
                if (!saved.ok) {
                    const message = element('p', 'fotogenic-ai-preset-notice is-error', saved.message || __( 'The reference could not be saved.', 'fotogenic-ai' ));
                    message.setAttribute('role', 'alert');
                    body.prepend(message);
                    trigger.disabled = false;
                    return;
                }
                draftId = id;
                page = 1;
                view = 'collection';
                await renderLibrary(body, overlay);
                window.requestAnimationFrame(() => overlay.heading.focus({ preventScroll: true }));
            };

            const openPlatformMedia = ({ body, overlay, trigger, uploadMode = false }) => openNativeMedia({
                title: model ? __( 'Add a model reference', 'fotogenic-ai' ) : __( 'Add an environment reference', 'fotogenic-ai' ),
                trigger,
                uploadMode,
                onSelect(id) {
                    saveNativeReference(id, body, overlay, trigger);
                },
            });

            const importOption = ({ icon, title, description, onClick }) => {
                const button = element('button', 'fotogenic-ai-model-import-option');
                button.type = 'button';
                const iconWrap = element('span', 'fotogenic-ai-model-import-option__icon');
				const iconNode = icons.create(icon, { weight: 'regular', size: 20 });
                iconWrap.appendChild(iconNode);
				const copy = element('span');
                copy.append(element('strong', '', title), element('small', '', description));
				const arrow = icons.create('arrow-right', { weight: 'bold', size: 17 });
                button.append(iconWrap, copy, arrow);
                button.addEventListener('click', onClick);
                return button;
            };

            const renderMediaImport = (body, overlay) => {
                body.replaceChildren();
                body.removeAttribute('aria-busy');
                const panel = element('div', model ? 'fotogenic-ai-model-custom-panel' : 'fotogenic-ai-environment-media-panel');
                const intro = element('div', model ? 'fotogenic-ai-model-custom-intro' : 'fotogenic-ai-environment-platform-note');
                const introIcon = element('span', model ? 'fotogenic-ai-model-custom-intro__icon' : 'fotogenic-ai-environment-platform-note__icon');
				const icon = icons.create(model ? 'user-square' : 'image-square', {
					weight: 'regular',
					size: model ? 21 : 18,
				});
                introIcon.appendChild(icon);
                const copy = element('div');
                copy.append(
                    element('strong', '', model ? __( 'Use one clear person reference', 'fotogenic-ai' ) : __( 'WordPress Media Library', 'fotogenic-ai' )),
                    element('p', '', model
                        ? __( 'The image is added to My models for quick reuse in this platform.', 'fotogenic-ai' )
                        : __( 'Choose or upload one image with the native WordPress picker.', 'fotogenic-ai' ))
                );
                intro.append(introIcon, copy);
                const options = element('div', 'fotogenic-ai-model-import-options');
                const library = importOption({
					icon: 'images',
                    title: model ? __( 'Choose from media library', 'fotogenic-ai' ) : __( 'Open WordPress Media Library', 'fotogenic-ai' ),
                    description: model
                        ? __( 'Opens WordPress Media Library or Shopify Files.', 'fotogenic-ai' )
                        : __( 'Choose an existing image or switch to Upload files.', 'fotogenic-ai' ),
                    onClick(event) {
                        openPlatformMedia({ body, overlay, trigger: event.currentTarget });
                    },
                });
                options.appendChild(library);
                if (model) {
                    options.appendChild(importOption({
						icon: 'upload-simple',
                        title: __( 'Upload from computer', 'fotogenic-ai' ),
                        description: __( 'Saves the image to the connected platform first.', 'fotogenic-ai' ),
                        onClick(event) {
                            openPlatformMedia({ body, overlay, trigger: event.currentTarget, uploadMode: true });
                        },
                    }));
                }
                panel.append(intro, options);
                if (model) {
                    panel.appendChild(element(
                        'p',
                        'fotogenic-ai-model-custom-note',
                        __( 'Custom models use one reference image. Full body, Portrait, and Face choices appear only when a Fotogenic model supplies those views.', 'fotogenic-ai' )
                    ));
                }
                body.appendChild(panel);
            };

            const renderLibrary = async (body, overlay) => {
                updateDrawerHeader(overlay);
                if (view !== 'collection') {
					renderMediaImport(body, overlay);
                    return;
                }
                const token = Symbol(type);
                overlay.libraryToken = token;
                body.replaceChildren();
                body.setAttribute('aria-busy', 'true');
                body.appendChild(requestState({
                    message: model ? __( 'Loading saved models…', 'fotogenic-ai' ) : __( 'Loading saved environments…', 'fotogenic-ai' ),
                    loading: true,
                }));
                overlayController?.abort?.();
                overlayController = typeof AbortController === 'function' ? new AbortController() : null;
                const response = typeof transport?.listLibrary === 'function'
                    ? await transport.listLibrary(type, { page, perPage: 12, signal: overlayController?.signal })
                    : { ok: false, message: __( 'Saved references are unavailable.', 'fotogenic-ai' ) };
                if (!activeOverlay || activeOverlay !== overlay || overlay.libraryToken !== token || response.aborted) return;
                overlayController = null;
                body.removeAttribute('aria-busy');
                body.replaceChildren();
                if (!response.ok) {
                    const error = element('div', 'fotogenic-ai-library-empty is-error');
                    error.setAttribute('role', 'alert');
                    error.append(
                        element('strong', '', __( 'Saved references are unavailable', 'fotogenic-ai' )),
                        element('p', '', response.message || __( 'Try loading the saved library again.', 'fotogenic-ai' ))
                    );
                    const retry = element('button', 'fotogenic-ai-secondary-small', __( 'Retry', 'fotogenic-ai' ));
                    retry.type = 'button';
                    retry.addEventListener('click', () => renderLibrary(body, overlay));
                    error.appendChild(retry);
                    body.appendChild(error);
                    return;
                }
                const library = normalizeLibraryPayload(response.data);
                library.items.forEach((item) => referenceItems.set(`${type}:${item.id}`, item));
                const intro = element('div', 'fotogenic-ai-library-heading');
                const introCopy = element('span');
                introCopy.append(
                    element('strong', '', model ? __( 'My models', 'fotogenic-ai' ) : __( 'Previously used', 'fotogenic-ai' )),
                    element('small', '', model
                        ? __( 'Fotogenic models and custom references.', 'fotogenic-ai' )
                        : __( 'Environment references available for quick reuse.', 'fotogenic-ai' ))
                );
                const add = element('button', 'fotogenic-ai-library-action');
                add.append(
                    icons.create(model ? 'plus' : 'folder-open', {
                        weight: model ? 'bold' : 'regular',
                        size: model ? 14 : 15,
                    }),
                    document.createTextNode(model ? __( 'Create custom model', 'fotogenic-ai' ) : __( 'Media library', 'fotogenic-ai' ))
                );
                add.type = 'button';
				add.disabled = typeof window.wp?.media !== 'function';
				add.addEventListener('click', () => {
					if (!model) {
						openPlatformMedia({ body, overlay, trigger: add });
						return;
					}
					view = 'media';
					renderLibrary(body, overlay);
					window.requestAnimationFrame(() => overlay.heading.focus({ preventScroll: true }));
                });
                intro.append(introCopy, add);
                body.appendChild(intro);
                if (!library.items.length) {
                    const empty = element('div', 'fotogenic-ai-library-empty');
                    empty.append(
                        element('strong', '', model ? __( 'No saved models yet', 'fotogenic-ai' ) : __( 'No saved environments yet', 'fotogenic-ai' )),
                        element('p', '', model
                            ? __( 'Add a WordPress image to create your reusable model library.', 'fotogenic-ai' )
                            : __( 'Add a WordPress image to reuse it as an environment reference.', 'fotogenic-ai' ))
                    );
                    body.appendChild(empty);
                } else {
                    const grid = element('div', `fotogenic-ai-library-grid is-${type}`);
                    grid.setAttribute('aria-label', model ? __( 'My models', 'fotogenic-ai' ) : __( 'Previously used environments', 'fotogenic-ai' ));
                    library.items.forEach((item) => {
                        const card = element('button', 'fotogenic-ai-library-card');
                        card.type = 'button';
                        card.setAttribute('aria-pressed', item.id === draftId ? 'true' : 'false');
                        card.classList.toggle('is-selected', item.id === draftId);
                        const image = element('span', 'fotogenic-ai-library-card__image');
                        if (item.thumbUrl || item.fullUrl) {
                            const preview = element('img');
                            preview.src = item.thumbUrl || item.fullUrl;
                            preview.alt = '';
                            image.appendChild(preview);
                        } else {
							const icon = icons.create('image-square', { weight: 'regular', size: 28 });
                            image.appendChild(icon);
                        }
                        if (item.id === draftId) {
                            const check = element('span', 'fotogenic-ai-library-card__check');
                            check.appendChild(icons.create('check', { weight: 'bold', size: 12 }));
                            image.appendChild(check);
                        }
                        const visibleName = (item.name || sprintf(model ? __( 'Model %d', 'fotogenic-ai' ) : __( 'Environment %d', 'fotogenic-ai' ), item.id))
                            .replace(/\.[^.]+$/, '')
                            .replaceAll('-', ' ');
                        card.append(
                            image,
                            element('strong', '', visibleName),
                            element('small', '', model ? __( 'Fotogenic model', 'fotogenic-ai' ) : __( 'Previously used', 'fotogenic-ai' ))
                        );
                        card.addEventListener('click', () => {
                            draftId = item.id;
                            grid.querySelectorAll('.fotogenic-ai-library-card').forEach((button) => {
                                const selected = button === card;
                                button.classList.toggle('is-selected', selected);
                                button.setAttribute('aria-pressed', selected ? 'true' : 'false');
                                button.querySelector('.fotogenic-ai-library-card__check')?.remove();
                                if (selected) {
                                    const check = element('span', 'fotogenic-ai-library-card__check');
                                    check.appendChild(icons.create('check', { weight: 'bold', size: 12 }));
                                    button.querySelector('.fotogenic-ai-library-card__image')?.appendChild(check);
                                }
                            });
                            overlay.applyButton.disabled = false;
                            overlay.applyButton.textContent = model ? __( 'Apply model', 'fotogenic-ai' ) : __( 'Apply environment', 'fotogenic-ai' );
                        });
                        grid.appendChild(card);
                    });
                    body.appendChild(grid);
                }
                if (library.total > library.perPage) {
                    const pages = Math.max(1, Math.ceil(library.total / library.perPage));
                    const pagination = element('div', 'fotogenic-ai-library-pagination');
					const previous = element('button', 'fotogenic-ai-library-pagination__button');
                    previous.type = 'button';
					previous.setAttribute('aria-label', __( 'Previous reference page', 'fotogenic-ai' ));
					previous.appendChild(icons.create('arrow-left', { size: 14 }));
                    previous.disabled = library.page <= 1;
                    previous.addEventListener('click', () => { page = Math.max(1, library.page - 1); renderLibrary(body, overlay); });
					const count = element('span', '', sprintf(__( '%1$d / %2$d', 'fotogenic-ai' ), library.page, pages));
					const next = element('button', 'fotogenic-ai-library-pagination__button');
                    next.type = 'button';
					next.setAttribute('aria-label', __( 'Next reference page', 'fotogenic-ai' ));
					next.appendChild(icons.create('arrow-right', { size: 14 }));
                    next.disabled = library.page >= pages;
                    next.addEventListener('click', () => { page = Math.min(pages, library.page + 1); renderLibrary(body, overlay); });
                    pagination.append(previous, count, next);
                    body.appendChild(pagination);
                }
                overlay.applyButton.disabled = draftId <= 0;
                overlay.applyButton.textContent = draftId > 0
                    ? (model ? __( 'Apply model', 'fotogenic-ai' ) : __( 'Apply environment', 'fotogenic-ai' ))
                    : (model ? __( 'Choose a model', 'fotogenic-ai' ) : __( 'Choose an environment', 'fotogenic-ai' ));
            };
            const overlay = openContainedOverlay({
                className: `fotogenic-ai-reference-library-layer is-${type}`,
                title: model ? __( 'Choose a model', 'fotogenic-ai' ) : __( 'Choose an environment', 'fotogenic-ai' ),
                headingTag: 'h3',
                closeLabel: model
                    ? __( 'Close model chooser', 'fotogenic-ai' )
                    : __( 'Close environment chooser', 'fotogenic-ai' ),
                description: model
                    ? __( 'Select one saved WordPress reference for this recipe.', 'fotogenic-ai' )
                    : __( 'Select one previously used reference for this recipe.', 'fotogenic-ai' ),
                returnFocus,
                renderBody: renderLibrary,
                renderFooter(footer, overlay) {
                    const apply = element('button', 'fotogenic-ai-configuration-apply');
                    apply.type = 'button';
                    apply.disabled = draftId <= 0;
                    apply.textContent = draftId > 0
                        ? (model ? __( 'Apply model', 'fotogenic-ai' ) : __( 'Apply environment', 'fotogenic-ai' ))
                        : (model ? __( 'Choose a model', 'fotogenic-ai' ) : __( 'Choose an environment', 'fotogenic-ai' ));
                    apply.addEventListener('click', () => {
                        if (draftId <= 0) return;
                        applyValue(path, draftId);
						closeContainedOverlay({ restoreFocus: type !== 'model', immediate: true });
                        if (type === 'model') {
                            render(workflow, route);
                            window.requestAnimationFrame(() => {
                                controls.get(path.join('.'))?.focusControl?.focus?.({ preventScroll: true });
                            });
                        }
                    });
                    overlay.applyButton = apply;
                    footer.appendChild(apply);
                    footer.hidden = model && view !== 'collection';
                },
            });
            return overlay;
        };

        const setToolsStatus = (message, state = '') => {
            toolsMessage = String(message || '');
            toolsMessageState = String(state || '');
            if (!toolsStatus) return;
            toolsStatus.textContent = toolsMessage;
            toolsStatus.dataset.state = toolsMessageState;
            toolsStatus.hidden = !toolsMessage;
        };

        const normalizePresetEntries = (payload) => {
            const entries = [];
            const seen = new Set();
            (Array.isArray(payload?.presets) ? payload.presets : []).some((preset) => {
                const uuid = String(preset?.uuid || '').trim().slice(0, 64);
                const name = String(preset?.name || '').trim().slice(0, 60);
                if (!uuid || !name || seen.has(uuid)) return false;
                seen.add(uuid);
                entries.push({
                    uuid,
                    name,
                    description: String(preset?.description || '').trim().slice(0, 160),
                });
                return entries.length >= 100;
            });
            return entries;
        };

        const applyPresetSnapshot = (snapshot) => {
            if (!isRecord(snapshot)) return false;
            const keys = Object.keys(snapshot);
            if (
                keys.length !== 5
                || !['schemaVersion', 'workflow', 'sourceType', 'scope', 'recipe'].every((key) => keys.includes(key))
                || snapshot.schemaVersion !== 1
                || snapshot.workflow !== route.workflow
                || snapshot.sourceType !== route.sourceType
                || snapshot.scope !== route.scope
                || !isRecord(snapshot.recipe)
            ) {
                return false;
            }
            const normalized = Studio.store.normalizeRecipe(snapshot.recipe, workflow.recipe, route, manifest.optionSources);
            if (
                normalized.issues.length
                || Studio.store.stableStringify(normalized.value)
                    !== Studio.store.stableStringify(snapshot.recipe)
            ) {
                return false;
            }
			commitRecipe(normalized.value);
            return true;
        };

        const loadPresets = async () => {
            listError = '';
            if (typeof transport?.listPresets !== 'function') {
                listBusy = false;
                listError = __( 'Saved presets are unavailable.', 'fotogenic-ai' );
                if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
                return;
            }
            const expectedRoute = routeKey(route);
            const token = ++listToken;
            listBusy = true;
            setToolsStatus(__( 'Loading saved presets…', 'fotogenic-ai' ));
            if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);

            const cachedResponse = presetCache.get(expectedRoute);
            let request = null;
            if (cachedResponse) {
                request = Promise.resolve(cachedResponse);
            } else if (listRequest && listRequestRoute === expectedRoute) {
                request = listRequest;
            } else {
                listController?.abort?.();
                listController = typeof AbortController === 'function' ? new AbortController() : null;
                listRequestRoute = expectedRoute;
                listRequest = transport.listPresets(route, { signal: listController?.signal });
                request = listRequest;
            }

            const response = await request;
            if (request === listRequest) {
                listController = null;
                listRequest = null;
                listRequestRoute = '';
            }
            if (token !== listToken || expectedRoute !== routeKey(route) || response.aborted) return;
            listBusy = false;
            if (!response.ok) {
                listError = response.message || __( 'Saved presets are unavailable.', 'fotogenic-ai' );
                setToolsStatus('');
                if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
                return;
            }
            presets = normalizePresetEntries(response.data);
            presetCache.set(expectedRoute, response);
            setToolsStatus(presets.length ? '' : __( 'No saved presets for this workflow yet.', 'fotogenic-ai' ));
            if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
        };

        const loadPreset = async (presetUuid) => {
            if (actionBusy) return;
            const previousUuid = activePresetUuid;
            const expectedRoute = routeKey(route);
            const token = ++actionToken;
            actionController?.abort?.();
            actionController = typeof AbortController === 'function' ? new AbortController() : null;
            actionBusy = true;
            toolsRoot.setAttribute('aria-busy', 'true');
            setToolsStatus(__( 'Loading preset…', 'fotogenic-ai' ));
            if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
            const response = await transport.getPreset(presetUuid, route, { signal: actionController?.signal });
            if (token !== actionToken || expectedRoute !== routeKey(route) || response.aborted) return;
            actionController = null;
            actionBusy = false;
            toolsRoot.removeAttribute('aria-busy');
            const snapshot = response.data?.preset?.snapshot;
            if (!response.ok || !applyPresetSnapshot(snapshot)) {
                activePresetUuid = previousUuid;
                setToolsStatus(response.message || __( 'This preset is incompatible and was not applied.', 'fotogenic-ai' ), 'error');
                if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
                return;
            }
            activePresetUuid = presetUuid;
            setToolsStatus(__( 'Preset applied.', 'fotogenic-ai' ), 'success');
			closeContainedOverlay({ restoreFocus: false, immediate: true });
            render(workflow, route);
            window.requestAnimationFrame(() => {
                toolsMount?.querySelector('.fotogenic-ai-recipe-footer-actions-trigger')?.focus({ preventScroll: true });
            });
        };

		const buildPresetSnapshot = () => ({
            schemaVersion: 1,
            workflow: route.workflow,
            sourceType: route.sourceType,
            scope: route.scope,
			recipe: clone(canonicalRecipe()),
        });

        const savePreset = async ({ presetUuid = '', name = '' } = {}) => {
            if (actionBusy) return;
            const expectedRoute = routeKey(route);
            const token = ++actionToken;
            const snapshot = buildPresetSnapshot();
            listToken += 1;
            listController?.abort?.();
            listController = null;
            listRequest = null;
            listRequestRoute = '';
            listBusy = false;
            actionController?.abort?.();
            actionController = typeof AbortController === 'function' ? new AbortController() : null;
            actionBusy = true;
            toolsRoot.setAttribute('aria-busy', 'true');
            setToolsStatus(__( 'Saving preset…', 'fotogenic-ai' ));
            if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
            const response = await transport.savePreset({
                presetUuid,
                name,
                snapshot,
            }, { signal: actionController?.signal });
            if (token !== actionToken || expectedRoute !== routeKey(route) || response.aborted) return;
            actionController = null;
            actionBusy = false;
            toolsRoot.removeAttribute('aria-busy');
            if (!response.ok) {
                setToolsStatus(response.message || __( 'The preset could not be saved.', 'fotogenic-ai' ), 'error');
                if (activeOverlay?.kind === 'presets') {
                    renderPresetsBody(activeOverlay.body, activeOverlay);
                    const failedNameInput = nameInput;
                    const failedEditor = failedNameInput?.closest('form');
                    if (failedNameInput && failedEditor) {
                        failedEditor.hidden = false;
                        failedNameInput.value = name;
                        window.requestAnimationFrame(() => failedNameInput.focus({ preventScroll: true }));
                    }
                }
                return;
            }
            presets = normalizePresetEntries(response.data);
            presetCache.set(expectedRoute, response);
            listError = '';
            activePresetUuid = String(response.data?.savedPresetUuid || presetUuid || '');
            if (nameInput) nameInput.value = '';
            setToolsStatus(__( 'Preset saved.', 'fotogenic-ai' ), 'success');
            if (activeOverlay?.kind === 'presets') {
                renderPresetsBody(activeOverlay.body, activeOverlay);
                const savedPreset = [...activeOverlay.body.querySelectorAll('[data-preset-uuid]')]
                    .find((node) => node.dataset.presetUuid === activePresetUuid);
                window.requestAnimationFrame(() => {
                    savedPreset?.querySelector('.fotogenic-ai-primary-small')?.focus({ preventScroll: true });
                });
            }
        };

        const deletePreset = async () => {
            if (!activePresetUuid || actionBusy) return;
            const deletingUuid = activePresetUuid;
            const expectedRoute = routeKey(route);
            const token = ++actionToken;
            actionController?.abort?.();
            actionController = typeof AbortController === 'function' ? new AbortController() : null;
            actionBusy = true;
            toolsRoot.setAttribute('aria-busy', 'true');
            setToolsStatus(__( 'Removing preset…', 'fotogenic-ai' ));
            if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
            const response = await transport.deletePreset(deletingUuid, route, { signal: actionController?.signal });
            if (token !== actionToken || expectedRoute !== routeKey(route) || response.aborted) return;
            actionController = null;
            actionBusy = false;
            toolsRoot.removeAttribute('aria-busy');
            if (!response.ok) {
                setToolsStatus(response.message || __( 'The preset could not be removed.', 'fotogenic-ai' ), 'error');
                if (activeOverlay?.kind === 'presets') renderPresetsBody(activeOverlay.body, activeOverlay);
                return;
            }
            presets = normalizePresetEntries(response.data);
            presetCache.set(expectedRoute, response);
            listError = '';
            activePresetUuid = '';
            setToolsStatus(__( 'Preset deleted.', 'fotogenic-ai' ), 'success');
            if (activeOverlay?.kind === 'presets') {
                renderPresetsBody(activeOverlay.body, activeOverlay);
                window.requestAnimationFrame(() => {
                    activeOverlay?.panel.querySelector('.fotogenic-ai-configuration-drawer__close')?.focus({ preventScroll: true });
                });
            }
        };

        const autoConfigurationReadiness = () => {
            const draft = canonicalDraft();
            if (route.workflow !== 'product_images' || draft.scope !== 'single') {
                return { available: false, ready: false, reason: '' };
            }
			if (!isAuthConnected()) {
				return { available: true, ready: false, reason: __( 'Reconnect Fotogenic to request server analysis.', 'fotogenic-ai' ) };
			}
			if (!Object.keys(manifest.optionSources?.configuration || {}).length) {
				return { available: true, ready: false, reason: __( 'Available after configuration options finish loading.', 'fotogenic-ai' ) };
			}
            const sourceAvailable = route.sourceType === 'product'
                ? typeof transport?.getProductContext === 'function'
                : Boolean(draft.sourcePolicy?.attachmentIds?.length);
            if (draft.selection?.selectedIds?.length !== 1 || !sourceAvailable) {
                return { available: true, ready: false, reason: __( 'Choose the source image before auto-configuring.', 'fotogenic-ai' ) };
            }
			return { available: true, ready: true, reason: __( 'Analyse the selected source and propose supported settings.', 'fotogenic-ai' ) };
        };

        const buildAutoConfigurationRequest = (sourceAttachmentIds) => {
            const draft = canonicalDraft();
            const references = {};
            REFERENCE_FIELDS.forEach((field) => {
                const id = Math.floor(Number(draft.recipe?.[field]));
                if (id > 0) references[field] = id;
            });
            return {
                schemaVersion: 1,
                workflow: 'product_images',
                sourceType: route.sourceType,
                scope: 'single',
                subjectId: draft.selection.selectedIds[0],
                sourceAttachmentIds: sourceAttachmentIds.slice(),
                references,
            };
        };

        const resolveAutoConfigurationSourceAttachments = async (signal) => {
            const draft = canonicalDraft();
            if (route.sourceType !== 'product') {
                const ids = (Array.isArray(draft.sourcePolicy?.attachmentIds) ? draft.sourcePolicy.attachmentIds : [])
                    .map((value) => Math.floor(Number(value)))
                    .filter((value, index, values) => value > 0 && values.indexOf(value) === index);
                return ids.length
                    ? { ok: true, ids }
                    : { ok: false, message: __( 'Choose the source image before auto-configuring.', 'fotogenic-ai' ) };
            }
            const subjectId = Math.floor(Number(draft.selection?.selectedIds?.[0]));
            const response = await transport.getProductContext(subjectId, { signal });
            if (!response.ok || response.aborted) {
                return {
                    ok: false,
                    aborted: response.aborted === true,
                    message: response.message || __( 'The selected Product images are unavailable.', 'fotogenic-ai' ),
                };
            }
            const images = typeof Studio.sourcePicker?.normalizeProductImages === 'function'
                ? Studio.sourcePicker.normalizeProductImages(response.data)
                : [];
            const eligible = images.filter((image) => image.eligible !== false);
            const sourceMode = String(draft.sourcePolicy?.sourceMode || 'featured');
            const candidates = sourceMode === 'gallery_only'
                ? eligible.filter((image) => image.role === 'gallery')
                : (sourceMode === 'featured_gallery'
                    ? eligible
                    : eligible.filter((image) => image.role === 'featured'));
            const sourceDefinition = workflow.sources?.find((source) => source.id === route.sourceType);
            const primaryMaximum = Math.max(1, Number(sourceDefinition?.inputCardinality?.single?.primary?.maximum) || 1);
            const totalMaximum = Math.max(primaryMaximum, Number(sourceDefinition?.inputCardinality?.single?.total?.maximum) || primaryMaximum);
            const referenceCount = REFERENCE_FIELDS.reduce(
                (count, key) => count + (Number(draft.recipe?.[key]) > 0 ? 1 : 0),
                0
            );
            const maximum = Math.min(primaryMaximum, Math.max(1, totalMaximum - referenceCount));
            const ids = candidates.slice(0, maximum).map((image) => image.id);
            return ids.length
                ? { ok: true, ids }
                : { ok: false, message: __( 'The selected Product image mode has no eligible source image.', 'fotogenic-ai' ) };
        };

        const prepareAutoConfigurationPatch = (patch) => {
            if (!isRecord(patch) || Object.keys(patch).some((key) => !AUTO_PATCH_FIELDS.has(key))) return false;
            const current = clone(canonicalDraft().recipe || {});
            const next = { ...current };
            if (Object.hasOwn(patch, 'selections')) {
                if (!isRecord(patch.selections)) return false;
                const selectionSchema = workflow.recipe?.fields?.selections?.fields || {};
                const merged = isRecord(current.selections) ? clone(current.selections) : {};
                for (const [key, value] of Object.entries(patch.selections)) {
                    const field = selectionSchema[key];
                    const id = isRecord(value) && typeof value.id === 'string' ? value.id : '';
                    const optionIds = resolveOptions(manifest, field || {}, ['selections', key]).map((option) => option.value);
                    if (!field || !id || !optionIds.includes(id) || (key === 'aspectRatio' && id.toLowerCase() === 'auto')) return false;
                    merged[key] = { id };
                }
                next.selections = merged;
            }
            for (const field of ['customInstructions', 'autoConfigDescription']) {
                if (Object.hasOwn(patch, field)) {
                    if (typeof patch[field] !== 'string') return false;
                    next[field] = patch[field];
                }
            }
            for (const field of ['autoConfigUsed', 'personPresence', 'includeFace', 'includeBody', 'lookAtCamera']) {
                if (Object.hasOwn(patch, field)) {
                    if (typeof patch[field] !== 'boolean') return false;
                    next[field] = patch[field];
                }
            }
            if (!Number.isInteger(current.subjectImageId) || current.subjectImageId <= 0) {
                delete next.includeFace;
                delete next.includeBody;
                delete next.lookAtCamera;
            }
            const normalized = Studio.store.normalizeRecipe(next, workflow.recipe, route, manifest.optionSources);
            if (normalized.issues.length) return false;
			return normalized.value;
        };

		const runAutoConfiguration = async () => {
            const readiness = autoConfigurationReadiness();
            if (!readiness.ready || autoController || typeof transport?.autoConfigure !== 'function') return;
            const token = ++autoToken;
            autoSignature = Studio.store.stableStringify(canonicalDraft());
            autoController = typeof AbortController === 'function' ? new AbortController() : null;
            pendingAutoProposal = { state: 'loading' };
            if (activeOverlay?.kind === 'auto') renderAutoConfigurationBody(activeOverlay.body, activeOverlay);
            const sources = await resolveAutoConfigurationSourceAttachments(autoController?.signal);
            if (token !== autoToken || sources.aborted) return;
            if (!sources.ok) {
                autoController = null;
                pendingAutoProposal = {
                    state: 'error',
                    message: sources.message || __( 'The source images could not be prepared for configuration.', 'fotogenic-ai' ),
                };
                if (activeOverlay?.kind === 'auto') renderAutoConfigurationBody(activeOverlay.body, activeOverlay);
                return;
            }
            const response = await transport.autoConfigure(buildAutoConfigurationRequest(sources.ids), { signal: autoController?.signal });
            if (token !== autoToken || response.aborted) return;
            autoController = null;
            if (autoSignature !== Studio.store.stableStringify(canonicalDraft())) {
                pendingAutoProposal = {
                    state: 'error',
                    message: __( 'The draft changed, so the stale configuration was not applied.', 'fotogenic-ai' ),
                };
                if (activeOverlay?.kind === 'auto') renderAutoConfigurationBody(activeOverlay.body, activeOverlay);
                return;
            }
            const recipe = response.ok ? prepareAutoConfigurationPatch(response.data?.recipePatch) : false;
            if (!response.ok || !recipe) {
                pendingAutoProposal = {
                    state: 'error',
                    message: response.message || __( 'Configuration could not be generated. Try again.', 'fotogenic-ai' ),
                };
                if (activeOverlay?.kind === 'auto') renderAutoConfigurationBody(activeOverlay.body, activeOverlay);
                return;
            }
            pendingAutoSignature = autoSignature;
            pendingAutoProposal = {
                state: 'ready',
                recipe,
                patch: clone(response.data.recipePatch),
            };
			if (activeOverlay?.kind === 'auto') renderAutoConfigurationBody(activeOverlay.body, activeOverlay);
		};

		const cancelAutoConfiguration = () => {
			autoToken += 1;
			autoController?.abort?.();
			autoController = null;
			autoSignature = '';
			pendingAutoProposal = null;
			pendingAutoSignature = '';
			syncTools();
		};

		const syncTools = () => {
			syncEnhancementRunItemCount();
			const nextCampaignSignature = workflow?.id === 'campaign_set'
				? campaignGroups().map((group) => group.id).join(':')
				: '';
			if (nextCampaignSignature !== renderedCampaignGroupSignature) {
				render(workflow, route);
				return;
			}
			if (!toolsRoot) return;
            const readiness = autoConfigurationReadiness();
            const autoButton = toolsRoot.querySelector('[data-fa-auto-configure]');
            const autoReason = toolsRoot.querySelector('[data-fa-auto-configure-reason]');
            if (autoButton) {
                autoButton.disabled = !readiness.ready || Boolean(autoController);
                const title = autoButton.querySelector('strong');
                if (title) {
                    title.textContent = autoController
                        ? __( 'Generating settings…', 'fotogenic-ai' )
                        : __( 'Use automatic settings', 'fotogenic-ai' );
                }
            }
            if (autoReason) autoReason.textContent = readiness.reason;
            if (autoController && autoSignature !== Studio.store.stableStringify(canonicalDraft())) {
                autoToken += 1;
                autoController.abort?.();
                autoController = null;
                toolsRoot.removeAttribute('aria-busy');
                pendingAutoProposal = {
                    state: 'error',
                    message: __( 'Auto-configuration stopped because the draft changed. Try again when ready.', 'fotogenic-ai' ),
                };
                if (activeOverlay?.kind === 'auto') renderAutoConfigurationBody(activeOverlay.body, activeOverlay);
            }
            syncRecipeControls();
            syncSectionNavigation();
        };

        const resetActiveSection = () => {
            const entry = sectionButtons.get(activeSectionId);
            if (!entry?.section) return;
            if (entry.section.id === 'delivery') {
                if (workflow?.id === 'campaign_set') {
					commitCampaignResultPolicy({ assignmentMode: 'review' });
				} else {
					onSourcePolicyChange?.({ ...(canonicalDraft().sourcePolicy || {}), sourceMode: 'featured' });
					onResultPolicyChange?.({ assignmentMode: 'review' });
				}
                return;
            }
            const defaults = Studio.store.createDefaultRecipe(workflow.recipe, route, manifest.optionSources);
            const recipe = entry.section.entries.reduce((nextRecipe, fieldEntry) => {
                const path = [...fieldEntry.path, fieldEntry.name];
                return setAtPath(nextRecipe, path, getAtPath(defaults, path));
            }, editableRecipe());
            commitRecipe(recipe);
        };

        const resetRecipeToDefaults = () => {
            commitRecipe(Studio.store.createDefaultRecipe(workflow.recipe, route, manifest.optionSources));
        };

        const closeTools = ({ focus = false, immediate = false } = {}) => {
			if (!toolsRoot?.classList.contains('is-open')) return;
			toolsRoot.classList.remove('is-open');
			const trigger = toolsRoot.querySelector('.fotogenic-ai-recipe-footer-actions-trigger');
			const body = toolsRoot.querySelector('.fotogenic-ai-recipe-footer-actions-popover');
			trigger?.setAttribute('aria-expanded', 'false');
			trigger?.classList.remove('is-open');
			window.clearTimeout(toolsCloseTimer);
			if (body) {
				body.classList.remove('is-open');
				body.classList.add('is-closing');
				const delay = immediate || window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ? 0 : 140;
				const finish = () => {
					toolsCloseTimer = 0;
					body.classList.remove('is-closing');
					body.hidden = true;
				};
				if (delay) toolsCloseTimer = window.setTimeout(finish, delay);
				else finish();
			}
			if (focus) trigger?.focus?.();
        };

        const configurationAction = ({ icon, title, description, onClick, disabled = false, forward = false }) => {
            const button = element('button', 'fotogenic-ai-recipe-footer-action');
            button.type = 'button';
			button.setAttribute('role', 'menuitem');
            button.disabled = disabled;
			const iconNode = icons.create(icon, { weight: 'regular', size: 17 });
			const copy = element('span', 'fotogenic-ai-recipe-footer-action-copy');
            copy.append(
                element('strong', '', title),
                element('small', '', description)
            );
			button.append(iconNode, copy);
			if (forward) button.appendChild(icons.create('arrow-right', { weight: 'regular', size: 14 }));
            button.addEventListener('click', onClick);
            return button;
        };

        const openPresetDeleteConfirmation = (preset, trigger, overlay) => {
            const confirmation = element('section', 'fotogenic-ai-preset-delete-confirmation');
            const titleId = `fotogenic-ai-delete-preset-${preset.uuid}`;
            const descriptionId = `${titleId}-description`;
            confirmation.setAttribute('role', 'alertdialog');
            confirmation.setAttribute('aria-modal', 'true');
            confirmation.setAttribute('aria-labelledby', titleId);
            confirmation.setAttribute('aria-describedby', descriptionId);
            const copy = element('div');
			const icon = icons.create('warning', { weight: 'fill', size: 18 });
            const text = element('span');
            const title = element('strong', '', __( 'Delete this preset?', 'fotogenic-ai' ));
            title.id = titleId;
            const description = element('small', '', __( 'This removes the saved settings from this site. Selected sources are not affected.', 'fotogenic-ai' ));
            description.id = descriptionId;
            text.append(title, description);
            copy.append(icon, text);
            const actions = element('footer');
            const cancel = element('button', 'fotogenic-ai-secondary-small', __( 'Cancel', 'fotogenic-ai' ));
            cancel.type = 'button';
            const remove = element('button', 'fotogenic-ai-danger-button', __( 'Delete preset', 'fotogenic-ai' ));
            remove.type = 'button';
            const closeConfirmation = ({ restore = true } = {}) => {
                confirmation.remove();
                overlay.deleteConfirmation = null;
                overlay.panel.setAttribute('aria-modal', 'true');
                refreshOverlayIsolation(overlay);
                if (restore) window.requestAnimationFrame(() => trigger.focus({ preventScroll: true }));
            };
            cancel.addEventListener('click', () => closeConfirmation());
            remove.addEventListener('click', async () => {
                activePresetUuid = preset.uuid;
                closeConfirmation({ restore: false });
                await deletePreset();
            });
            actions.append(cancel, remove);
            confirmation.append(copy, actions);
            confirmation.tabIndex = -1;
            overlay.body.appendChild(confirmation);
            overlay.deleteConfirmation = { node: confirmation, close: closeConfirmation };
            overlay.panel.removeAttribute('aria-modal');
            refreshOverlayIsolation(overlay);
            window.requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
        };

        const renderPresetsBody = (body, overlay) => {
            if (!activeOverlay || activeOverlay !== overlay) return;
            overlay.kind = 'presets';
            body.replaceChildren();
            nameInput = null;
            const saveCurrent = element('button', 'fotogenic-ai-preset-save-current', __( 'Save current settings as preset', 'fotogenic-ai' ));
            saveCurrent.type = 'button';
            const editor = element('form', 'fotogenic-ai-preset-editor');
            editor.hidden = true;
            const editorLabel = element('label');
            editorLabel.appendChild(element('span', '', __( 'Preset name', 'fotogenic-ai' )));
            nameInput = element('input');
            nameInput.type = 'text';
            nameInput.maxLength = 60;
            nameInput.placeholder = __( 'e.g. Clean catalog launch', 'fotogenic-ai' );
            editorLabel.appendChild(nameInput);
            const editorActions = element('div');
            const cancel = element('button', 'fotogenic-ai-secondary-small', __( 'Cancel', 'fotogenic-ai' ));
            cancel.type = 'button';
            const save = element('button', 'fotogenic-ai-primary-small', __( 'Save preset', 'fotogenic-ai' ));
            save.type = 'submit';
            editorActions.append(cancel, save);
            editor.append(editorLabel, editorActions);
            saveCurrent.addEventListener('click', () => {
                editor.hidden = false;
                nameInput.focus({ preventScroll: true });
            });
            cancel.addEventListener('click', () => {
                editor.hidden = true;
                nameInput.value = '';
                saveCurrent.focus({ preventScroll: true });
            });
            editor.addEventListener('submit', (event) => {
                event.preventDefault();
                const name = nameInput.value.trim();
                if (name.length < 2 || name.length > 60) {
                    setToolsStatus(__( 'Enter a preset name between 2 and 60 characters.', 'fotogenic-ai' ), 'error');
                    return;
                }
                savePreset({ name });
            });
            toolsStatus = element('p', 'fotogenic-ai-preset-notice');
            toolsStatus.setAttribute('role', 'status');
            toolsStatus.setAttribute('aria-live', 'polite');
            const visibleMessage = listBusy
                ? __( 'Loading saved presets…', 'fotogenic-ai' )
                : (actionBusy ? __( 'Updating saved presets…', 'fotogenic-ai' ) : toolsMessage);
            toolsStatus.textContent = visibleMessage;
            toolsStatus.dataset.state = listBusy || actionBusy ? '' : toolsMessageState;
            toolsStatus.hidden = !visibleMessage
                || listBusy || Boolean(listError)
                || (!listBusy && !actionBusy && !['error', 'success'].includes(toolsMessageState));
            const list = element('div', 'fotogenic-ai-preset-list');
            list.setAttribute('aria-busy', listBusy ? 'true' : 'false');
            if (listBusy) {
                list.appendChild(requestState({ message: __( 'Loading saved presets…', 'fotogenic-ai' ), loading: true }));
            } else if (listError) {
                list.appendChild(requestState({ message: listError, onRetry: loadPresets }));
            } else {
                presets.forEach((preset) => {
                    const article = element('article', 'fotogenic-ai-preset-card');
                    article.dataset.presetUuid = preset.uuid;
                    const header = element('div', 'fotogenic-ai-preset-card__header');
                    const copy = element('div', 'fotogenic-ai-preset-card__copy');
                    copy.append(
                        element('strong', '', preset.name),
                        element('p', '', preset.description || __( 'Saved settings for this workflow.', 'fotogenic-ai' ))
                    );
                    const apply = element('button', 'fotogenic-ai-primary-small fotogenic-ai-preset-apply', __( 'Apply', 'fotogenic-ai' ));
                    apply.type = 'button';
                    apply.disabled = actionBusy;
                    apply.addEventListener('click', () => {
                        activePresetUuid = preset.uuid;
                        loadPreset(preset.uuid);
                    });
                    header.append(copy, apply);
                    const meta = element('footer', 'fotogenic-ai-preset-card__meta');
                    const compatible = element('small', 'fotogenic-ai-preset-compatible');
                    compatible.append(
                        icons.create('check-circle', { weight: 'fill', size: 12 }),
                        document.createTextNode(__( 'Ready for this workflow.', 'fotogenic-ai' ))
                    );
                    const actions = element('div', 'fotogenic-ai-preset-card__utilities');
                    const update = element('button', 'fotogenic-ai-preset-utility-button');
                    update.type = 'button';
                    update.disabled = actionBusy;
                    update.append(
                        icons.create('arrows-clockwise', { weight: 'regular', size: 13 }),
                        element('span', '', __( 'Update', 'fotogenic-ai' ))
                    );
                    update.addEventListener('click', () => {
                        activePresetUuid = preset.uuid;
                        savePreset({ presetUuid: preset.uuid });
                    });
                    const remove = element('button', 'fotogenic-ai-preset-utility-button is-danger');
                    remove.type = 'button';
					const trash = icons.create('trash', { weight: 'regular', size: 14 });
                    remove.append(trash, element('span', '', __( 'Delete', 'fotogenic-ai' )));
                    remove.addEventListener('click', () => openPresetDeleteConfirmation(preset, remove, overlay));
                    actions.append(update, remove);
                    meta.append(compatible, actions);
                    article.append(header, meta);
                    list.appendChild(article);
                });
                if (!presets.length) {
                    const empty = element('div', 'fotogenic-ai-preset-empty');
                    empty.append(
                        element('strong', '', __( 'No saved presets yet', 'fotogenic-ai' )),
                        element('p', '', __( 'Save the current recipe to reuse it later.', 'fotogenic-ai' ))
                    );
                    list.appendChild(empty);
                }
            }
            body.append(saveCurrent, editor, toolsStatus, list);
        };

        const openPresetsOverlay = (returnFocus) => {
            const overlay = openContainedOverlay({
                className: 'fotogenic-ai-configuration-tool-layer is-presets',
                title: __( 'Saved presets', 'fotogenic-ai' ),
                description: __( 'Reuse saved settings without changing the selected sources.', 'fotogenic-ai' ),
                closeLabel: __( 'Close configuration tool', 'fotogenic-ai' ),
                returnFocus,
                initialFocus: 'close',
                renderBody: renderPresetsBody,
                onClose: () => {
                    listToken += 1;
                    actionToken += 1;
                    listController?.abort?.();
                    actionController?.abort?.();
                    listController = null;
                    actionController = null;
                    listRequest = null;
                    listRequestRoute = '';
                    listBusy = false;
                    listError = '';
                    if (actionBusy) presetCache.delete(routeKey(route));
                    actionBusy = false;
                    toolsRoot.removeAttribute('aria-busy');
                },
            });
            overlay.kind = 'presets';
            loadPresets();
        };

        const proposalEntries = (patch) => {
            const entries = [];
            if (isRecord(patch?.selections)) {
                Object.entries(patch.selections).forEach(([key, value]) => {
                    const field = workflow.recipe?.fields?.selections?.fields?.[key] || {};
                    const option = resolveOptions(manifest, field, ['selections', key])
                        .find((candidate) => candidate.value === String(value?.id || ''));
                    if (option) entries.push({ label: fieldLabel(key), value: option.label, wide: false });
                });
            }
            ['personPresence', 'includeFace', 'includeBody', 'lookAtCamera'].forEach((key) => {
                if (!Object.hasOwn(patch || {}, key)) return;
                entries.push({
                    label: fieldLabel(key),
                    value: patch[key] ? __( 'Yes', 'fotogenic-ai' ) : __( 'No', 'fotogenic-ai' ),
                    wide: false,
                });
            });
            if (typeof patch?.customInstructions === 'string' && patch.customInstructions) {
                entries.push({
                    label: fieldLabel('customInstructions'),
                    value: patch.customInstructions.trim().slice(0, 320),
                    wide: true,
                });
            }
            if (typeof patch?.autoConfigDescription === 'string' && patch.autoConfigDescription) {
                entries.push({
                    label: fieldLabel('autoConfigDescription'),
                    value: patch.autoConfigDescription.trim().slice(0, 320),
                    wide: true,
                });
            }
            return entries.slice(0, 18);
        };

        const renderAutoConfigurationBody = (body, overlay) => {
            if (!activeOverlay || activeOverlay !== overlay) return;
            overlay.kind = 'auto';
            body.replaceChildren();
			const panel = element('div', 'fotogenic-ai-automatic-configuration-panel');
			const readiness = autoConfigurationReadiness();
			const state = pendingAutoProposal?.state || 'idle';
			panel.classList.toggle('is-ready', state === 'ready');
            if (state === 'loading') {
                const loading = element('div', 'fotogenic-ai-automatic-analysis-loading');
                loading.setAttribute('role', 'status');
				const loadingIcon = icons.create('arrows-clockwise', { weight: 'regular', size: 24 });
				loadingIcon.classList.add('fotogenic-ai-icon--spin');
				loading.append(
					loadingIcon,
                    element('strong', '', __( 'Analysing source images…', 'fotogenic-ai' )),
                    element('small', '', __( 'Matching catalog options and output requirements.', 'fotogenic-ai' ))
                );
                panel.appendChild(loading);
            } else if (state === 'ready') {
                const heading = element('div', 'fotogenic-ai-automatic-recommendation-heading');
				const check = icons.create('check-circle', { weight: 'fill', size: 22 });
                const copy = element('div');
                copy.append(
                    element('strong', '', __( 'Recommended settings', 'fotogenic-ai' )),
                    element('p', '', __( 'Review every suggested value. Nothing changes until you apply it.', 'fotogenic-ai' ))
                );
                heading.append(check, copy);
                const recommendations = element('dl', 'fotogenic-ai-automatic-recommendations');
                proposalEntries(pendingAutoProposal.patch).forEach(({ label, value, wide }) => {
                    const item = element('div');
                    item.classList.toggle('is-wide', wide);
                    item.append(element('dt', '', label), element('dd', '', value));
                    recommendations.appendChild(item);
                });
                if (!recommendations.childElementCount) {
                    const item = element('div');
                    item.append(element('dt', '', __( 'Recipe', 'fotogenic-ai' )), element('dd', '', __( 'No supported changes', 'fotogenic-ai' )));
                    recommendations.appendChild(item);
                }
				const actions = element('div', 'fotogenic-ai-automatic-configuration-actions');
                const keep = element('button', 'fotogenic-ai-secondary-small', __( 'Keep current settings', 'fotogenic-ai' ));
                keep.type = 'button';
                keep.addEventListener('click', () => closeContainedOverlay({ restoreFocus: true }));
                const apply = element('button', 'fotogenic-ai-primary', __( 'Apply these settings', 'fotogenic-ai' ));
                apply.type = 'button';
                apply.addEventListener('click', () => {
                    if (
                        pendingAutoSignature !== Studio.store.stableStringify(canonicalDraft())
                        || !isRecord(pendingAutoProposal?.recipe)
                    ) {
                        pendingAutoProposal = { state: 'error', message: __( 'The draft changed, so this proposal is stale. Analyse the current sources again.', 'fotogenic-ai' ) };
                        renderAutoConfigurationBody(body, overlay);
                        return;
                    }
                    commitRecipe(pendingAutoProposal.recipe);
                    pendingAutoProposal = null;
                    pendingAutoSignature = '';
                    closeContainedOverlay({ restoreFocus: false, immediate: true });
                    render(workflow, route);
                    onAutomaticSettingsApplied?.();
                    window.requestAnimationFrame(() => {
                        toolsMount?.querySelector('.fotogenic-ai-recipe-footer-actions-trigger')?.focus({ preventScroll: true });
                    });
                });
                actions.append(keep, apply);
				panel.append(heading, recommendations, actions);
            } else {
				const icon = icons.create('sparkle', { weight: 'fill', size: 25 });
				icon.classList.add('fotogenic-ai-automatic-configuration-icon');
                panel.append(
                    icon,
                    element('h3', '', sprintf(__( 'Analyse %d selected item', 'fotogenic-ai' ), canonicalDraft().selection?.selectedIds?.length || 0)),
                    element('p', '', __( 'The Fotogenic server will inspect source composition and return supported recipe values. This is separate from resetting fields to automatic.', 'fotogenic-ai' ))
                );
                if (state === 'error') {
                    const error = element('p', 'fotogenic-ai-preset-notice is-error', pendingAutoProposal.message || __( 'Configuration could not be generated.', 'fotogenic-ai' ));
                    error.setAttribute('role', 'alert');
                    panel.appendChild(error);
                } else if (!readiness.ready && readiness.reason) {
                    panel.appendChild(element('p', 'fotogenic-ai-preset-notice is-error', readiness.reason));
                }
                const analyze = element('button', 'fotogenic-ai-primary', state === 'error' ? __( 'Try again', 'fotogenic-ai' ) : __( 'Analyse sources', 'fotogenic-ai' ));
                analyze.type = 'button';
                analyze.disabled = !readiness.ready;
                analyze.addEventListener('click', runAutoConfiguration);
                panel.appendChild(analyze);
            }
            body.appendChild(panel);
        };

        const openAutoConfigurationOverlay = (returnFocus, { analyse = false } = {}) => {
            pendingAutoProposal = null;
            pendingAutoSignature = '';
            const overlay = openContainedOverlay({
                className: 'fotogenic-ai-configuration-tool-layer is-auto',
                title: __( 'Automatic settings', 'fotogenic-ai' ),
                description: __( 'Review the server-generated recipe before applying it.', 'fotogenic-ai' ),
                closeLabel: __( 'Close configuration tool', 'fotogenic-ai' ),
				returnFocus,
				initialFocus: 'close',
				renderBody: renderAutoConfigurationBody,
				onClose: cancelAutoConfiguration,
			});
            overlay.kind = 'auto';
            if (analyse) runAutoConfiguration();
        };

        const renderRecipeTools = () => {
			window.clearTimeout(toolsCloseTimer);
			toolsCloseTimer = 0;
            toolsDocumentHandler && document.removeEventListener('pointerdown', toolsDocumentHandler, true);
			toolsRoot = element('div', 'fotogenic-ai-recipe-tools fotogenic-ai-recipe-footer-actions-menu');
			toolsRoot.setAttribute('aria-label', __( 'Configuration actions', 'fotogenic-ai' ));
			const summary = element('button', 'fotogenic-ai-recipe-footer-actions-trigger');
			summary.type = 'button';
			const summaryIcon = icons.create('sliders-horizontal', { weight: 'regular', size: 16 });
			const summaryCaret = icons.create('caret-down', { weight: 'bold', size: 13 });
			summaryCaret.classList.add('fotogenic-ai-recipe-footer-actions-caret');
            summary.append(summaryIcon, element('span', '', __( 'Actions', 'fotogenic-ai' )), summaryCaret);
			summary.setAttribute('aria-haspopup', 'menu');
			summary.setAttribute('aria-expanded', 'false');
			summary.addEventListener('click', () => {
				const open = !toolsRoot.classList.contains('is-open');
				if (!open) {
					closeTools({ focus: true });
					return;
				}
				window.clearTimeout(toolsCloseTimer);
				toolsCloseTimer = 0;
				toolsRoot.classList.toggle('is-open', open);
				summary.setAttribute('aria-expanded', open ? 'true' : 'false');
				summary.classList.toggle('is-open', open);
				body.hidden = !open;
				body.classList.remove('is-closing');
				body.classList.add('is-open');
				if (open) {
					window.requestAnimationFrame(() => {
						body.querySelector('[role="menuitem"]:not(:disabled)')?.focus({ preventScroll: true });
					});
				}
			});
			toolsRoot.addEventListener('keydown', (event) => {
				if (!toolsRoot.classList.contains('is-open')) return;
				if (event.key === 'Escape') {
					event.preventDefault();
					closeTools({ focus: true });
					return;
				}
				if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
				const items = [...body.querySelectorAll('[role="menuitem"]:not(:disabled)')];
				if (!items.length) return;
				event.preventDefault();
				const current = items.indexOf(document.activeElement);
				if (event.key === 'Home') items[0].focus();
				else if (event.key === 'End') items.at(-1).focus();
				else if (event.key === 'ArrowDown') items[(current + 1 + items.length) % items.length].focus();
				else items[(current - 1 + items.length) % items.length].focus();
			});
            const body = element('div', 'fotogenic-ai-recipe-tools__body fotogenic-ai-recipe-footer-actions-popover');
			body.hidden = true;
			body.setAttribute('role', 'menu');
            body.setAttribute('aria-label', __( 'Configuration actions', 'fotogenic-ai' ));
            toolsRoot.append(summary, body);

            const presetToggle = configurationAction({
				icon: 'stack-simple',
                title: __( 'Saved presets', 'fotogenic-ai' ),
                description: __( 'Save or apply reusable settings.', 'fotogenic-ai' ),
                onClick() {
                    openPresetsOverlay(summary);
                },
				forward: true,
            });
            body.appendChild(presetToggle);

            const autoReadiness = autoConfigurationReadiness();
            const autoButton = configurationAction({
				icon: 'sparkle',
                title: __( 'Use automatic settings', 'fotogenic-ai' ),
                description: autoReadiness.reason || __( 'Unavailable for the current route.', 'fotogenic-ai' ),
                onClick() {
                    openAutoConfigurationOverlay(summary, { analyse: true });
                },
                disabled: !autoReadiness.ready,
				forward: true,
            });
            autoButton.setAttribute('data-fa-auto-configure', '');
            autoButton.querySelector('small')?.setAttribute('data-fa-auto-configure-reason', '');
            body.appendChild(autoButton);

            const separator = element('div', 'fotogenic-ai-recipe-footer-actions-separator');
            separator.setAttribute('role', 'separator');
            body.appendChild(separator);
            const resetSectionButton = configurationAction({
				icon: 'arrows-clockwise',
                title: sprintf( __( 'Reset %s', 'fotogenic-ai' ), sectionButtons.get(activeSectionId)?.section?.label || __( 'section', 'fotogenic-ai' ) ),
                description: __( 'Restore only this section to its defaults.', 'fotogenic-ai' ),
                onClick() {
                    const sectionLabel = sectionButtons.get(activeSectionId)?.section?.label || __( 'Section', 'fotogenic-ai' );
                    resetActiveSection();
                    closeTools({ focus: true });
					onSectionReset?.(sectionLabel);
                },
            });
            resetSectionButton.setAttribute('data-fa-reset-section', '');
            body.appendChild(resetSectionButton);
            body.appendChild(configurationAction({
				icon: 'magic-wand',
                title: __( 'Reset full recipe', 'fotogenic-ai' ),
				description: __( 'Restore every recipe section to its defaults.', 'fotogenic-ai' ),
                onClick() {
                    resetRecipeToDefaults();
                    closeTools({ focus: true });
					onRecipeReset?.();
                },
            }));

			(toolsMount || mount).appendChild(toolsRoot);
            toolsDocumentHandler = (event) => {
				if (toolsRoot?.classList.contains('is-open') && !toolsRoot.contains(event.target)) closeTools();
            };
            document.addEventListener('pointerdown', toolsDocumentHandler, true);
            syncTools();
        };

        const createSelect = (name, field, path, currentValue, presentation = {}) => {
            const select = element('select');
            const shell = element('span', 'fotogenic-ai-recipe-select-shell');
            const caret = icons.create('caret-down', { weight: 'bold', size: 15 });
            caret.classList.add('fotogenic-ai-recipe-select-caret');
            const options = resolveOptions(manifest, field, path).filter(
                (option) => !field.optionSource || (
                    !['auto', 'custom_input'].includes(option.value)
                    && option.label.trim().toLowerCase() !== 'automatic'
                )
            );
            const currentOptionValue = field.type === 'object' ? currentValue?.id : currentValue;
            const optionState = selectOptionState(options, currentOptionValue);
            const { normalizedCurrent } = optionState;
            if (!field.required || String(field.omission || '').includes('auto')) {
                const emptyLabel = presentation.emptyLabel || (name === 'aspectRatio'
                    ? __( 'Not set', 'fotogenic-ai' )
                    : (field.optionSource ? __( 'Automatic', 'fotogenic-ai' ) : __( 'Select', 'fotogenic-ai' )));
                const empty = element('option', '', emptyLabel);
                empty.value = '';
                select.appendChild(empty);
            }
            if (optionState.unavailable) {
                const unavailable = element(
                    'option',
                    '',
                    sprintf( __( '%s (unavailable)', 'fotogenic-ai' ), normalizedCurrent )
                );
				unavailable.value = normalizedCurrent;
				unavailable.disabled = true;
				unavailable.selected = true;
				select.appendChild(unavailable);
                storedUnavailableOptions.set(path.join('.'), {
                    label: fieldLabel(name),
                    value: normalizedCurrent,
                });
            }
            options.forEach((option) => {
                const optionNode = element('option', '', option.label);
                optionNode.value = option.value;
                select.appendChild(optionNode);
            });
            const sync = (nextValue) => {
                const value = field.type === 'object' ? nextValue?.id : nextValue;
                const normalized = value === undefined || value === null ? '' : String(value);
                if (select.value !== normalized) select.value = normalized;
            };
            sync(currentValue);
            if (field.optionSource && options.length === 0) {
                select.disabled = true;
                select.setAttribute('aria-describedby', `fotogenic-recipe-options-${path.join('-')}`);
            }
            select.addEventListener('change', () => {
                const value = select.value;
                if (field.type === 'integer') {
                    applyValue(path, value ? Number(value) : undefined);
                } else if (field.type === 'object') {
                    applyValue(path, value ? { id: value } : undefined);
                } else {
                    applyValue(path, value || undefined);
                }
            });
            shell.append(select, caret);
            return {
                control: shell,
                focusControl: select,
                sync,
                optionsUnavailable: field.optionSource && options.length === 0,
                storedUnavailable: optionState.unavailable,
            };
        };

        const createModelReference = (path, currentValue) => {
            const attachmentId = Math.floor(Number(currentValue));
            const selected = attachmentId > 0;
            const stored = referenceItems.get(`model:${attachmentId}`) || {};
            const attachmentModel = window.wp?.media?.attachment?.(attachmentId);
            const attachment = attachmentModel?.toJSON?.() || {};
            const referenceImage = (item = {}) => String(
                item.thumbUrl
                || item.fullUrl
                || item.sizes?.medium?.url
                || item.sizes?.thumbnail?.url
                || item.url
                || ''
            );
            let visibleName = referenceName(stored.name ? stored : attachment, attachmentId);
            let imageUrl = referenceImage(stored) || referenceImage(attachment);
            const choose = element('button', selected
                ? 'fotogenic-ai-model-reference__change'
                : 'fotogenic-ai-model-reference-empty');
            choose.type = 'button';
            choose.disabled = typeof transport?.listLibrary !== 'function';
            choose.addEventListener('click', () => {
                openReferenceLibrary({
                    type: 'model',
                    path,
                    currentValue: getAtPath(editableRecipe(), path),
                    returnFocus: choose,
                });
            });

            if (!selected) {
                const copy = element('span', 'fotogenic-ai-model-reference-empty__copy');
                copy.append(
                    element('strong', '', __( 'Select a model reference', 'fotogenic-ai' )),
                    element('small', '', __( 'Choose a Fotogenic model or add a custom reference.', 'fotogenic-ai' ))
                );
                choose.append(
                    icons.create('image-square', { weight: 'regular', size: 20 }),
                    copy,
                    element('span', 'fotogenic-ai-model-reference-empty__action', __( 'Select', 'fotogenic-ai' ))
                );
                return {
                    control: choose,
                    focusControl: choose,
                    sync() {},
                };
            }

            choose.textContent = __( 'Change', 'fotogenic-ai' );
            const card = element('div', 'fotogenic-ai-model-reference-card');
            const copy = element('span', 'fotogenic-ai-model-reference-card__copy');
            const title = element('strong');
            const source = element('small', '', __( 'My model', 'fotogenic-ai' ));
            copy.append(title, source);
            const actions = element('div', 'fotogenic-ai-model-reference-card__actions');
            const remove = element('button', 'fotogenic-ai-model-reference-card__remove');
            remove.type = 'button';
            remove.appendChild(icons.create('x', { weight: 'bold', size: 17 }));
            remove.addEventListener('click', () => {
                applyValue(path, undefined);
                render(workflow, route);
                window.requestAnimationFrame(() => {
                    controls.get(path.join('.'))?.focusControl?.focus?.({ preventScroll: true });
                });
            });
            actions.append(choose, remove);
            const hydrate = (item) => {
                visibleName = referenceName(item, attachmentId);
                imageUrl = referenceImage(item);
                title.textContent = visibleName;
                remove.setAttribute('aria-label', sprintf(__( 'Remove %s', 'fotogenic-ai' ), visibleName));
                const currentPreview = card.firstElementChild;
                if (imageUrl) {
                    const image = element('img');
                    image.src = imageUrl;
                    image.alt = '';
                    currentPreview?.replaceWith(image);
                }
            };
            const preview = imageUrl ? element('img') : element('span', 'fotogenic-ai-model-reference-card__preview');
            if (imageUrl) {
                preview.src = imageUrl;
                preview.alt = '';
            } else {
                preview.appendChild(icons.create('image-square', { weight: 'regular', size: 20 }));
            }
            card.append(preview, copy, actions);
            hydrate(stored.name || stored.thumbUrl || stored.fullUrl ? stored : attachment);
            if (!stored.name && !attachment.filename && !attachment.title && typeof attachmentModel?.fetch === 'function') {
                const request = attachmentModel.fetch();
                request.done?.(() => {
                    const item = attachmentModel.toJSON?.() || {};
                    referenceItems.set(`model:${attachmentId}`, item);
                    hydrate(item);
                    syncSectionNavigation();
                });
                request.fail?.(() => {
                    card.dataset.referenceMetadata = 'unavailable';
                });
            }
            return {
                control: card,
                focusControl: choose,
                sync() {},
            };
        };

        const createMediaReference = (name, path, currentValue) => {
            const isModel = ['subjectImageId', 'subjectAttachmentId'].includes(name);
            if (isModel) return createModelReference(path, currentValue);
            const isInspiration = name === 'inspirationImageId';
            const variant = isInspiration ? 'inspiration' : 'environment';
            const wrapper = element('div', `fotogenic-ai-recipe-reference fotogenic-ai-recipe-reference--${variant}`);
            wrapper.setAttribute('aria-live', 'polite');
            const preview = element('span', 'fotogenic-ai-recipe-reference__preview');
            preview.setAttribute('aria-hidden', 'true');
            const copyWrap = element('span', 'fotogenic-ai-recipe-reference__copy');
            const value = element('strong');
            const help = element('small');
            copyWrap.append(value, help);
            const actions = element('span', 'fotogenic-ai-recipe-reference__actions');
            const choose = element('button', 'fotogenic-ai-recipe-reference__source');
            choose.type = 'button';
            const upload = element('button', 'fotogenic-ai-recipe-reference__source');
            upload.type = 'button';
            const remove = element('button', 'fotogenic-ai-recipe-reference__remove');
            remove.type = 'button';
            const copies = {
                inspirationImageId: {
                    selected: __( 'Inspiration reference selected', 'fotogenic-ai' ),
                    empty: __( 'No reference selected', 'fotogenic-ai' ),
                    help: __( 'Choose an image to guide the visual direction.', 'fotogenic-ai' ),
                    remove: __( 'Remove inspiration reference', 'fotogenic-ai' ),
                    choose: __( 'Choose inspiration reference', 'fotogenic-ai' ),
                },
                environmentImageId: {
                    selected: __( 'Environment reference selected', 'fotogenic-ai' ),
                    empty: __( 'No environment selected', 'fotogenic-ai' ),
                    help: __( 'Choose an image to guide the scene and setting.', 'fotogenic-ai' ),
                    remove: __( 'Remove environment reference', 'fotogenic-ai' ),
                    choose: __( 'Choose environment reference', 'fotogenic-ai' ),
                },
            };
            copies.environmentAttachmentId = copies.environmentImageId;
            const copy = copies[name] || copies.environmentImageId;
            const mediaById = new Map();
			const libraryItem = (attachmentId) => referenceItems.get(`${variant}:${attachmentId}`) || {};
			const attachmentFileName = (attachment = {}) => {
				const fileUrl = String(
					attachment.url
					|| attachment.fullUrl
					|| attachment.sizes?.full?.url
					|| attachment.sizes?.large?.url
					|| attachment.sizes?.medium?.url
					|| attachment.sizes?.thumbnail?.url
					|| ''
				).split(/[?#]/, 1)[0];
				const encodedName = fileUrl.slice(fileUrl.lastIndexOf('/') + 1).replace(/-\d+x\d+(?=\.[^.]+$)/, '');
				if (encodedName) {
					try {
						return decodeURIComponent(encodedName);
					} catch (error) {
						wrapper.dataset.referenceFilename = 'encoded';
						return encodedName;
					}
				}
				const storedName = String(attachment.name || '').trim();
				if (storedName) return storedName;
				return String(attachment.filename || attachment.title || copy.selected);
			};
			const actionIcon = (name, weight = 'regular') => icons.create(name, { weight, size: 17 });
            const renderPreview = (attachmentId) => {
                const attachment = mediaById.get(attachmentId)
					|| libraryItem(attachmentId)
                    || window.wp?.media?.attachment?.(attachmentId)?.toJSON?.()
                    || {};
				const imageUrl = String(
					attachment?.thumbUrl
					|| attachment?.fullUrl
					|| attachment?.sizes?.thumbnail?.url
					|| attachment?.url
					|| ''
				);
                preview.replaceChildren();
                if (imageUrl) {
                    const image = element('img');
                    image.src = imageUrl;
                    image.alt = '';
                    preview.appendChild(image);
                    return;
                }
				const icon = icons.create('image-square', { weight: 'regular', size: 19 });
                preview.appendChild(icon);
            };
            const sync = (nextValue) => {
                const attachmentId = Math.floor(Number(nextValue));
                const selected = attachmentId > 0;
				const stored = libraryItem(attachmentId);
				const attachment = mediaById.get(attachmentId) || stored;
				const selectedLabel = attachmentFileName(attachment);
                if (value.textContent !== (selected ? selectedLabel : copy.empty)) value.textContent = selected ? selectedLabel : copy.empty;
                help.textContent = selected
					? (variant === 'environment'
						? __( 'Previously used', 'fotogenic-ai' )
						: sprintf( __( 'Media Library attachment %d', 'fotogenic-ai' ), attachmentId ))
                    : copy.help;
                help.hidden = !selected;
                choose.replaceChildren(
					actionIcon(isInspiration ? 'folder-open' : 'image-square'),
					element('span', '', isInspiration ? __( 'Media library', 'fotogenic-ai' ) : __( 'Select saved', 'fotogenic-ai' ))
                );
                upload.replaceChildren(
					actionIcon(isInspiration ? 'upload-simple' : 'folder-open'),
                    element('span', '', isInspiration
                        ? (selected ? __( 'Replace image', 'fotogenic-ai' ) : __( 'Upload image', 'fotogenic-ai' ))
                        : __( 'Media library', 'fotogenic-ai' ))
                );
				remove.replaceChildren(actionIcon('x', 'bold'));
                remove.setAttribute('aria-label', copy.remove);
                remove.hidden = !selected;
                wrapper.classList.toggle('has-value', selected);
                renderPreview(attachmentId);
            };
			const hydrateCurrentAttachment = (attachmentId) => {
				if (attachmentId <= 0 || libraryItem(attachmentId).name || mediaById.has(attachmentId)) return;
				const attachmentModel = window.wp?.media?.attachment?.(attachmentId);
				const useAttachment = () => {
					const attachment = attachmentModel?.toJSON?.() || {};
					if (!attachment.filename && !attachment.title && !attachment.url && !attachment.sizes) return false;
					mediaById.set(attachmentId, attachment);
					if (Math.floor(Number(getAtPath(editableRecipe(), path))) === attachmentId) sync(attachmentId);
					return true;
				};
				if (useAttachment() || typeof attachmentModel?.fetch !== 'function') return;
				const request = attachmentModel.fetch();
				request.done?.(useAttachment);
				request.fail?.(() => {
					wrapper.dataset.referenceMetadata = 'unavailable';
				});
			};
            const openMedia = ({ trigger, uploadMode = false } = {}) => {
                const frame = window.wp.media({
                    title: copy.choose,
                    button: { text: __( 'Use selected media', 'fotogenic-ai' ) },
                    library: { type: 'image' },
                    multiple: false,
                });
                frame.on('open', () => frame.content?.mode?.(uploadMode ? 'upload' : 'browse'));
                frame.on('select', () => {
                    const selected = frame.state()?.get?.('selection')?.first?.()?.toJSON?.() || {};
                    const id = Math.floor(Number(selected.id));
                    if (id > 0) {
                        mediaById.set(id, selected);
                        applyValue(path, id);
                        sync(id);
                    }
                });
                frame.on('close', () => window.setTimeout(() => {
                    frame.off?.();
                    frame.remove?.();
                    trigger.focus();
                }, 0));
                frame.open();
            };
			const initialAttachmentId = Math.floor(Number(currentValue));
			sync(initialAttachmentId);
			hydrateCurrentAttachment(initialAttachmentId);
            const unavailable = typeof window.wp?.media !== 'function';
            choose.disabled = isInspiration ? unavailable : typeof transport?.listLibrary !== 'function';
            upload.disabled = unavailable || (!isInspiration && typeof transport?.listLibrary !== 'function');
            choose.addEventListener('click', () => {
                if (isInspiration) {
                    openMedia({ trigger: choose });
                    return;
                }
                openReferenceLibrary({
                    type: 'environment',
                    path,
                    currentValue: getAtPath(editableRecipe(), path),
                    returnFocus: choose,
                });
            });
            upload.addEventListener('click', () => {
                if (isInspiration) {
                    openMedia({ trigger: upload, uploadMode: true });
                    return;
                }
                openReferenceLibrary({
                    type: 'environment',
                    path,
                    currentValue: getAtPath(editableRecipe(), path),
                    returnFocus: upload,
                    initialMedia: true,
                });
            });
            remove.addEventListener('click', () => {
                applyValue(path, undefined);
                sync(undefined);
                choose.focus({ preventScroll: true });
            });
            actions.appendChild(choose);
            actions.appendChild(upload);
            actions.appendChild(remove);
            wrapper.append(preview, copyWrap, actions);
            return { control: wrapper, focusControl: choose, sync };
        };

        const createFieldLabel = (name, field, labelText = fieldLabel(name)) => {
            const label = element('span', 'fotogenic-ai-studio-field__label');
            label.appendChild(element('span', '', labelText));
            if (field.required !== true) {
                label.appendChild(element('em', '', __( 'Optional', 'fotogenic-ai' )));
            }
            return label;
        };

		const createField = (name, field, path, recipe, presentation = {}) => {
			if (INTERNAL_FIELDS.has(name) || !fieldApplies(field, route, recipe)) {
                return null;
            }
            const fullPath = [...path, name];
            const id = `fotogenic-recipe-${fullPath.join('-')}`;
            const value = getAtPath(recipe, fullPath);

            if (field.type === 'object' && !field.optionSource) {
                const fieldset = element('fieldset', 'fotogenic-ai-recipe-group');
                const legend = element('legend', '', fieldLabel(name));
                fieldset.appendChild(legend);
                Object.entries(field.fields || {}).forEach(([childName, child]) => {
                    const childNode = createField(childName, child, fullPath, recipe);
                    if (childNode) {
                        fieldset.appendChild(childNode);
                    }
                });
                return fieldset;
            }

            if (isMediaReference(name, field)) {
                const group = element('div', 'fotogenic-ai-studio-field fotogenic-ai-studio-field--reference');
                if (activeSectionOwner === 'guidance') group.classList.add('fotogenic-ai-guidance-section');
                const labelId = `${id}-label`;
				const label = presentation.hideLabel
					? null
					: createFieldLabel(name, field, presentation.label || fieldLabel(name));
				if (label) label.id = labelId;
                const result = createMediaReference(name, fullPath, value);
				if (label && result.control !== result.focusControl) {
                    result.control.setAttribute('role', 'group');
                    result.control.setAttribute('aria-labelledby', labelId);
                }
                result.focusControl.id = id;
				if (label) group.appendChild(label);
                if (presentation.description) {
                    group.appendChild(element('p', 'fotogenic-ai-recipe-control-description', presentation.description));
                }
                group.appendChild(result.control);
                const baseDisabled = result.focusControl.disabled;
                const sync = (nextRecipe) => {
                    const visible = requirementsMet(field, nextRecipe);
                    group.hidden = !visible;
                    result.focusControl.disabled = baseDisabled || !visible;
                    result.sync(getAtPath(nextRecipe, fullPath));
                };
                controls.set(fullPath.join('.'), {
                    focusControl: result.focusControl,
                    sync,
                    fieldNode: group,
                    section: activeSectionOwner,
                });
                sync(recipe);
                return group;
            }

            const globalGuidance = activeSectionOwner === 'guidance' && name === 'applyGlobalInstructions';
            const runInstructions = activeSectionOwner === 'guidance' && name === 'customInstructions';
            const label = element('label', 'fotogenic-ai-studio-field');
            if (globalGuidance) {
                label.classList.add('fotogenic-ai-global-guidance-control', 'fotogenic-ai-guidance-section');
                const copy = element('span', 'fotogenic-ai-global-guidance-copy');
                copy.append(
                    element('strong', '', fieldLabel(name)),
                    element('small', '', __( 'Reusable instructions from Settings.', 'fotogenic-ai' ))
                );
                label.appendChild(copy);
            } else if (runInstructions) {
                label.classList.add('fotogenic-ai-guidance-custom-instructions', 'fotogenic-ai-guidance-section');
                label.append(
                    element('span', 'fotogenic-ai-studio-field__label', fieldLabel(name)),
                    element('p', 'fotogenic-ai-guidance-scope-copy', __( 'Only affects this run. Your saved account guidance is not changed.', 'fotogenic-ai' ))
                );
            } else {
                label.appendChild(createFieldLabel(name, field, presentation.label || fieldLabel(name)));
            }
            if (!globalGuidance && presentation.description) {
                label.appendChild(element('small', 'fotogenic-ai-recipe-control-description', presentation.description));
            }
            let control;
            let focusControl;
            let syncControl;
            let optionsUnavailable = false;
            let storedUnavailable = false;
            let characterCount = null;

            if (field.type === 'boolean') {
                const checkboxLabel = element(
                    'span',
                    globalGuidance ? 'fotogenic-ai-global-guidance-choice' : 'fotogenic-ai-recipe-checkbox'
                );
                const stateLabel = element('span');
                control = element('input');
                control.type = 'checkbox';
                focusControl = control;
                syncControl = (nextRecipe) => {
                    const checked = getAtPath(nextRecipe, fullPath) === true;
                    const stateText = globalGuidance
                        ? __( 'Apply to this run', 'fotogenic-ai' )
                        : (checked ? __( 'Enabled', 'fotogenic-ai' ) : __( 'Enable', 'fotogenic-ai' ));
                    if (control.checked !== checked) control.checked = checked;
                    if (stateLabel.textContent !== stateText) stateLabel.textContent = stateText;
                };
                control.addEventListener('change', () => applyValue(fullPath, control.checked));
                checkboxLabel.append(control, stateLabel);
                label.appendChild(checkboxLabel);
            } else if (field.type === 'object' && field.optionSource) {
                const result = createSelect(name, field, fullPath, value, presentation);
                control = result.control;
                focusControl = result.focusControl;
                syncControl = (nextRecipe) => result.sync(getAtPath(nextRecipe, fullPath));
                optionsUnavailable = result.optionsUnavailable;
                storedUnavailable = result.storedUnavailable;
                label.appendChild(control);
			} else if (
				['string', 'integer'].includes(field.type)
				&& (Array.isArray(field.enum) || field.optionSource || Array.isArray(field.options))
			) {
                const result = createSelect(name, field, fullPath, value, presentation);
                control = result.control;
                focusControl = result.focusControl;
                syncControl = (nextRecipe) => result.sync(getAtPath(nextRecipe, fullPath));
                optionsUnavailable = result.optionsUnavailable;
                storedUnavailable = result.storedUnavailable;
                label.appendChild(control);
            } else if (field.type === 'integer') {
                control = element('input');
                control.type = 'number';
                focusControl = control;
                control.step = '1';
                if (field.minimum !== undefined) control.min = String(field.minimum);
                if (field.maximum !== undefined) control.max = String(field.maximum);
                syncControl = (nextRecipe) => {
                    const nextValue = getAtPath(nextRecipe, fullPath);
                    const normalized = nextValue === undefined ? '' : String(nextValue);
                    if (control.value !== normalized) control.value = normalized;
                };
                control.addEventListener('change', () => applyValue(fullPath, control.value === '' ? undefined : Number(control.value)));
                label.appendChild(control);
            } else {
                control = field.maxLength > 160 || /instructions|description/i.test(name)
                    ? element('textarea')
                    : element('input');
                focusControl = control;
                if (control.tagName === 'INPUT') control.type = 'text';
                if (field.maxLength) control.maxLength = field.maxLength;
                if (runInstructions) {
                    control.placeholder = __( 'Describe framing, campaign tone, product emphasis, or other direction.', 'fotogenic-ai' );
                }
                if (control.tagName === 'TEXTAREA' && field.maxLength) {
                    characterCount = element('span', 'fotogenic-ai-recipe-character-count');
                }
                syncControl = (nextRecipe) => {
                    const nextValue = getAtPath(nextRecipe, fullPath);
                    const normalized = nextValue === undefined ? '' : String(nextValue);
                    if (control.value !== normalized) control.value = normalized;
                    if (characterCount) {
                        characterCount.textContent = sprintf(
                            __( '%1$d / %2$s', 'fotogenic-ai' ),
                            normalized.length,
                            new Intl.NumberFormat().format(field.maxLength)
                        );
                    }
                };
                control.addEventListener('input', () => applyValue(fullPath, control.value || undefined));
                label.appendChild(control);
                if (characterCount) label.appendChild(characterCount);
            }

            if (focusControl instanceof HTMLElement) {
                focusControl.id = id;
            }
            if (optionsUnavailable) {
                const helper = element('span', 'fotogenic-ai-recipe-control-note', __( 'No options are currently available.', 'fotogenic-ai' ));
                helper.id = `fotogenic-recipe-options-${fullPath.join('-')}`;
                label.appendChild(helper);
            } else if (storedUnavailable) {
                const helper = element(
                    'span',
                    'fotogenic-ai-recipe-control-note',
                    __( 'This saved value is no longer offered. Choose a current option to continue.', 'fotogenic-ai' )
                );
                helper.id = `fotogenic-recipe-options-${fullPath.join('-')}`;
                focusControl.setAttribute('aria-describedby', helper.id);
                label.appendChild(helper);
            }
            const baseDisabled = focusControl.disabled;
            const sync = (nextRecipe) => {
                const visible = requirementsMet(field, nextRecipe);
                label.hidden = !visible;
                focusControl.disabled = baseDisabled || !visible;
                syncControl(nextRecipe);
            };
            controls.set(fullPath.join('.'), {
                focusControl,
                sync,
                fieldNode: label,
                section: activeSectionOwner,
            });
            sync(recipe);
            return label;
        };

        const createDeliverySelect = ({ key, id, labelText, description, options, value, onSelect }) => {
            const label = element('label', 'fotogenic-ai-studio-field');
            label.appendChild(element('span', 'fotogenic-ai-studio-field__label', labelText));
            if (description) {
                label.appendChild(element('small', 'fotogenic-ai-recipe-control-description', description));
            }
            const select = element('select');
            const shell = element('span', 'fotogenic-ai-recipe-select-shell');
            const caret = icons.create('caret-down', { weight: 'bold', size: 15 });
            caret.classList.add('fotogenic-ai-recipe-select-caret');
            select.id = id;
            options.forEach((option) => {
                const node = element('option', '', option.label);
                node.value = option.value;
                select.appendChild(node);
            });
            select.value = options.some((option) => option.value === value) ? value : options[0]?.value || '';
            select.addEventListener('change', () => onSelect(select.value));
            shell.append(select, caret);
            label.appendChild(shell);
            controls.set(key, {
                focusControl: select,
                fieldNode: label,
                section: 'delivery',
                sync() {
					const nextValue = key === 'sourcePolicy.sourceMode'
						? String(canonicalDraft().sourcePolicy?.sourceMode || '')
						: String(
							workflow?.id === 'campaign_set'
								? (campaignGroup(canonicalDraft())?.resultPolicy?.assignmentMode || 'review')
								: (canonicalDraft().resultPolicy?.assignmentMode || 'review')
						);
                    if (select.value !== nextValue && options.some((option) => option.value === nextValue)) {
                        select.value = nextValue;
                    }
                },
            });
            return label;
        };

        const renderProductDelivery = (body) => {
            body.classList.add('fotogenic-ai-product-delivery-editor');
            const delivery = createRecipeFieldGroup({
                id: 'fotogenic-ai-platform-delivery-title',
                label: __( 'Product delivery', 'fotogenic-ai' ),
                hiddenHeading: true,
                className: 'fotogenic-ai-platform-delivery-settings',
            });
            const grid = element(
                'div',
                'fotogenic-ai-recipe-grid fotogenic-ai-recipe-guided-grid fotogenic-ai-product-delivery-grid'
            );
            const sourceDefinition = workflow.sources?.find((source) => source.id === 'product');
            const modes = Array.isArray(sourceDefinition?.sourcePolicy?.bulkModes)
                ? sourceDefinition.sourcePolicy.bulkModes
                : [];
            const sourceMode = String(canonicalDraft().sourcePolicy?.sourceMode || modes[0] || 'featured');
			let deliveryControlRoot = grid;
			if (workflow?.id === 'campaign_set') {
				const groupCount = campaignGroups().length;
				const plan = element('div', 'fotogenic-ai-campaign-delivery-plan');
				const summary = element('div', 'fotogenic-ai-campaign-product-delivery-summary');
				const step = element('span', 'fotogenic-ai-campaign-delivery-step', '1');
				step.setAttribute('aria-hidden', 'true');
				const copy = element('span', 'fotogenic-ai-campaign-product-delivery-summary__copy');
				copy.append(
					element('strong', '', __( 'Campaign Sets', 'fotogenic-ai' )),
					element('small', '', __( 'Source groups are configured per exact Product or variation in Select.', 'fotogenic-ai' ))
				);
				const count = element(
					'strong',
					'',
					sprintf(
						_n( '%d set', '%d sets', groupCount, 'fotogenic-ai' ),
						groupCount
					)
				);
				const edit = element('button', '', __( 'Edit source groups', 'fotogenic-ai' ));
				edit.type = 'button';
				edit.addEventListener('click', () => onBackToSelection?.());
				const actions = element('span', 'fotogenic-ai-campaign-product-delivery-summary__actions');
				actions.append(count, edit);
				summary.append(step, copy, actions);
				plan.appendChild(summary);
				grid.appendChild(plan);
				deliveryControlRoot = plan;
            } else if (modes.length) {
                const recipe = canonicalRecipe();
                const referenceCount = ['subjectImageId', 'inspirationImageId', 'environmentImageId']
                    .filter((key) => Number(recipe?.[key]) > 0).length;
				const configuredPrimaryMaximum = Math.floor(Number(sourceDefinition?.inputCardinality?.single?.primary?.maximum)) || 1;
				const totalMaximum = Math.max(
					1,
					Math.floor(Number(sourceDefinition?.inputCardinality?.single?.total?.maximum)) || configuredPrimaryMaximum
				);
                const primaryMaximum = Math.max(1, Math.min(
					configuredPrimaryMaximum,
                    totalMaximum - referenceCount
                ));
                const sourceLabels = {
                    featured: __( 'Featured image', 'fotogenic-ai' ),
                    featured_gallery: sprintf(
                        __( 'Featured + gallery · up to %d', 'fotogenic-ai' ),
                        primaryMaximum
                    ),
                    gallery_only: sprintf(
                        __( 'Gallery only · up to %d', 'fotogenic-ai' ),
                        primaryMaximum
                    ),
                };
                grid.appendChild(createDeliverySelect({
                    key: 'sourcePolicy.sourceMode',
                    id: 'fotogenic-result-source-mode',
                    labelText: __( 'Source images', 'fotogenic-ai' ),
                    description: sprintf(
                        _n(
                            '%1$d optional reference uses the four-image request budget. Up to %2$d product image is available per item.',
                            '%1$d optional references use the four-image request budget. Up to %2$d product images are available per item.',
                            referenceCount,
                            'fotogenic-ai'
                        ),
                        referenceCount,
                        primaryMaximum
                    ),
                    options: modes.map((mode) => ({ value: mode, label: sourceLabels[mode] || humanize(mode) })),
                    value: sourceMode,
                    onSelect(nextMode) {
                        onSourcePolicyChange?.({ ...(canonicalDraft().sourcePolicy || {}), sourceMode: nextMode });
                    },
                }));
            }

            const assignmentValues = workflow?.id === 'campaign_set'
                ? [ 'review', 'gallery_append' ]
                : [ 'review', 'gallery_append', 'featured_replace' ];
            const assignments = assignmentValues.map((value) => ({ value }))
                .map((option) => ({ ...option, label: assignmentLabel(option.value) }));
			const assignmentMode = String(
				workflow?.id === 'campaign_set'
					? (campaignGroup(canonicalDraft())?.resultPolicy?.assignmentMode || 'review')
					: (canonicalDraft().resultPolicy?.assignmentMode || 'review')
			);
			const assignmentField = createDeliverySelect({
				key: 'resultPolicy.assignmentMode',
                id: 'fotogenic-result-assignment-mode',
                labelText: __( 'After saving', 'fotogenic-ai' ),
                description: workflow?.id === 'campaign_set'
					? __( 'Campaign images are always saved first as new Media Library files.', 'fotogenic-ai' )
					: __( 'Generated files are always saved first in Media Library.', 'fotogenic-ai' ),
                options: assignments,
                value: assignmentMode,
				onSelect(nextMode) {
					if (workflow?.id === 'campaign_set') commitCampaignResultPolicy({ assignmentMode: nextMode });
					else onResultPolicyChange?.({ assignmentMode: nextMode });
                },
			});
			if (workflow?.id === 'campaign_set') {
				const step = element('span', 'fotogenic-ai-campaign-delivery-step', '2');
				step.setAttribute('aria-hidden', 'true');
				assignmentField.prepend(step);
			}
			deliveryControlRoot.appendChild(assignmentField);
            delivery.appendChild(grid);
            body.appendChild(delivery);
        };

		const sectionChangedEntries = (section) => {
            if (section.id === 'delivery') {
                const draft = canonicalDraft();
                const values = [];
				if (workflow?.id !== 'campaign_set' && String(draft.sourcePolicy?.sourceMode || 'featured') !== 'featured') {
                    values.push(humanize(draft.sourcePolicy.sourceMode));
                }
				const resultPolicy = workflow?.id === 'campaign_set'
					? (campaignGroup(draft)?.resultPolicy || {})
					: (draft.resultPolicy || {});
				if (String(resultPolicy.assignmentMode || 'review') !== 'review') {
					values.push(assignmentLabel(resultPolicy.assignmentMode));
                }
                return values;
            }
			const recipe = canonicalRecipe();
			if (section.id === 'subject' && workflow?.id === 'product_images') {
				const mode = personPresenceMode(recipe);
				if (mode === PERSON_PRESENCE.none) return [__( 'No person', 'fotogenic-ai' )];
				if (mode === PERSON_PRESENCE.model && !(Number(recipe.subjectImageId) > 0)) {
					return [__( 'Model required', 'fotogenic-ai' )];
				}
				if (mode === PERSON_PRESENCE.model) {
					const attachmentId = Math.floor(Number(recipe.subjectImageId));
					const stored = referenceItems.get(`model:${attachmentId}`) || {};
					const attachment = window.wp?.media?.attachment?.(attachmentId)?.toJSON?.() || {};
					return [referenceName(stored.name || stored.filename ? stored : attachment, attachmentId)];
				}
				if (mode === PERSON_PRESENCE.automatic) return [];
			}
			if (section.id === 'guidance') {
				return section.entries.flatMap((entry) => {
					const value = getAtPath(recipe, [...entry.path, entry.name]);
					if (isMediaReference(entry.name, entry.field)) {
						return Number(value) > 0 ? [__( 'Reference selected', 'fotogenic-ai' )] : [];
					}
					if (entry.name === 'applyGlobalInstructions') {
						return value === true ? [__( 'Saved account guidance', 'fotogenic-ai' )] : [];
					}
					if (entry.name === 'customInstructions') {
						return String(value || '').trim() ? [__( 'Run instructions', 'fotogenic-ai' )] : [];
					}
					return [];
				});
			}
            const defaults = Studio.store.createDefaultRecipe(workflow.recipe, route, manifest.optionSources);
            return section.entries.flatMap((entry) => {
                const path = [...entry.path, entry.name];
                const value = getAtPath(recipe, path);
                const baseline = getAtPath(defaults, path);
                if (Studio.store.stableStringify(value) === Studio.store.stableStringify(baseline)) return [];
                if (isMediaReference(entry.name, entry.field)) return [__( 'Reference selected', 'fotogenic-ai' )];
                if (entry.field.type === 'boolean') return [value ? __( 'Enabled', 'fotogenic-ai' ) : __( 'Disabled', 'fotogenic-ai' )];
                if (/instructions|description/i.test(entry.name)) return [__( 'Custom guidance', 'fotogenic-ai' )];
                const optionValue = entry.field.type === 'object' ? value?.id : value;
                const option = resolveOptions(manifest, entry.field, path)
                    .find((candidate) => candidate.value === String(optionValue ?? ''));
                return [option?.label || humanize(optionValue) || fieldLabel(entry.name)];
            });
        };

        const sectionHasChanges = (section) => {
            if (section.id !== 'guidance') return sectionChangedEntries(section).length > 0;
            const recipe = canonicalRecipe();
            const defaults = Studio.store.createDefaultRecipe(workflow.recipe, route, manifest.optionSources);
            return section.entries.some((entry) => {
                const path = [...entry.path, entry.name];
                const value = getAtPath(recipe, path);
                const baseline = getAtPath(defaults, path);
                if (isMediaReference(entry.name, entry.field)) {
                    return Math.max(0, Math.floor(Number(value)) || 0)
                        !== Math.max(0, Math.floor(Number(baseline)) || 0);
                }
                if (entry.name === 'customInstructions') {
                    return String(value || '').trim() !== String(baseline || '').trim();
                }
                return Studio.store.stableStringify(value) !== Studio.store.stableStringify(baseline);
            });
        };

        const syncSectionNavigation = () => {
            sectionButtons.forEach((entry, sectionId) => {
                const values = sectionChangedEntries(entry.section);
                const summary = values.length ? values.slice(0, 2).join(' · ') : __( 'Automatic', 'fotogenic-ai' );
                const incomplete = sectionId === 'subject' && summary === __( 'Model required', 'fotogenic-ai' );
                const complete = sectionHasChanges(entry.section) && !incomplete && sectionId !== activeSectionId;
                entry.summary.textContent = summary;
                entry.button.classList.toggle('is-incomplete', incomplete);
                entry.button.classList.toggle('is-complete', complete);
                entry.state.replaceChildren();
                if (complete) {
					const check = icons.create('check', { weight: 'bold', size: 15 });
                    entry.state.appendChild(check);
                } else {
                    entry.state.textContent = String(entry.index + 1);
                }
                entry.button.setAttribute(
                    'aria-label',
                    sprintf(
                        sectionId === activeSectionId
                            ? __( '%1$s, %2$s, current section', 'fotogenic-ai' )
                            : __( '%1$s, %2$s', 'fotogenic-ai' ),
                        entry.section.label,
                        summary
                    )
                );
            });
            const resetTitle = toolsRoot?.querySelector('[data-fa-reset-section] strong');
            if (resetTitle) {
                resetTitle.textContent = sprintf(
                    __( 'Reset %s', 'fotogenic-ai' ),
                    sectionButtons.get(activeSectionId)?.section?.label || __( 'section', 'fotogenic-ai' )
                );
            }
        };

        const sectionNavigation = () => {
			const ids = [...sectionPanels.keys()];
			const index = ids.indexOf(activeSectionId);
			return {
				hasSections: ids.length > 0,
				activeSectionId: index >= 0 ? activeSectionId : '',
					hasPrevious: index > 0,
					hasNext: index >= 0 && index < ids.length - 1,
					label: index >= 0 ? sectionButtons.get(activeSectionId)?.section?.label || '' : '',
				};
		};

        const cancelSectionNavigatorFrame = () => {
            if (!sectionNavigatorFrame) return;
            if (typeof window.cancelAnimationFrame === 'function') {
                window.cancelAnimationFrame(sectionNavigatorFrame);
            } else {
                window.clearTimeout(sectionNavigatorFrame);
            }
            sectionNavigatorFrame = 0;
        };

        const keepActiveSectionVisible = () => {
            sectionNavigatorFrame = 0;
            if (!sectionNavigator || sectionNavigator.scrollWidth <= sectionNavigator.clientWidth + 1) return;
            const activeButton = sectionButtons.get(activeSectionId)?.button;
            if (!activeButton) return;
            const navigatorRect = sectionNavigator.getBoundingClientRect?.();
            const activeRect = activeButton.getBoundingClientRect?.();
            if (!navigatorRect || !activeRect) {
                activeButton.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
                return;
            }
            const delta = activeRect.left < navigatorRect.left
                ? activeRect.left - navigatorRect.left
                : (activeRect.right > navigatorRect.right ? activeRect.right - navigatorRect.right : 0);
            if (Math.abs(delta) <= 1) return;
            sectionNavigator.scrollLeft += delta;
        };

        const scheduleActiveSectionVisible = () => {
            cancelSectionNavigatorFrame();
            const requestFrame = typeof window.requestAnimationFrame === 'function'
                ? window.requestAnimationFrame.bind(window)
                : (callback) => window.setTimeout(callback, 0);
            sectionNavigatorFrame = requestFrame(keepActiveSectionVisible);
        };

        const stopObservingSectionNavigator = () => {
            cancelSectionNavigatorFrame();
            sectionNavigatorObserver?.disconnect?.();
            sectionNavigatorObserver = null;
            window.removeEventListener('resize', scheduleActiveSectionVisible);
            sectionNavigator = null;
        };

        const syncErrorRegion = () => {
            const panel = sectionPanels.get(activeSectionId);
            const visible = Boolean(
                recipeIssues.length
                && ['subject', 'guidance', 'delivery'].includes(activeSectionId)
                && panel
            );
            errorRegion.hidden = !visible;
            if (visible) {
                panel.querySelector('.fotogenic-ai-recipe-editor-fields')?.appendChild(errorRegion);
            }
        };

        const observeSectionNavigator = (navigator) => {
            stopObservingSectionNavigator();
            sectionNavigator = navigator;
            if (typeof window.ResizeObserver === 'function') {
                sectionNavigatorObserver = new window.ResizeObserver(scheduleActiveSectionVisible);
                sectionNavigatorObserver.observe(navigator);
            }
            window.addEventListener('resize', scheduleActiveSectionVisible);
            scheduleActiveSectionVisible();
        };

        const selectRecipeSection = (sectionId, { focus = false } = {}) => {
            if (!sectionPanels.has(sectionId)) return false;
            activeSectionId = sectionId;
            sectionPanels.forEach((panel, id) => {
                panel.hidden = id !== sectionId;
            });
            sectionButtons.forEach((entry, id) => {
                const active = id === sectionId;
                entry.button.classList.toggle('is-active', active);
                if (active) {
                    entry.button.setAttribute('aria-current', 'step');
                } else {
                    entry.button.removeAttribute('aria-current');
                }
            });
            syncSectionNavigation();
			syncErrorRegion();
			if (typeof onSectionChange === 'function') onSectionChange(sectionNavigation());
            if (focus) {
                sectionPanels.get(sectionId)?.querySelector('h2')?.focus?.({ preventScroll: true });
            }
            scheduleActiveSectionVisible();
            return true;
        };

		const renderRunSettings = (recipe) => {
            const runSettings = element('div', 'fotogenic-ai-recipe-run-settings fotogenic-ai-compact-run-controls');
            runSettings.setAttribute('role', 'group');
            runSettings.setAttribute('aria-label', __( 'Run settings', 'fotogenic-ai' ));
			const countLabel = workflow.id === 'campaign_set'
				? __( 'Campaign images', 'fotogenic-ai' )
				: __( 'Images', 'fotogenic-ai' );
			const countDescription = workflow.id === 'campaign_set'
				? __( 'Campaign images per set', 'fotogenic-ai' )
				: __( 'Images per item', 'fotogenic-ai' );
            ['count', 'quality'].forEach((name) => {
                const field = workflow.recipe?.fields?.[name];
                if (!field || !routeApplies(field, route)) return;
				const minimum = Math.max(1, Number(field.minimum) || 1);
				const maximum = Math.max(minimum, Number(field.maximum) || minimum);
				const runField = name === 'count'
					? {
						...field,
						enum: Array.from(
							{ length: maximum - minimum + 1 },
							(_, index) => minimum + index
						),
					}
					: field;
                const node = createField(name, runField, [], recipe);
                if (!node) return;
                node.classList.add('fotogenic-ai-compact-run-control');
                node.querySelector('.fotogenic-ai-recipe-control-note')?.classList.add('fotogenic-ai-studio-sr-only');
                const fieldName = node.querySelector('.fotogenic-ai-studio-field__label > span');
				if (fieldName && name === 'count') fieldName.textContent = countLabel;
				const visibleLabel = node.querySelector('.fotogenic-ai-studio-field__label');
				visibleLabel?.classList.add('fotogenic-ai-studio-sr-only');
				const select = node.querySelector('select');
				if (select) {
					select.setAttribute(
						'aria-label',
						name === 'count' ? countDescription : __( 'Quality', 'fotogenic-ai' )
					);
					if (name === 'count') select.title = countDescription;
				}
				const selectShell = node.querySelector('.fotogenic-ai-recipe-select-shell');
				if (selectShell) {
					const icon = icons.create(name === 'count' ? 'image-square' : 'sparkle', {
						weight: name === 'count' ? 'regular' : 'fill',
						size: 15,
					});
					icon.classList.add('fotogenic-ai-compact-run-control__icon');
					selectShell.prepend(icon);
				}
                runSettings.appendChild(node);
            });
            runSettings.classList.toggle('has-three', runSettings.childElementCount > 2);
            workspaceActions?.classList.toggle('has-single-run-control', runSettings.childElementCount === 1);
            if (runSettings.childElementCount) (runSettingsMount || mount).appendChild(runSettings);
		};

		const syncUnavailableRegion = () => {
			const first = [...storedUnavailableOptions.values()][0];
			unavailableRegion.hidden = !first;
			unavailableRegion.dataset.state = first ? 'warning' : '';
			unavailableRegion.textContent = first
				? sprintf(
					__( '%1$s %2$s is unavailable in the current server configuration. Choose a current option before continuing.', 'fotogenic-ai' ),
					first.label,
					first.value
				)
				: '';
		};

        const createRecipeFieldGroup = ({ id, label, hiddenHeading = false, className = '' } = {}) => {
            const group = element('section', `fotogenic-ai-recipe-field-group ${className}`.trim());
            group.setAttribute('aria-labelledby', id);
            const heading = element('h3', `fotogenic-ai-recipe-group-heading${hiddenHeading ? ' screen-reader-text' : ''}`, label);
            heading.id = id;
            group.appendChild(heading);
            return group;
        };

        const createSegmentedControl = ({ label, description = '', options, value, onChange, id }) => {
            const fieldset = element('fieldset', 'fotogenic-ai-segmented-field');
            const legend = element('legend', '', label);
            fieldset.appendChild(legend);
            if (description) fieldset.appendChild(element('p', '', description));
            const control = element('div', 'fotogenic-ai-segmented-control');
            control.setAttribute('role', 'radiogroup');
            control.setAttribute('aria-label', label);
            const buttons = options.map((option, index) => {
                const button = element('button', value === option.value ? 'is-selected' : '', option.label);
                button.type = 'button';
                button.id = index === 0 && id ? id : '';
                button.setAttribute('role', 'radio');
                button.setAttribute('aria-checked', value === option.value ? 'true' : 'false');
                button.tabIndex = value === option.value ? 0 : -1;
                button.addEventListener('click', () => onChange(option.value));
                button.addEventListener('keydown', (event) => {
                    if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return;
                    event.preventDefault();
                    const nextIndex = event.key === 'Home'
                        ? 0
                        : (event.key === 'End'
                            ? options.length - 1
                            : (index + (['ArrowRight', 'ArrowDown'].includes(event.key) ? 1 : -1) + options.length) % options.length);
                    onChange(options[nextIndex].value);
                    window.requestAnimationFrame(() => buttons[nextIndex]?.focus({ preventScroll: true }));
                });
                control.appendChild(button);
                return button;
            });
            fieldset.appendChild(control);
            return { fieldset, focusControl: buttons.find((button) => button.tabIndex === 0) || buttons[0] };
        };

        const entryByKey = (section, key) => section.entries.find((entry) => entry.key === key);

        const appendEntry = (parent, section, key, recipe, presentation = {}) => {
            const entry = entryByKey(section, key);
            if (!entry) return null;
            const node = createField(entry.name, entry.field, entry.path, recipe, presentation);
            if (node) parent.appendChild(node);
            return node;
        };

        const renderSubjectSection = (body, section, recipe) => {
            body.classList.add('fotogenic-ai-subject-editor', 'fotogenic-ai-recipe-section-stack');
            const campaign = workflow.id === 'campaign_set';
            const referenceKey = campaign ? 'subjectAttachmentId' : 'subjectImageId';
            if (campaign) {
                const reference = createRecipeFieldGroup({
                    id: 'fotogenic-ai-campaign-model-reference-heading',
                    label: __( 'Model reference', 'fotogenic-ai' ),
                    hiddenHeading: true,
                });
                appendEntry(reference, section, referenceKey, recipe, { hideLabel: true });
                reference.appendChild(element(
                    'p',
                    'fotogenic-ai-field-help fotogenic-ai-model-contract-note',
                    __( 'The selected reference is applied consistently to every image in the campaign set. Campaign Set keeps person styling automatic; face, body, styling, action, expression, and grip controls are available in Generate Images.', 'fotogenic-ai' )
                ));
                body.appendChild(reference);
                return;
            }

            const mode = personPresenceMode(recipe);
            const person = createRecipeFieldGroup({
                id: 'fotogenic-ai-subject-person-heading',
                label: __( 'Person', 'fotogenic-ai' ),
                hiddenHeading: true,
            });
            const segmented = createSegmentedControl({
                id: 'fotogenic-recipe-personPresence',
                label: __( 'Presence', 'fotogenic-ai' ),
                value: mode,
                options: [
                    { value: PERSON_PRESENCE.automatic, label: __( 'Automatic', 'fotogenic-ai' ) },
                    { value: PERSON_PRESENCE.none, label: __( 'No person', 'fotogenic-ai' ) },
                    { value: PERSON_PRESENCE.model, label: __( 'Use a model', 'fotogenic-ai' ) },
                ],
                onChange(nextMode) {
                    setPersonPresenceMode(nextMode);
                    render(workflow, route);
                    window.requestAnimationFrame(() => controls.get('personPresence')?.focusControl?.focus?.({ preventScroll: true }));
                },
            });
            person.appendChild(segmented.fieldset);
            if (mode !== PERSON_PRESENCE.model || !(Number(recipe.subjectImageId) > 0)) {
                person.appendChild(element(
                    'p',
                    'fotogenic-ai-subject-mode-help',
                    mode === PERSON_PRESENCE.automatic
                        ? __( 'No model reference is sent. Fotogenic decides from the product and instructions.', 'fotogenic-ai' )
                        : (mode === PERSON_PRESENCE.none
                            ? __( 'No model reference or person-specific controls are sent.', 'fotogenic-ai' )
                            : __( 'Select one model reference to unlock supported person controls.', 'fotogenic-ai' ))
                ));
            }
            controls.set('personPresence', {
                focusControl: segmented.focusControl,
                sync() {},
                fieldNode: segmented.fieldset,
                section: 'subject',
            });
            body.appendChild(person);
            if (mode !== PERSON_PRESENCE.model) return;

            const reference = createRecipeFieldGroup({
                id: 'fotogenic-ai-subject-model-reference-heading',
                label: __( 'Model reference', 'fotogenic-ai' ),
            });
            appendEntry(reference, section, referenceKey, recipe, { hideLabel: true });
            body.appendChild(reference);
            if (!(Number(recipe.subjectImageId) > 0)) return;

            const modelControls = createRecipeFieldGroup({
                id: 'fotogenic-ai-subject-model-controls-heading',
                label: __( 'Model controls', 'fotogenic-ai' ),
                className: 'fotogenic-ai-subject-controls',
            });
            const booleanGrid = element('div', 'fotogenic-ai-subject-boolean-grid');
            ['includeFace', 'includeBody', 'lookAtCamera'].forEach((key) => {
                const entry = entryByKey(section, key);
                if (!entry || !fieldApplies(entry.field, route, recipe)) return;
                const current = getAtPath(recipe, [...entry.path, entry.name]);
                const segmentedBoolean = createSegmentedControl({
                    id: `fotogenic-recipe-${key}`,
                    label: fieldLabel(key),
                    description: FIELD_DESCRIPTIONS[key],
                    value: current === true ? 'yes' : (current === false ? 'no' : 'automatic'),
                    options: [
                        { value: 'automatic', label: __( 'Auto', 'fotogenic-ai' ) },
                        { value: 'yes', label: __( 'Yes', 'fotogenic-ai' ) },
                        { value: 'no', label: __( 'No', 'fotogenic-ai' ) },
                    ],
                    onChange(value) {
                        applyValue([...entry.path, entry.name], value === 'automatic' ? undefined : value === 'yes');
                        render(workflow, route);
                        window.requestAnimationFrame(() => controls.get(key)?.focusControl?.focus?.({ preventScroll: true }));
                    },
                });
                booleanGrid.appendChild(segmentedBoolean.fieldset);
                controls.set(key, {
                    focusControl: segmentedBoolean.focusControl,
                    sync() {},
                    fieldNode: segmentedBoolean.fieldset,
                    section: 'subject',
                });
            });
            modelControls.appendChild(booleanGrid);
            const optionGrid = element('div', 'fotogenic-ai-recipe-grid fotogenic-ai-recipe-grid-three fotogenic-ai-subject-option-grid');
            ['selections.styling', 'selections.clothing', 'selections.action', 'selections.expression', 'selections.grip']
                .forEach((key) => appendEntry(optionGrid, section, key, recipe));
            if (optionGrid.childElementCount) modelControls.appendChild(optionGrid);
            body.appendChild(modelControls);
        };

        const renderLookSection = (body, section, recipe) => {
            body.classList.add('fotogenic-ai-look-editor', 'fotogenic-ai-recipe-section-stack');
            if (workflow.id === 'campaign_set') {
                const visual = createRecipeFieldGroup({
                    id: 'fotogenic-ai-campaign-visual-direction-heading',
                    label: __( 'Visual direction', 'fotogenic-ai' ),
                    hiddenHeading: true,
                });
                const grid = element('div', 'fotogenic-ai-recipe-grid');
                const styleKey = entryByKey(section, 'style') ? 'style' : 'styleId';
                appendEntry(grid, section, styleKey, recipe, {
					label: __( 'Campaign style', 'fotogenic-ai' ),
					description: __( 'Choose one API-provided style for the coordinated set.', 'fotogenic-ai' ),
					emptyLabel: __( 'No style selected', 'fotogenic-ai' ),
				});
                visual.appendChild(grid);
                visual.appendChild(element('p', 'fotogenic-ai-field-help', __( 'Campaign Set derives its coordinated scenes internally. Standard Generate Images selections are intentionally not shown or sent.', 'fotogenic-ai' )));
                body.appendChild(visual);
                return;
            }
			const style = createRecipeFieldGroup({
				id: 'fotogenic-ai-look-style-heading',
				label: __( 'Style', 'fotogenic-ai' ),
				hiddenHeading: true,
			});
			const styleGrid = element('div', 'fotogenic-ai-recipe-grid');
			const styleKey = entryByKey(section, 'style') ? 'style' : 'styleId';
			appendEntry(styleGrid, section, styleKey, recipe, {
				label: __( 'Visual style', 'fotogenic-ai' ),
				description: __( 'Styles load from the current API catalog and can lock fields below.', 'fotogenic-ai' ),
				emptyLabel: __( 'No style selected', 'fotogenic-ai' ),
			});
			style.appendChild(styleGrid);
			const styleOptions = normalizeOptions(manifest.optionSources?.styles);
			const note = element('p', 'fotogenic-ai-style-policy-note');
			const syncStyleNote = () => {
				const selectedStyleId = String(styleGrid.querySelector('select')?.value || '');
				const selectedStyle = styleOptions.find((option) => option.value === selectedStyleId);
				note.replaceChildren();
				note.hidden = !selectedStyle;
				if (!selectedStyle) return;
				const copy = element('span');
				copy.appendChild(element('strong', '', selectedStyle.label));
				if (selectedStyle.description) {
					copy.appendChild(document.createTextNode(`: ${selectedStyle.description}`));
				}
				note.append(
					icons.create('sparkle', { weight: 'fill', size: 16 }),
					copy
				);
			};
			styleGrid.querySelector('select')?.addEventListener('change', syncStyleNote);
			syncStyleNote();
			style.appendChild(note);
			body.appendChild(style);
            const mood = createRecipeFieldGroup({ id: 'fotogenic-ai-look-mood-heading', label: __( 'Mood & lighting', 'fotogenic-ai' ) });
            const grid = element('div', 'fotogenic-ai-recipe-grid fotogenic-ai-recipe-grid-three fotogenic-ai-recipe-guided-grid');
            ['selections.emotion', 'selections.lighting', 'selections.atmosphere']
                .forEach((key) => appendEntry(grid, section, key, recipe, { description: FIELD_DESCRIPTIONS[key.split('.').at(-1)] }));
            mood.appendChild(grid);
            body.appendChild(mood);
        };

        const renderSceneSection = (body, section, recipe) => {
            body.classList.add('fotogenic-ai-scene-editor', 'fotogenic-ai-recipe-section-stack');
            if (workflow.id !== 'campaign_set') {
                const scene = createRecipeFieldGroup({ id: 'fotogenic-ai-scene-context-heading', label: __( 'Scene', 'fotogenic-ai' ), hiddenHeading: true });
                const grid = element('div', 'fotogenic-ai-recipe-grid fotogenic-ai-recipe-guided-grid');
                ['selections.setting', 'selections.bgElements']
                    .forEach((key) => appendEntry(grid, section, key, recipe, { description: FIELD_DESCRIPTIONS[key.split('.').at(-1)] }));
                scene.appendChild(grid);
                body.appendChild(scene);
            }
            const reference = createRecipeFieldGroup({
                id: workflow.id === 'campaign_set' ? 'fotogenic-ai-campaign-environment-reference-heading' : 'fotogenic-ai-scene-reference-heading',
                label: __( 'Environment reference', 'fotogenic-ai' ),
                hiddenHeading: workflow.id === 'campaign_set',
            });
            const referenceKey = workflow.id === 'campaign_set' ? 'environmentAttachmentId' : 'environmentImageId';
            appendEntry(reference, section, referenceKey, recipe, {
                label: __( 'Reference image', 'fotogenic-ai' ),
                description: workflow.id === 'campaign_set'
                    ? __( 'Use a reference image when the campaign should follow a specific place or setting.', 'fotogenic-ai' )
                    : __( 'Use a reference image when the setting should follow a specific place.', 'fotogenic-ai' ),
            });
            body.appendChild(reference);
        };

        const renderCameraSection = (body, section, recipe) => {
            body.classList.add('fotogenic-ai-camera-editor', 'fotogenic-ai-recipe-section-stack');
            const frame = createRecipeFieldGroup({ id: 'fotogenic-ai-camera-frame-heading', label: __( 'Frame', 'fotogenic-ai' ), hiddenHeading: true });
            const frameFields = element('div', 'fotogenic-ai-camera-frame-fields');
            const frameGrid = element('div', 'fotogenic-ai-recipe-grid fotogenic-ai-recipe-grid-three fotogenic-ai-recipe-guided-grid fotogenic-ai-camera-frame-grid');
            const keys = workflow.id === 'campaign_set'
                ? ['aspectRatio']
                : [
                    'selections.framing',
                    'selections.shotSize',
                    entryByKey(section, 'selections.aspectRatio') ? 'selections.aspectRatio' : 'aspectRatio',
                ];
            const rendered = new Set();
            keys.forEach((key) => {
                const entry = entryByKey(section, key);
                if (!entry || rendered.has(entry.key)) return;
                rendered.add(entry.key);
                appendEntry(frameGrid, section, key, recipe, { description: FIELD_DESCRIPTIONS[entry.name] });
            });
            frameFields.append(
                frameGrid,
                element('p', 'fotogenic-ai-camera-aspect-ratio-note', __( 'Omitted until you choose one. The current API may still resolve its own default.', 'fotogenic-ai' ))
            );
            frame.appendChild(frameFields);
            body.appendChild(frame);
            if (workflow.id === 'campaign_set') return;
            const camera = createRecipeFieldGroup({ id: 'fotogenic-ai-camera-controls-heading', label: __( 'Camera', 'fotogenic-ai' ) });
            const cameraGrid = element('div', 'fotogenic-ai-recipe-grid fotogenic-ai-recipe-grid-three fotogenic-ai-recipe-guided-grid');
            ['selections.angle', 'selections.focus'].forEach((key) => {
                const entry = entryByKey(section, key);
                if (entry) appendEntry(cameraGrid, section, key, recipe, { description: FIELD_DESCRIPTIONS[entry.name] });
            });
            camera.appendChild(cameraGrid);
            body.appendChild(camera);
        };

		const renderStructuredRecipe = (recipe) => {
            const { sections } = generateSectionEntries(workflow.recipe, route);
            renderRunSettings(recipe);
            if (!sections.length) return;

            const navigator = element('nav', 'fotogenic-ai-recipe-navigator');
            navigator.setAttribute('aria-label', __( 'Recipe sections', 'fotogenic-ai' ));
            const editor = element('section', 'fotogenic-ai-recipe-editor');
            editor.id = 'fotogenic-ai-recipe-editor-panel';
            const panels = element('div', 'fotogenic-ai-recipe-editor-panels');
            sectionButtons = new Map();
            sectionPanels = new Map();

            sections.forEach((section, index) => {
                const panelId = `fotogenic-ai-recipe-section-${section.id}`;
                const button = element('button', 'fotogenic-ai-recipe-nav-item');
                button.type = 'button';
                button.setAttribute('aria-controls', editor.id);
                const state = element('span', 'fotogenic-ai-recipe-nav-state', String(index + 1));
                state.setAttribute('aria-hidden', 'true');
                const copy = element('span', 'fotogenic-ai-recipe-nav-copy');
                const summary = element('small', '', __( 'Automatic', 'fotogenic-ai' ));
                copy.append(element('strong', '', section.label), summary);
                button.append(state, copy);
                button.addEventListener('click', () => selectRecipeSection(section.id, { focus: true }));
                navigator.appendChild(button);
                sectionButtons.set(section.id, { button, summary, state, section, index });

                const panel = element('section', 'fotogenic-ai-recipe-section');
                panel.id = panelId;
                panel.setAttribute('aria-labelledby', `${panelId}-title`);
                const heading = element('header', 'fotogenic-ai-recipe-editor-heading');
                const title = element('h2', '', section.label);
                title.id = `${panelId}-title`;
                title.tabIndex = -1;
                const helper = section.id === 'guidance'
                    ? section.helper
                    : sprintf( __( '%s Leave anything you do not need on automatic.', 'fotogenic-ai' ), section.helper );
                heading.append(title, element('p', '', helper));
                const body = element('div', 'fotogenic-ai-recipe-editor-fields');
                const sectionContent = element('div', 'fotogenic-ai-recipe-section__body fotogenic-ai-recipe-section-stack');
                if (section.id === 'guidance') sectionContent.classList.add('fotogenic-ai-guidance-editor');
                activeSectionOwner = section.id;
                if (section.id === 'delivery') {
                    renderProductDelivery(sectionContent);
                } else if (section.id === 'subject') {
                    renderSubjectSection(sectionContent, section, recipe);
                } else if (section.id === 'look') {
                    renderLookSection(sectionContent, section, recipe);
                } else if (section.id === 'scene') {
                    renderSceneSection(sectionContent, section, recipe);
                } else if (section.id === 'camera') {
                    renderCameraSection(sectionContent, section, recipe);
                } else {
                    section.entries.forEach((entry) => {
                        const node = createField(entry.name, entry.field, entry.path, recipe);
                        if (node) sectionContent.appendChild(node);
                    });
                }
                activeSectionOwner = '';
                body.appendChild(sectionContent);
                panel.append(heading, body);
                panels.appendChild(panel);
                sectionPanels.set(section.id, panel);
            });

            editor.append(unavailableRegion, panels, errorRegion);
            mount.append(navigator, editor);
            observeSectionNavigator(navigator);
            syncUnavailableRegion();
            if (!sectionPanels.has(activeSectionId)) activeSectionId = sections[0].id;
            selectRecipeSection(activeSectionId);
		};

		const enhancementRunItemCount = () => {
			return Math.max(0, Math.floor(Number(getRunItemCount?.())) || 0);
		};

		const syncEnhancementRunItemCount = () => {
			if (!enhancementRunItemValue?.isConnected) return;
			const count = enhancementRunItemCount();
			enhancementRunItemValue.textContent = sprintf(
				_n( '%1$s independent request', '%1$s independent requests', count, 'fotogenic-ai' ),
				new Intl.NumberFormat().format(count)
			);
		};

		const renderEnhancementWorkspace = () => {
			const workspace = element('section', 'fotogenic-ai-enhancement-workspace');
			const headingId = 'fotogenic-ai-enhancement-setup-title';
			workspace.setAttribute('aria-labelledby', headingId);
			const heading = element('header', 'fotogenic-ai-enhancement-heading');
			const headingCopy = element('div');
			const headingTitle = element('h2', '', __( 'Enhancement setup', 'fotogenic-ai' ));
			headingTitle.id = headingId;
			headingTitle.tabIndex = -1;
			headingCopy.append(
				element('span', 'fotogenic-ai-enhancement-eyebrow', __( 'Step 2 of 4 · Configure', 'fotogenic-ai' )),
				headingTitle,
				element('p', '', __( 'No extra settings are needed.', 'fotogenic-ai' ))
			);
			const headingIcon = icons.create('sliders-horizontal', { weight: 'regular', size: 22 });
			heading.append(headingCopy, headingIcon);

			const card = element('div', 'fotogenic-ai-endpoint-ready-card');
			const readyIcon = element('span', 'fotogenic-ai-endpoint-ready-icon');
			const checkIcon = icons.create('check', { weight: 'bold', size: 20 });
			readyIcon.appendChild(checkIcon);
			const copy = element('div');
			copy.append(
				element('h3', '', __( 'No recipe options required', 'fotogenic-ai' )),
				element('p', '', __( 'Increase Resolution processes every selected item as an independent one-image request and saves each result as a new Media Library attachment.', 'fotogenic-ai' ))
			);
			const metrics = element('dl');
			[
				[__( 'Run items', 'fotogenic-ai' ), ''],
				[__( 'Output per source', 'fotogenic-ai' ), __( '1 enhanced image', 'fotogenic-ai' )],
				[__( 'Source file', 'fotogenic-ai' ), __( 'Preserved', 'fotogenic-ai' )],
			].forEach(([label, value], index) => {
				const row = element('div');
				const data = element('dd', '', value);
				if (index === 0) enhancementRunItemValue = data;
				row.append(element('dt', '', label), data);
				metrics.appendChild(row);
			});
			syncEnhancementRunItemCount();
			card.append(readyIcon, copy, metrics);
			workspace.append(heading, card);
			if (workspaceActions) workspace.appendChild(workspaceActions);
			mount.appendChild(workspace);
		};

		const render = (nextWorkflow, nextRoute) => {
			closeContainedOverlay({ restoreFocus: false, immediate: true });
			if (workspaceActions && workspaceActions.parentElement !== recipeWorkspace) {
				recipeWorkspace?.appendChild(workspaceActions);
			}
            const previousRoute = route ? routeKey(route) : '';
            const incomingRoute = routeKey(nextRoute);
            listToken += 1;
            actionToken += 1;
            autoToken += 1;
            const routeChanged = previousRoute && previousRoute !== incomingRoute;
            if (routeChanged) {
                recipeIssues = [];
                listController?.abort?.();
                listController = null;
                listRequest = null;
                listRequestRoute = '';
            }
            actionController?.abort?.();
            autoController?.abort?.();
            actionController = null;
			autoController = null;
			listBusy = false;
			actionBusy = false;
			enhancementRunItemValue = null;
			workflow = nextWorkflow;
			route = nextRoute;
			mount.parentElement?.classList.toggle('is-enhancement', workflow.id === 'increase_resolution');
			renderedCampaignGroupSignature = workflow.id === 'campaign_set'
				? campaignGroups().map((group) => group.id).join(':')
				: '';
            controls = new Map();
            sectionButtons = new Map();
            sectionPanels = new Map();
            storedUnavailableOptions = new Map();
            presets = [];
            activePresetUuid = '';
            stopObservingSectionNavigator();
            toolsDocumentHandler && document.removeEventListener('pointerdown', toolsDocumentHandler, true);
            toolsDocumentHandler = null;
            toolsRoot = null;
            mount.replaceChildren();
			runSettingsMount?.replaceChildren();
			toolsMount?.replaceChildren();
			const configurationState = getConfigurationState();
			const connected = isAuthConnected();
			if (!connected || (configurationState !== 'ready' && workflow.id !== 'increase_resolution')) {
				const pending = connected && configurationState === 'loading';
				const status = element('section', 'fotogenic-ai-recipe-configuration-status');
				status.setAttribute('role', 'status');
				status.setAttribute('aria-live', 'polite');
				status.setAttribute('aria-busy', pending ? 'true' : 'false');
				const heading = !connected ? __( 'Sign in to Fotogenic', 'fotogenic-ai' )
					: pending ? __( 'Loading configuration…', 'fotogenic-ai' )
						: __( 'Configuration could not be loaded', 'fotogenic-ai' );
				status.appendChild(element('h2', '', heading));
				status.appendChild(element('p', '', connected
					? __( 'Your selections are saved. Retry to load the current options.', 'fotogenic-ai' )
					: __( 'Use Sign in in the top bar to configure and generate images. Your selections are saved.', 'fotogenic-ai' )));
				if (connected && typeof onRetryConfiguration === 'function') {
					const retry = element('button', 'secondary', pending ? __( 'Loading…', 'fotogenic-ai' ) : __( 'Retry', 'fotogenic-ai' ));
					retry.type = 'button';
					retry.disabled = pending;
					if (pending) {
						const spinner = icons.create('arrows-clockwise', { size: 16 });
						spinner.classList.add('fotogenic-ai-icon--spin');
						retry.prepend(spinner);
					}
					retry.addEventListener('click', onRetryConfiguration);
					status.appendChild(retry);
				}
				mount.appendChild(status);
				if (typeof onSectionChange === 'function') onSectionChange(sectionNavigation());
				return;
			}
			const recipe = workflow.id === 'campaign_set' ? editableRecipe() : (getState().draft.recipe || {});
            const entries = Object.entries(workflow.recipe?.fields || {})
				.filter(([name, field]) => !INTERNAL_FIELDS.has(name) && fieldApplies(field, route, recipe));
            if (!entries.length) {
				if (workflow.id === 'increase_resolution') renderEnhancementWorkspace();
				else mount.appendChild(element('p', 'fotogenic-ai-studio-empty-copy', __( 'This workflow has no recipe options.', 'fotogenic-ai' )));
			} else {
	                renderStructuredRecipe(recipe);
	                renderRecipeTools();
				syncRecipeIssues(recipeIssues);
	            }
			if (!sectionPanels.size && typeof onSectionChange === 'function') {
				onSectionChange(sectionNavigation());
			}
        };

        const issueControlKey = (issue) => {
            const message = String(issue || '');
            if (message === 'Use a model requires a model reference.') return 'subjectImageId';
            return [...controls.keys()]
                .sort((left, right) => right.length - left.length)
                .find((key) => message === key || message.startsWith(`${key} `) || message.startsWith(`${key}.`)) || '';
        };

	        const removeErrorReference = (control) => {
            const values = String(control.getAttribute('aria-describedby') || '')
                .split(/\s+/)
                .filter((value) => value && value !== errorRegion.id);
            if (values.length) {
                control.setAttribute('aria-describedby', values.join(' '));
            } else {
                control.removeAttribute('aria-describedby');
            }
            control.removeAttribute('aria-invalid');
	            control.removeAttribute('aria-errormessage');
	        };

		function syncRecipeIssues(issues) {
			const messages = Array.isArray(issues) ? issues.filter(Boolean) : [];
			recipeIssues = messages;
			controls.forEach((entry) => removeErrorReference(entry.focusControl));
			errorList.replaceChildren(...messages.map((message) => element('li', '', humanizeIssue(message))));
			syncErrorRegion();
			if (!messages.length) return;
			const key = issueControlKey(messages[0]);
			const entry = key ? controls.get(key) : null;
			if (!entry?.focusControl) return;
			const describedBy = String(entry.focusControl.getAttribute('aria-describedby') || '')
				.split(/\s+/)
				.filter(Boolean);
			if (!describedBy.includes(errorRegion.id)) describedBy.push(errorRegion.id);
			entry.focusControl.setAttribute('aria-describedby', describedBy.join(' '));
			entry.focusControl.setAttribute('aria-invalid', 'true');
			entry.focusControl.setAttribute('aria-errormessage', errorRegion.id);
		}

        const focusIssue = (issue) => {
            const key = issueControlKey(issue);
            const entry = key ? controls.get(key) : null;
            if (!entry?.focusControl?.focus) {
                errorRegion.focus();
                return false;
            }
            if (entry.section) selectRecipeSection(entry.section);
            entry.focusControl.focus();
            return true;
        };

        return {
            render,
			getSectionNavigation: sectionNavigation,
			resetSection() {
				const first = sectionPanels.keys().next().value;
				if (first) selectRecipeSection(first);
			},
			moveSection(direction, { focus = true } = {}) {
				const ids = [...sectionPanels.keys()];
				const index = ids.indexOf(activeSectionId);
				const nextIndex = index + (direction === 'previous' ? -1 : 1);
				if (index < 0 || nextIndex < 0 || nextIndex >= ids.length) return false;
				return selectRecipeSection(ids[nextIndex], { focus });
			},
	            updateContext: syncTools,
	            updateErrors(issues) {
				syncRecipeIssues(issues);
	            },
            focusIssue,
            focusFirst() {
                const first = [...controls.values()].find((entry) => entry.focusControl?.focus && !entry.focusControl.disabled);
                first?.focusControl?.focus?.();
            },
            destroy() {
				closeContainedOverlay({ restoreFocus: false, immediate: true });
				window.clearTimeout(toolsCloseTimer);
				toolsCloseTimer = 0;
                listToken += 1;
                actionToken += 1;
                autoToken += 1;
                listController?.abort?.();
                listRequest = null;
                listRequestRoute = '';
                actionController?.abort?.();
                autoController?.abort?.();
                toolsDocumentHandler && document.removeEventListener('pointerdown', toolsDocumentHandler, true);
                toolsDocumentHandler = null;
                stopObservingSectionNavigator();
                mount.replaceChildren();
				runSettingsMount?.replaceChildren();
				toolsMount?.replaceChildren();
                controls.clear();
            },
        };
    };

    Studio.recipeForm = Object.freeze({
        createRecipeForm,
        setAtPath,
        fieldApplies,
        humanizeIssue,
        fieldLabel,
        generateSectionEntries,
        selectOptionState,
    });
})();
