(() => {
    'use strict';

    window.FotogenicAI = window.FotogenicAI || {};
    const Studio = window.FotogenicAI.Studio = window.FotogenicAI.Studio || {};
    const Shared = window.FotogenicAI.Shared = window.FotogenicAI.Shared || {};
    const { __, _n, sprintf } = Studio.i18n;
    const vm = Studio.viewModel;
    const icons = Shared.ui?.icon;
    if (!icons) throw new Error('Fotogenic AI shared icon helper is required.');
	const resultStyles = Studio.resultsStyles;
	if (!resultStyles || typeof resultStyles !== 'object') throw new Error('Fotogenic AI Results styles are required.');
	const style = (...names) => names.filter(Boolean).map((name) => {
		const value = resultStyles[name];
		if (!value) throw new Error(`Fotogenic AI Results style is missing: ${name}`);
		return value;
	}).join(' ');
	const resultButton = (label = '', className = '') => {
		const control = vm.button(label, className);
		control.className = className;
		return control;
	};

    const RESULT_STATUSES = new Set(['loading', 'partial', 'completed', 'failed', 'removed']);
	const GROUP_STATUSES = new Set(['partial', 'completed', 'failed', 'skipped', 'stopped', 'uncertain', 'removed']);
    const PAGE_SIZES = new Set([10, 25, 50, 100]);
    const ATTACHMENT_ACTIONS = new Set(['apply_featured', 'apply_gallery', 'apply_both']);
	const GROUP_ACTIONS = new Set(['add_selected_to_gallery', 'add_all_to_gallery']);
	const APPLICATION_ACTIONS = new Set([...ATTACHMENT_ACTIONS, ...GROUP_ACTIONS]);
	let resultConfirmationSequence = 0;
	const ACTION_LABELS = Object.freeze({
		apply_featured: __( 'Set featured image', 'fotogenic-ai' ),
		apply_gallery: __( 'Add to gallery', 'fotogenic-ai' ),
		apply_both: __( 'Set featured + gallery', 'fotogenic-ai' ),
		add_selected_to_gallery: __( 'Add selected images to gallery', 'fotogenic-ai' ),
		add_all_to_gallery: __( 'Add all', 'fotogenic-ai' ),
		delete_attachment: __( 'Delete attachment', 'fotogenic-ai' ),
		keep_saved: __( 'Add to library', 'fotogenic-ai' ),
    });
	const allowedActions = (route) => new Set([
		...(route.workflow === 'product_images' && route.sourceType === 'product'
				? ['apply_featured', 'apply_gallery', 'apply_both', 'add_all_to_gallery']
            : []),
        ...(route.workflow === 'product_images' && ['post', 'page'].includes(route.sourceType)
            ? ['apply_featured']
            : []),
        ...(route.workflow === 'campaign_set' && route.sourceType === 'product'
			? ['apply_featured', 'add_selected_to_gallery', 'add_all_to_gallery']
            : []),
    ]);

    const normalizeActionList = (items, route) => {
        const allowed = allowedActions(route);
        return [...new Set((Array.isArray(items) ? items : [])
            .map((item) => vm.cleanText(item, 64).toLowerCase())
            .filter((item) => allowed.has(item)))];
    };

    const normalizeTargetIdentity = (value = {}) => {
        if (
            !value
            || typeof value !== 'object'
            || Array.isArray(value)
            || Object.keys(value).sort().join(',') !== 'destinationCapabilities,eligible,ineligibilityReason,label,parentProductId,schemaVersion,sku,sourceType,targetId,targetType,variationId'
            || value.schemaVersion !== 1
            || typeof value.sourceType !== 'string'
            || typeof value.targetType !== 'string'
            || typeof value.targetId !== 'number'
            || !Number.isSafeInteger(value.targetId)
            || value.targetId < 1
            || typeof value.parentProductId !== 'number'
            || !Number.isSafeInteger(value.parentProductId)
            || value.parentProductId < 0
            || typeof value.variationId !== 'number'
            || !Number.isSafeInteger(value.variationId)
            || value.variationId < 0
            || typeof value.sku !== 'string'
            || typeof value.label !== 'string'
            || typeof value.eligible !== 'boolean'
            || typeof value.ineligibilityReason !== 'string'
            || !value.destinationCapabilities
            || typeof value.destinationCapabilities !== 'object'
            || Array.isArray(value.destinationCapabilities)
            || Object.keys(value.destinationCapabilities).sort().join(',') !== 'addGallery,applyFeatured,setFeatured,setFeaturedAndGallery'
            || Object.values(value.destinationCapabilities).some((capability) => typeof capability !== 'boolean')
        ) return null;
        const sourceType = vm.cleanText(value.sourceType, 32).toLowerCase();
        const targetType = vm.cleanText(value.targetType, 32).toLowerCase();
        const productTarget = sourceType === 'product' && (
            (targetType === 'product' && value.parentProductId === 0 && value.variationId === 0)
            || (targetType === 'variation' && value.parentProductId > 0 && value.variationId === value.targetId)
        );
        const wordPressTarget = ['media', 'post', 'page'].includes(sourceType)
            && targetType === sourceType
            && value.parentProductId === 0
            && value.variationId === 0;
        if (!productTarget && !wordPressTarget) return null;
        return Object.freeze({
            schemaVersion: 1,
            sourceType,
            targetType,
            targetId: value.targetId,
            parentProductId: value.parentProductId,
            variationId: value.variationId,
            label: vm.cleanText(value.label, 200),
            sku: vm.cleanText(value.sku, 100),
            eligible: value.eligible,
            ineligibilityReason: vm.safeCode(value.ineligibilityReason),
            destinationCapabilities: Object.freeze({
                setFeatured: value.destinationCapabilities.setFeatured,
                addGallery: value.destinationCapabilities.addGallery,
                setFeaturedAndGallery: value.destinationCapabilities.setFeaturedAndGallery,
                applyFeatured: value.destinationCapabilities.applyFeatured,
            }),
        });
    };

    const normalizeTargetLinks = (value = {}) => {
        if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
        const editUrl = vm.safeUrl(value.editUrl);
        const viewUrl = vm.safeUrl(value.viewUrl);
        if (!editUrl && !viewUrl) return null;
        return Object.freeze({ editUrl, viewUrl });
    };
	const targetLinkLabels = (sourceType, targetIdentity) => {
		if (targetIdentity?.sourceType !== sourceType) return null;
		if (sourceType === 'product') {
			return Object.freeze({ edit: __( 'View product', 'fotogenic-ai' ), view: __( 'View storefront', 'fotogenic-ai' ) });
		}
		if (sourceType === 'post') {
			return Object.freeze({ edit: __( 'Edit post', 'fotogenic-ai' ), view: __( 'View post', 'fotogenic-ai' ) });
		}
		if (sourceType === 'page') {
			return Object.freeze({ edit: __( 'Edit page', 'fotogenic-ai' ), view: __( 'View page', 'fotogenic-ai' ) });
		}
		return null;
	};

    const normalizeGroup = (value = {}, index, route, remaining, fallback = {}) => {
        const attachments = vm.normalizeAttachments(value.attachments, remaining);
        const rawStatus = vm.cleanText(value.status, 32).toLowerCase();
        const appliedAction = vm.cleanText(value.appliedAction, 64).toLowerCase();
		const requestedAppliedAttachmentId = vm.positiveInteger(value.appliedAttachmentId);
        const appliedAttachmentId = attachments.some((attachment) => attachment.attachmentId === requestedAppliedAttachmentId)
			? requestedAppliedAttachmentId
			: 0;
		const appliedAttachmentIds = [...new Set((Array.isArray(value.appliedAttachmentIds) ? value.appliedAttachmentIds : [])
			.map((attachmentId) => vm.positiveInteger(attachmentId))
			.filter((attachmentId) => attachments.some((attachment) => attachment.attachmentId === attachmentId)))];
		const applicationApplied = allowedActions(route).has(appliedAction)
			&& (!ATTACHMENT_ACTIONS.has(appliedAction) || appliedAttachmentId > 0)
			&& (appliedAction !== 'add_selected_to_gallery' || appliedAttachmentIds.length > 0);
		const deliveryPending = value.deliveryPending === true;
		const deliveryFailed = value.deliveryFailed === true;
		const deliveryRetryAvailable = deliveryFailed && value.deliveryRetryAvailable === true;
		const availableActions = normalizeActionList(value.availableActions, route);
		const unappliedActions = normalizeActionList(value.unappliedActions ?? value.availableActions, route);
        const source = vm.normalizeAttachment(value.source) || fallback.source || null;
        const sources = vm.normalizeAttachments(value.sources, 10);
        if (source && !sources.some((candidate) => candidate.attachmentId === source.attachmentId)) sources.unshift(source);
        const currentProduct = vm.normalizeAttachment(value.currentProduct) || fallback.currentProduct || null;
		const requestedOutputCount = vm.positiveInteger(value.requestedOutputCount, attachments.length || 1, 100);
		const completedOutputCount = vm.nonNegativeInteger(value.completedOutputCount, attachments.length, requestedOutputCount);
		const failedOutputCount = vm.nonNegativeInteger(value.failedOutputCount, Math.max(0, requestedOutputCount - completedOutputCount), requestedOutputCount);
        return Object.freeze({
            key: vm.cleanText(value.key ?? value.groupId ?? value.subjectId, 100) || `group-${index + 1}`,
            label: vm.cleanText(value.label ?? value.title ?? value.name, 200) || (route.scope === 'bulk' ? sprintf( __( 'Item %d', 'fotogenic-ai' ), index + 1 ) : __( 'Generated images', 'fotogenic-ai' )),
            status: GROUP_STATUSES.has(rawStatus) ? rawStatus : (attachments.length ? 'completed' : 'failed'),
            message: vm.cleanText(value.message, 300),
            attachments,
			availableActions: applicationApplied || deliveryPending ? [] : availableActions,
			unappliedActions,
			appliedAction: applicationApplied ? appliedAction : '',
			appliedAttachmentId: applicationApplied ? appliedAttachmentId : 0,
			appliedAttachmentIds: applicationApplied ? Object.freeze(appliedAttachmentIds) : Object.freeze([]),
			deliveryPending,
			deliveryFailed,
			deliveryRetryAvailable,
            source,
            sources: sources.length ? Object.freeze(sources) : fallback.sources,
            sourceMissing: value.sourceMissing === true || fallback.sourceMissing === true,
            currentProduct,
            currentProductMissing: value.currentProductMissing === true || fallback.currentProductMissing === true,
            targetIdentity: normalizeTargetIdentity(value.targetIdentity) || fallback.targetIdentity,
            targetLinks: normalizeTargetLinks(value.targetLinks) || fallback.targetLinks,
			quality: vm.normalizeOutputQuality(value.quality ?? fallback.quality, route.workflow),
            deliveryLabel: vm.cleanText(value.deliveryLabel ?? fallback.deliveryLabel, 120),
			requestedOutputCount,
            savedOutputCount: vm.nonNegativeInteger(value.savedOutputCount, attachments.length, 100),
			completedOutputCount,
			failedOutputCount,
        });
    };

    const normalizeResults = (value = {}) => {
        const route = vm.normalizeRoute(value);
        const rawStatus = vm.cleanText(value.status, 32).toLowerCase();
        const status = RESULT_STATUSES.has(rawStatus) ? rawStatus : 'completed';
        const source = vm.normalizeAttachment(value.source);
        const sources = vm.normalizeAttachments(value.sources, 10);
        if (source && !sources.some((candidate) => candidate.attachmentId === source.attachmentId)) sources.unshift(source);
        const fallback = Object.freeze({
            source,
            sources: Object.freeze(sources),
            sourceMissing: value.sourceMissing === true || value.source?.missing === true,
            currentProduct: vm.normalizeAttachment(value.currentProduct),
            currentProductMissing: value.currentProductMissing === true || value.currentProduct?.missing === true,
            targetIdentity: normalizeTargetIdentity(value.targetIdentity),
            targetLinks: normalizeTargetLinks(value.targetLinks),
			quality: vm.normalizeOutputQuality(value.quality, route.workflow),
            deliveryLabel: vm.cleanText(value.deliveryLabel, 120),
        });
        const candidates = Array.isArray(value.groups) && value.groups.length
            ? value.groups
            : status === 'loading'
                ? []
                : [{
                    key: 'results',
                    label: value.groupLabel,
                    status,
					message: value.message,
					attachments: value.attachments,
					availableActions: value.availableActions,
					unappliedActions: value.unappliedActions,
					appliedAction: value.appliedAction,
					appliedAttachmentId: value.appliedAttachmentId,
					appliedAttachmentIds: value.appliedAttachmentIds,
					deliveryPending: value.deliveryPending,
					deliveryFailed: value.deliveryFailed,
					deliveryRetryAvailable: value.deliveryRetryAvailable,
					deliveryLabel: value.deliveryLabel,
				}];
        const groups = [];
        let remaining = 100;
        candidates.slice(0, 50).forEach((group, index) => {
            if (remaining <= 0) return;
            const normalized = normalizeGroup(group, index, route, remaining, fallback);
            remaining -= normalized.attachments.length;
            groups.push(normalized);
        });
        const attachmentCount = groups.reduce((count, group) => count + group.attachments.length, 0);
        const totalItems = vm.positiveInteger(value.totalItems, groups.length || 1, 100000);
        return Object.freeze({
            ...route,
            status,
            groups: Object.freeze(groups),
            source,
            sources: Object.freeze(sources),
            sourceMissing: fallback.sourceMissing,
            currentProduct: fallback.currentProduct,
            currentProductMissing: fallback.currentProductMissing,
            targetIdentity: fallback.targetIdentity,
            targetLinks: fallback.targetLinks,
            quality: fallback.quality,
            deliveryLabel: fallback.deliveryLabel,
            attachmentCount,
            totalItems,
            partialSnapshot: totalItems > groups.length,
            message: vm.cleanText(value.message, 400),
            resultKey: vm.cleanText(value.resultKey, 100)
                || `${route.workflow}:${groups.flatMap((group) => group.attachments.map((item) => item.attachmentId)).join(',')}`,
        });
    };

    const paginateResults = (items, page = 1, pageSize = 25) => {
        const normalizedItems = Array.isArray(items) ? items : [];
        const size = PAGE_SIZES.has(Number(pageSize)) ? Number(pageSize) : 25;
        const totalPages = Math.max(1, Math.ceil(normalizedItems.length / size));
        const activePage = Math.min(totalPages, vm.positiveInteger(page, 1, 100000));
        const offset = (activePage - 1) * size;
        return Object.freeze({
            items: normalizedItems.slice(offset, offset + size),
            page: activePage,
            pageSize: size,
            totalPages,
            totalItems: normalizedItems.length,
            start: normalizedItems.length ? offset + 1 : 0,
            end: Math.min(offset + size, normalizedItems.length),
        });
    };

    const intersectResultActions = (groups) => {
        const eligible = (Array.isArray(groups) ? groups : []).filter((group) => group.attachments.length);
        if (!eligible.length) return [];
        return eligible[0].availableActions.filter((action) => (
            eligible.every((group) => group.availableActions.includes(action))
            && (GROUP_ACTIONS.has(action) || (ATTACHMENT_ACTIONS.has(action) && eligible.every((group) => group.attachments.length === 1)))
        ));
    };

    const resultPresentation = (value = {}) => {
        const groups = Array.isArray(value.groups) ? value.groups : [];
        return groups.length === 1 ? 'single' : 'collection';
    };

	const isImmersiveSingleResult = (route = {}, group = {}) => (
		route.workflow !== 'increase_resolution'
		&& Array.isArray(group.attachments)
		&& group.attachments.length > 0
    );

    const formatByteSize = (bytes, compact = false) => {
        const size = vm.nonNegativeInteger(bytes, 0, 10 ** 12);
        return size
            ? sprintf(
                compact ? __( '%1$s KiB', 'fotogenic-ai' ) : __( '%1$s KiB (%2$s bytes)', 'fotogenic-ai' ),
                new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(size / 1024),
                new Intl.NumberFormat(undefined).format(size)
            )
            : __( 'Unknown', 'fotogenic-ai' );
    };

    const deliveryLabel = (group, route) => {
        if (group.deliveryLabel) return group.deliveryLabel;
        if (route.sourceType === 'product') return __( 'Review before product changes', 'fotogenic-ai' );
        if (['post', 'page'].includes(route.sourceType)) return __( 'Review before featured-image changes', 'fotogenic-ai' );
        return __( 'Media Library only', 'fotogenic-ai' );
    };

    const sourceNoun = (sourceType, count) => {
        const nouns = {
            product: [__( 'product', 'fotogenic-ai' ), __( 'products', 'fotogenic-ai' )],
            media: [__( 'media item', 'fotogenic-ai' ), __( 'media items', 'fotogenic-ai' )],
            post: [__( 'post', 'fotogenic-ai' ), __( 'posts', 'fotogenic-ai' )],
            page: [__( 'page', 'fotogenic-ai' ), __( 'pages', 'fotogenic-ai' )],
        };
        const pair = nouns[sourceType] || [__( 'item', 'fotogenic-ai' ), __( 'items', 'fotogenic-ai' )];
        return count === 1 ? pair[0] : pair[1];
    };

	const groupPresentation = (group, route = {}) => {
		if (group.appliedAction) {
			return { label: __( 'Applied', 'fotogenic-ai' ), action: __( 'View applied result', 'fotogenic-ai' ), tone: 'ready' };
		}
		if (group.status === 'removed') {
			return { label: __( 'Removed', 'fotogenic-ai' ), action: __( 'View details', 'fotogenic-ai' ), tone: 'stopped' };
		}
		if (group.status === 'completed') {
			return group.availableActions.length
				? {
					label: __( 'Ready to apply', 'fotogenic-ai' ),
					action: __( 'Choose destination', 'fotogenic-ai' ),
                    tone: 'ready',
                }
				: {
					label: __( 'Saved', 'fotogenic-ai' ),
					action: route.workflow === 'increase_resolution'
						? __( 'Open enhanced image', 'fotogenic-ai' )
						: __( 'Open image', 'fotogenic-ai' ),
					tone: 'ready',
				};
		}
		if (group.status === 'partial' && group.deliveryFailed) {
			return {
				label: __( 'Delivery failed', 'fotogenic-ai' ),
				action: group.deliveryRetryAvailable ? __( 'Retry delivery', 'fotogenic-ai' ) : __( 'View saved attachment', 'fotogenic-ai' ),
				tone: 'attention',
			};
		}
		if (group.status === 'partial') return { label: __( 'Partially saved', 'fotogenic-ai' ), action: __( 'View saved result', 'fotogenic-ai' ), tone: 'attention' };
		if (group.status === 'uncertain') return { label: __( 'Status needs reconciliation', 'fotogenic-ai' ), action: __( 'Return to progress', 'fotogenic-ai' ), tone: 'attention' };
		if (group.status === 'failed') return { label: __( 'Generation failed', 'fotogenic-ai' ), action: __( 'Regenerate · New credits', 'fotogenic-ai' ), tone: 'attention' };
		if (group.status === 'stopped' && group.attachments.length) {
			return { label: __( 'Stopped', 'fotogenic-ai' ), action: __( 'View saved result', 'fotogenic-ai' ), tone: 'stopped' };
		}
		return { label: __( 'Stopped', 'fotogenic-ai' ), action: __( 'No saved result', 'fotogenic-ai' ), tone: 'stopped' };
	};
	const groupState = (group) => group.status === 'removed'
		? 'removed'
		: (group.appliedAction ? 'applied' : groupPresentation(group).tone);
	const groupOutputLabel = (group) => {
		if (group.status === 'removed') return __( 'Attachment deleted', 'fotogenic-ai' );
		if (group.failedOutputCount > 0) {
			return sprintf(
				__( '%1$d completed, %2$d failed', 'fotogenic-ai' ),
				group.completedOutputCount,
				group.failedOutputCount
			);
		}
		if (group.status === 'failed') {
			return sprintf( _n( '0 of %d output', '0 of %d outputs', group.requestedOutputCount, 'fotogenic-ai' ), group.requestedOutputCount );
		}
		return sprintf( _n( '%d output', '%d outputs', group.attachments.length, 'fotogenic-ai' ), group.attachments.length );
	};

    const statusIcon = (status) => {
		if (status === 'completed') return icons.create('check-circle', { weight: 'fill', size: 16 });
		if (status === 'removed') return icons.create('trash', { size: 16 });
		if (['failed', 'partial'].includes(status)) return icons.create('warning', { weight: 'fill', size: 16 });
		if (['skipped', 'stopped'].includes(status)) return icons.create('stop-circle', { weight: 'fill', size: 16 });
        return icons.create('clock', { weight: 'fill', size: 16 });
    };

    const createResultsView = ({ mount, announce = () => {} } = {}) => {
        let current = null;
        let handlers = {};
        let pending = '';
        let actionError = '';
        let lastResultKey = '';
        let restoreFocusKey = '';
		let renderRevision = 0;
        let destroyed = false;
        let query = '';
        let filter = 'all';
        let layout = 'list';
        let page = 1;
		let pageSize = 25;
		let selectedKeys = new Set();
		let campaignOutputSelections = new Map();
        let activeGroupKey = '';
        let inspectorManager = null;
        let inspectorLayer = null;
        let inspectorReturnFocus = null;
		let lightboxModal = null;
        let confirmationManager = null;
        let confirmationLayer = null;
        let confirmationResolve = null;
        let confirmationReturnFocus = null;

        const closeConfirmation = (accepted = false, { immediate = false } = {}) => {
            const manager = confirmationManager;
            const layer = confirmationLayer;
            const resolve = confirmationResolve;
            const returnFocus = confirmationReturnFocus;
            confirmationManager = null;
            confirmationLayer = null;
            confirmationResolve = null;
            confirmationReturnFocus = null;
            const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
            manager?.close?.({ immediate: immediate || reducedMotion });
            if (!manager) layer?.remove?.();
            const settle = () => {
                inspectorLayer?.querySelector?.('[role="dialog"]')?.setAttribute?.('aria-modal', 'true');
                resolve?.(accepted);
                window.requestAnimationFrame(() => returnFocus?.isConnected && returnFocus.focus?.({ preventScroll: true }));
            };
            if (immediate || reducedMotion || !manager) settle();
            else window.setTimeout(settle, 220);
        };

        const requestConfirmation = (confirmation, returnFocus = document.activeElement) => new Promise((resolve) => {
            closeConfirmation(false, { immediate: true });
            confirmationResolve = resolve;
            confirmationReturnFocus = returnFocus?.focus ? returnFocus : null;
			resultConfirmationSequence += 1;
			const titleId = `fotogenic-ai-result-confirmation-title-${resultConfirmationSequence}`;
			const descriptionId = `fotogenic-ai-result-confirmation-description-${resultConfirmationSequence}`;
            const layer = vm.element('div', style('result-confirmation-layer'));
            layer.setAttribute('role', 'presentation');
            const dialog = vm.element('section', style('result-confirmation'));
            dialog.setAttribute('role', 'alertdialog');
            dialog.setAttribute('aria-modal', 'true');
            dialog.setAttribute('aria-labelledby', titleId);
            dialog.setAttribute('aria-describedby', descriptionId);
            const icon = vm.element('span', style('confirmation-icon', confirmation.destructive ? 'is-danger' : ''));
            icon.appendChild(icons.create(confirmation.destructive ? 'trash' : 'shield-check', { size: 22 }));
            const title = vm.element('h2', '', confirmation.title);
            title.id = titleId;
            const description = vm.element('div');
            description.id = descriptionId;
            description.appendChild(vm.element('p', '', confirmation.description));
            if (confirmation.note) description.appendChild(vm.element('small', '', confirmation.note));
            const footer = document.createElement('footer');
            const cancel = resultButton(__( 'Cancel', 'fotogenic-ai' ), style('secondary'));
            const confirm = resultButton(confirmation.confirmLabel, style(confirmation.destructive ? 'danger-button' : 'primary'));
            cancel.addEventListener('click', () => closeConfirmation(false));
            confirm.addEventListener('click', () => closeConfirmation(true));
            footer.append(cancel, confirm);
            dialog.append(icon, title, description, footer);
            layer.appendChild(dialog);
            const workspace = mount.querySelector(`.${style('results-workspace')}`) || mount;
            workspace.appendChild(layer);
            inspectorLayer?.querySelector?.('[role="dialog"]')?.setAttribute?.('aria-modal', 'false');
            confirmationLayer = layer;
            if (!Shared.ui?.containedOverlay?.create) {
                confirmationResolve = null;
                layer.remove();
                resolve(false);
                return;
            }
            confirmationManager = Shared.ui.containedOverlay.create({
                layer,
                panel: dialog,
                decorate: false,
                onClose: () => closeConfirmation(false),
                initialFocus: dialog,
                returnFocus: confirmationReturnFocus,
            });
            confirmationManager.open({ returnFocus: confirmationReturnFocus });
        });

		const selectedCampaignOutputIds = (group) => {
			const availableIds = group.attachments.map((attachment) => attachment.attachmentId);
			const available = new Set(availableIds);
			let selected = campaignOutputSelections.get(group.key);
			if (!selected) {
				selected = new Set(availableIds);
				campaignOutputSelections.set(group.key, selected);
				return selected;
			}
			selected = new Set([...selected].filter((attachmentId) => available.has(attachmentId)));
			campaignOutputSelections.set(group.key, selected);
			return selected;
		};

		const destinationActionLabel = (action, group) => {
			if (action === 'keep_saved') return __( 'Add to library', 'fotogenic-ai' );
            if (action === 'apply_featured' && group.targetIdentity?.targetType === 'variation') {
				return __( 'Set variation image', 'fotogenic-ai' );
            }
            if (action === 'apply_featured' && ['post', 'page'].includes(current.sourceType)) {
				return __( 'Set featured image', 'fotogenic-ai' );
            }
			if (action === 'apply_gallery') return __( 'Add to gallery', 'fotogenic-ai' );
			if (action === 'apply_both') return __( 'Set featured + gallery', 'fotogenic-ai' );
			if (action === 'add_all_to_gallery') return __( 'Add all', 'fotogenic-ai' );
            return ACTION_LABELS[action] || __( 'Apply destination', 'fotogenic-ai' );
        };

		const appliedDestinationLabel = (action, group) => {
			if (action === 'apply_featured') {
				if (group.targetIdentity?.targetType === 'variation') return __( 'exact variation image', 'fotogenic-ai' );
				if (['post', 'page'].includes(current.sourceType)) {
					return sprintf( __( '%s featured image', 'fotogenic-ai' ), current.sourceType );
				}
				return __( 'featured image', 'fotogenic-ai' );
			}
			if (action === 'apply_both') return __( 'featured image and product gallery', 'fotogenic-ai' );
			return __( 'product gallery', 'fotogenic-ai' );
		};

        const destinationActions = (group, actions) => {
            const available = Array.isArray(actions) ? actions : [];
			if (!group.attachments.length) return [];
            if (group.targetIdentity?.targetType === 'variation') {
                return [
                    ...(available.includes('apply_featured') ? ['apply_featured'] : []),
                    'keep_saved',
                ];
            }
            return available.length ? [...available, 'keep_saved'] : available;
        };

		const actionConfirmation = (action, group, attachment = null) => {
            if (action === 'delete_attachment') {
                return {
                    destructive: true,
                    title: __( 'Delete generated attachment?', 'fotogenic-ai' ),
                    description: __( 'Permanently delete this saved Media Library attachment? Related product, variation, or featured-image associations may also be removed.', 'fotogenic-ai' ),
                    note: __( 'Existing source files and other generated versions are not changed.', 'fotogenic-ai' ),
                    confirmLabel: __( 'Delete attachment', 'fotogenic-ai' ),
                };
            }
			const label = action === 'add_selected_to_gallery'
				? sprintf(
					_n( 'Add %d selected image to gallery', 'Add %d selected images to gallery', selectedCampaignOutputIds(group).size, 'fotogenic-ai' ),
					selectedCampaignOutputIds(group).size
				)
				: destinationActionLabel(action, group);
			const keepsSaved = action === 'keep_saved';
			const selectedCampaignCount = action === 'add_selected_to_gallery'
				? selectedCampaignOutputIds(group).size
				: 0;
            const outputIndex = Math.max(0, group.attachments.findIndex((item) => item.attachmentId === attachment?.attachmentId));
            return {
                title: sprintf( __( '%s?', 'fotogenic-ai' ), label ),
                description: keepsSaved
                    ? __( 'The generated attachments will remain in Media Library; no product or content destination will change.', 'fotogenic-ai' )
                    : __( 'The generated attachments are already saved. Confirm this platform destination for the result.', 'fotogenic-ai' ),
                note: [
					group.targetIdentity?.targetType === 'variation'
						? (group.targetIdentity.sku
							? sprintf(
								__( 'Destination locked to %1$s (%2$s); the parent product will not be changed.', 'fotogenic-ai' ),
								group.targetIdentity.label,
								group.targetIdentity.sku
							)
							: sprintf(
								__( 'Destination locked to %s; the parent product will not be changed.', 'fotogenic-ai' ),
								group.targetIdentity.label
							))
						: '',
                    !keepsSaved && ['apply_featured', 'apply_both'].includes(action)
                        ? sprintf( __( 'Generated output %d will be used for this destination.', 'fotogenic-ai' ), outputIndex + 1 )
                        : '',
                ].filter(Boolean).join(' '),
				confirmLabel: keepsSaved
					? __( 'Add to library', 'fotogenic-ai' )
					: (action === 'add_selected_to_gallery'
						? sprintf(
							_n( 'Add %d image to gallery', 'Add %d images to gallery', selectedCampaignCount, 'fotogenic-ai' ),
							selectedCampaignCount
						)
						: label),
            };
        };

        const closeLightbox = () => {
			if (!lightboxModal) return;
			const modal = lightboxModal;
			lightboxModal = null;
			modal.close?.();
			modal.detach?.();
			modal.remove?.();
        };

        const destroyInspector = ({ preserveKey = false, restoreFocus = false } = {}) => {
            closeLightbox();
            inspectorManager?.destroy?.();
            inspectorManager = null;
            inspectorLayer?.remove?.();
            inspectorLayer = null;
            if (!preserveKey) activeGroupKey = '';
            if (restoreFocus) inspectorReturnFocus?.focus?.({ preventScroll: true });
        };

        const requestInspectorClose = () => {
            const layer = inspectorLayer;
            const manager = inspectorManager;
            inspectorManager = null;
            inspectorLayer = null;
            activeGroupKey = '';
            closeLightbox();
            manager?.close?.({ immediate: true });
            layer?.remove?.();
        };

		const commitApplicationOutcome = (name, outcome, payload, { restorePrimaryFocus = true } = {}) => {
			if (
				!APPLICATION_ACTIONS.has(name)
				|| outcome?.status !== 'applied'
				|| outcome?.action !== name
				|| typeof outcome?.changed !== 'boolean'
			) throw new Error('invalid_application_response');
			let matched = false;
			const appliedAttachmentId = ATTACHMENT_ACTIONS.has(name)
				? vm.positiveInteger(payload?.attachmentId)
				: 0;
			const appliedAttachmentIds = name === 'add_selected_to_gallery'
				? [...new Set((Array.isArray(payload?.attachmentIds) ? payload.attachmentIds : [])
					.map((attachmentId) => vm.positiveInteger(attachmentId))
					.filter(Boolean))]
				: [];
			const groups = current.groups.map((group) => {
				if (group.key !== payload?.groupKey) return group;
					if (
						ATTACHMENT_ACTIONS.has(name)
						&& !group.attachments.some((attachment) => attachment.attachmentId === appliedAttachmentId)
					) return group;
					if (
						name === 'add_selected_to_gallery'
						&& (
							!appliedAttachmentIds.length
							|| appliedAttachmentIds.some((attachmentId) => !group.attachments.some((attachment) => attachment.attachmentId === attachmentId))
						)
					) return group;
				matched = true;
				const generationPartial = group.savedOutputCount < group.requestedOutputCount;
				return {
					...group,
					status: generationPartial ? 'partial' : 'completed',
					message: generationPartial
						? __( 'Some requested outputs were not saved. Available images are shown.', 'fotogenic-ai' )
						: '',
						appliedAction: name,
						appliedAttachmentId,
						appliedAttachmentIds,
					availableActions: [],
					deliveryPending: false,
					deliveryFailed: false,
					deliveryRetryAvailable: false,
						deliveryLabel: name === 'add_all_to_gallery'
							? __( 'Appended to product gallery', 'fotogenic-ai' )
							: (name === 'add_selected_to_gallery'
								? sprintf(
									__( '%1$d of %2$d campaign images appended to product gallery', 'fotogenic-ai' ),
									appliedAttachmentIds.length,
									group.attachments.length
								)
								: __( 'Applied to destination', 'fotogenic-ai' )),
				};
			});
			if (!matched) throw new Error('missing_application_group');
			current = normalizeResults({ ...current, groups });
			selectedKeys.delete(payload.groupKey);
			if (restorePrimaryFocus) {
				restoreFocusKey = `results:primary:${encodeURIComponent(payload.groupKey)}`;
			}
			return current.groups.find((group) => group.key === payload.groupKey) || null;
		};

		const selectedApplicationMessage = (completed, total) => sprintf(
			_n( '%d selected destination completed.', '%d selected destinations completed.', total, 'fotogenic-ai' ),
			completed
		);

		const partialApplicationMessage = (completed, total, failed) => [
			sprintf(
				_n( '%1$d of %2$d selected destination completed.', '%1$d of %2$d selected destinations completed.', total, 'fotogenic-ai' ),
				completed,
				total
			),
			sprintf(
				_n( '%d destination could not be completed and remains selected.', '%d destinations could not be completed and remain selected.', failed, 'fotogenic-ai' ),
				failed
			),
			__( 'Completed destinations were not rolled back.', 'fotogenic-ai' ),
		].join(' ');

		const invokeApplicationBatch = async (name, groups, { confirmation = null, returnFocus = null } = {}) => {
			if (
				destroyed
				|| pending
				|| !APPLICATION_ACTIONS.has(name)
				|| typeof handlers[name] !== 'function'
			) return;
			if (confirmation && !await requestConfirmation(confirmation, returnFocus)) return;
			const requestedKeys = new Set((Array.isArray(groups) ? groups : []).map((group) => group.key));
			const queue = current.groups.filter((group) => (
				requestedKeys.has(group.key)
				&& selectedKeys.has(group.key)
				&& group.availableActions.includes(name)
			));
			if (!queue.length) return;
			pending = name;
			actionError = '';
			restoreFocusKey = `results:batch:${name}`;
			renderCurrent();
			let completed = 0;
			let failed = 0;
			try {
				for (const queuedGroup of queue) {
					if (destroyed || !current) break;
					const group = current.groups.find((candidate) => candidate.key === queuedGroup.key);
					if (!group || !group.availableActions.includes(name) || !selectedKeys.has(group.key)) {
						failed += 1;
						continue;
					}
					const attachment = ATTACHMENT_ACTIONS.has(name) ? group.attachments[0] : null;
					const payload = actionPayload(
						group,
						attachment,
						name === 'add_selected_to_gallery' ? [...selectedCampaignOutputIds(group)] : null
					);
					try {
						const outcome = await handlers[name](payload);
						if (destroyed || !current) break;
						commitApplicationOutcome(name, outcome, payload, { restorePrimaryFocus: false });
						completed += 1;
						renderCurrent();
					} catch (_) {
						if (destroyed || !current) break;
						failed += 1;
					}
				}
				if (destroyed || !current) return;
				if (failed) {
					actionError = partialApplicationMessage(completed, queue.length, failed);
					announce(actionError);
				} else {
					announce(selectedApplicationMessage(completed, queue.length));
				}
			} finally {
				pending = '';
				if (!destroyed && current) renderCurrent();
			}
		};

        const invoke = async (name, callback, payload, { navigation = false, confirmation = null, returnFocus = null } = {}) => {
            if (destroyed || pending || typeof callback !== 'function') return;
            if (confirmation) {
                if (!await requestConfirmation(confirmation, returnFocus)) return;
            }
            pending = name;
            actionError = '';
            renderCurrent();
            let navigated = false;
            try {
                const outcome = await callback(payload);
                if (name === 'delete_attachment') {
                    if (
                        outcome?.status !== 'removed'
                        || typeof outcome?.changed !== 'boolean'
                        || !Number.isInteger(outcome?.removedAttachmentId)
                    ) throw new Error('invalid_remove_response');
                    const removedId = outcome.removedAttachmentId;
                    let matched = false;
                    current = normalizeResults({
                        ...current,
                        groups: current.groups.map((group) => {
                            if (group.key !== payload?.groupKey) return group;
                            const attachments = group.attachments.filter((attachment) => attachment.attachmentId !== removedId);
                            if (attachments.length === group.attachments.length) return group;
							matched = true;
							const removedAppliedAttachment = group.appliedAttachmentId === removedId;
							const removedAppliedGroupAttachment = group.appliedAction === 'add_all_to_gallery'
								|| (
									group.appliedAction === 'add_selected_to_gallery'
									&& group.appliedAttachmentIds.includes(removedId)
								);
							const applicationInvalidated = removedAppliedAttachment || removedAppliedGroupAttachment;
							return {
								...group,
								attachments,
								availableActions: attachments.length && applicationInvalidated ? group.unappliedActions : group.availableActions,
								appliedAction: attachments.length && !applicationInvalidated ? group.appliedAction : '',
								appliedAttachmentId: attachments.length && !applicationInvalidated ? group.appliedAttachmentId : 0,
								appliedAttachmentIds: attachments.length && !applicationInvalidated ? group.appliedAttachmentIds : [],
                                status: attachments.length ? group.status : 'removed',
                                savedOutputCount: attachments.length,
                            };
                        }),
                        resultKey: `${current.resultKey}:removed:${removedId}`,
                    });
                    if (!matched) throw new Error('missing_remove_group');
                    selectedKeys.delete(payload.groupKey);
				}
				if (APPLICATION_ACTIONS.has(name)) {
					commitApplicationOutcome(name, outcome, payload);
				}
                if (navigation || outcome?.navigated === true) {
                    navigated = true;
                    restoreFocusKey = '';
                    activeGroupKey = '';
                } else {
                    const completedGroup = APPLICATION_ACTIONS.has(name)
                        ? current.groups.find((group) => group.key === payload?.groupKey)
                        : null;
                    const completedLabel = completedGroup
                        ? destinationActionLabel(name, completedGroup)
                        : (ACTION_LABELS[name] || __( 'Result action', 'fotogenic-ai' ));
                    announce(sprintf( __( '%s completed.', 'fotogenic-ai' ), completedLabel ));
                }
            } catch (_) {
                actionError = __( 'The saved attachment is unchanged, but the optional result action could not be completed.', 'fotogenic-ai' );
                announce(actionError);
            } finally {
                pending = '';
                if (!destroyed && !navigated) renderCurrent();
            }
        };

		const actionPayload = (group, attachment = null, attachmentIds = null) => ({
			groupKey: group.key,
			attachmentId: attachment?.attachmentId || 0,
			attachmentIds: Array.isArray(attachmentIds)
				? attachmentIds
				: (attachment ? [attachment.attachmentId] : group.attachments.map((item) => item.attachmentId)),
		});
		const actionErrorElement = () => {
			const error = vm.element('p', 'fotogenic-ai-studio-validation', actionError);
			error.setAttribute('role', 'alert');
			return error;
		};
		const pendingActionLabel = (action) => ({
			apply_featured: __( 'Setting…', 'fotogenic-ai' ),
			apply_gallery: __( 'Adding…', 'fotogenic-ai' ),
			apply_both: __( 'Applying…', 'fotogenic-ai' ),
			add_selected_to_gallery: __( 'Adding…', 'fotogenic-ai' ),
			add_all_to_gallery: __( 'Adding…', 'fotogenic-ai' ),
			keep_saved: __( 'Adding…', 'fotogenic-ai' ),
			delete_attachment: __( 'Deleting…', 'fotogenic-ai' ),
		}[action] || __( 'Working…', 'fotogenic-ai' ));
		const decoratePendingAction = (control, action, label) => {
			if (pending !== action) return control;
			const spinner = icons.create('arrows-clockwise', { size: 15 });
			spinner.classList.add('fotogenic-ai-icon--spin');
			control.replaceChildren(spinner, vm.element('span', '', label));
			control.classList.add(style('is-pending'));
			return control;
		};

		const actionButton = (action, group, attachment = null, className = '', beforeInvoke = null) => {
			const label = destinationActionLabel(action, group);
			const control = resultButton(label, className);
			decoratePendingAction(control, action, pendingActionLabel(action));
			const selectedAttachmentIds = action === 'add_selected_to_gallery'
				? [...selectedCampaignOutputIds(group)]
				: null;
			control.disabled = Boolean(pending) || (Array.isArray(selectedAttachmentIds) && !selectedAttachmentIds.length);
            control.setAttribute('aria-busy', pending === action ? 'true' : 'false');
            control.setAttribute('data-fa-focus-key', `results:${action}:${encodeURIComponent(group.key)}:${attachment?.attachmentId || 'group'}`);
            control.addEventListener('click', () => {
                const returnFocus = beforeInvoke?.() || control;
                void invoke(
                    action,
                    action === 'keep_saved' ? async () => ({ changed: false }) : handlers[action],
				actionPayload(group, attachment, selectedAttachmentIds),
                    { confirmation: actionConfirmation(action, group, attachment), returnFocus }
                );
            });
            return control;
        };

        const openLightbox = (images, activeIndex, title, trigger) => {
            closeLightbox();
            const available = (Array.isArray(images) ? images : []).filter(Boolean);
            if (!available.length) return;
			const MediaModal = window.wp?.media?.view?.Modal;
			const BackboneView = window.wp?.Backbone?.View;
			if (typeof MediaModal !== 'function' || typeof BackboneView !== 'function') {
                if (typeof handlers.zoom === 'function') void invoke('zoom', handlers.zoom, available[activeIndex] || available[0]);
                return;
            }
            let index = Math.min(Math.max(0, activeIndex), available.length - 1);
			const view = new BackboneView({
				tagName: 'div',
				className: style('wp-image-viewer'),
			});
			const modalTitle = vm.element('h1', 'screen-reader-text', title);
			modalTitle.id = 'media-frame-title';
			const position = vm.element('p', style('wp-image-viewer-position'));
            position.setAttribute('aria-live', 'polite');
			const stage = vm.element('div', style('wp-image-viewer-stage'));
            const image = vm.element('img');
			image.decoding = 'async';
            const previous = resultButton(__( 'Previous image', 'fotogenic-ai' ));
			previous.className = style('wp-image-viewer-previous');
            previous.setAttribute('aria-label', __( 'Previous image', 'fotogenic-ai' ));
			previous.replaceChildren(icons.create('arrow-left', { size: 20 }));
            const next = resultButton(__( 'Next image', 'fotogenic-ai' ));
			next.className = style('wp-image-viewer-next');
            next.setAttribute('aria-label', __( 'Next image', 'fotogenic-ai' ));
			next.replaceChildren(icons.create('arrow-right', { size: 20 }));
			const thumbnails = vm.element('div', style('wp-image-viewer-thumbnails'));
            thumbnails.setAttribute('aria-label', __( 'Image thumbnails', 'fotogenic-ai' ));
            const update = (nextIndex) => {
                index = (nextIndex + available.length) % available.length;
                const active = available[index];
                image.src = active.fullUrl;
                image.alt = active.alt;
				position.textContent = sprintf( __( '%1$d of %2$d: %3$s', 'fotogenic-ai' ), index + 1, available.length, active.label );
                previous.disabled = available.length < 2;
                next.disabled = available.length < 2;
                [...thumbnails.children].forEach((button, buttonIndex) => {
                    if (buttonIndex === index) {
						button.className = style('wp-image-viewer-thumbnail', 'is-active');
                        button.setAttribute('aria-current', 'true');
                    } else {
						button.className = style('wp-image-viewer-thumbnail');
                        button.removeAttribute('aria-current');
                    }
                });
            };
            available.forEach((attachment, attachmentIndex) => {
				const thumbnailLabel = sprintf( __( 'View image %d', 'fotogenic-ai' ), attachmentIndex + 1 );
				const button = resultButton(
					thumbnailLabel,
					style('wp-image-viewer-thumbnail')
				);
                button.setAttribute('aria-label', thumbnailLabel);
                const thumbnail = vm.element('img');
                thumbnail.src = attachment.thumbUrl;
                thumbnail.alt = '';
                button.replaceChildren(thumbnail, vm.element('span', '', String(attachmentIndex + 1)));
                button.addEventListener('click', () => update(attachmentIndex));
                thumbnails.appendChild(button);
            });
            previous.addEventListener('click', () => update(index - 1));
            next.addEventListener('click', () => update(index + 1));
			const handleModalNavigationKeydown = (event) => {
				if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || available.length < 2) return;
				if (event.key === 'ArrowLeft') {
                    event.preventDefault();
                    update(index - 1);
                } else if (event.key === 'ArrowRight' && available.length > 1) {
                    event.preventDefault();
                    update(index + 1);
                }
			};
            if (available.length > 1) stage.append(previous, image, next);
            else stage.appendChild(image);
			view.el.append(modalTitle, position, stage);
			if (available.length > 1) view.el.appendChild(thumbnails);
			const modal = new MediaModal({
				title,
				hasCloseButton: true,
				propagate: false,
			});
			modal.content(view);
			modal.once('close', () => {
				if (lightboxModal === modal) lightboxModal = null;
				modal.el?.removeEventListener?.('keydown', handleModalNavigationKeydown);
				window.setTimeout(() => {
					modal.detach?.();
					modal.remove?.();
					view.remove?.();
					if (trigger?.isConnected && document.activeElement === document.body) {
						trigger.focus?.({ preventScroll: true });
					}
				}, 0);
			});
			lightboxModal = modal;
			modal.open();
			modal.el?.addEventListener?.('keydown', handleModalNavigationKeydown);
            update(index);
        };

		const resultViews = (group) => {
			const views = [];
            if (current.workflow === 'increase_resolution' && group.attachments.length && group.source) {
                views.push({ id: 'comparison', label: __( 'Compare', 'fotogenic-ai' ) });
            }
            if (group.attachments.length) {
                views.push({
                    id: 'generated',
                    label: current.workflow === 'increase_resolution' ? __( 'Enhanced', 'fotogenic-ai' ) : __( 'Generated', 'fotogenic-ai' ),
                });
            }
			return views;
		};
		const renderEmbeddedHeadingActions = (compact = false) => {
			const actions = vm.element('div', style('result-embedded-heading-actions'));
			const createLabel = current.workflow === 'increase_resolution' ? __( 'Enhance another image', 'fotogenic-ai' ) : __( 'Create another', 'fotogenic-ai' );
			[
				['createAnother', compact ? __( 'Enhance another', 'fotogenic-ai' ) : createLabel, createLabel],
				['openHistory', compact ? __( 'History', 'fotogenic-ai' ) : __( 'Run history', 'fotogenic-ai' ), __( 'Run history', 'fotogenic-ai' )],
			].forEach(([action, label, accessibleLabel]) => {
				if (typeof handlers[action] !== 'function') return;
				const control = resultButton(label, style('secondary'));
				control.setAttribute('aria-label', accessibleLabel);
				if (action === 'openHistory') control.prepend(icons.create('clock', { size: 15 }));
				control.disabled = Boolean(pending);
				control.setAttribute('data-fa-focus-key', `results:${action}`);
				control.addEventListener('click', () => void invoke(action, handlers[action], current, { navigation: true }));
				actions.appendChild(control);
			});
			return actions;
		};

        const renderInspector = (group, { embedded = false, position = 1, total = 1 } = {}) => {
			const views = resultViews(group);
			const hasViewSwitcher = views.length > 1;
			const campaignChoiceAvailable = group.availableActions.includes('add_selected_to_gallery');
			let activeView = views[0]?.id || 'generated';
            let activeImageIndex = 0;
            const immersiveSingle = isImmersiveSingleResult(current, group);
            const enhancement = current.workflow === 'increase_resolution' && group.attachments.length > 0;
            const panel = vm.element(
                'article',
                style('result-inspector', ...(embedded ? ['is-embedded'] : []), ...(immersiveSingle ? ['is-immersive-single'] : []), ...(enhancement ? ['is-enhancement'] : []))
            );
            panel.tabIndex = -1;
            const heading = vm.element('h2', '', group.label);
            const headingId = `fotogenic-ai-result-heading-${encodeURIComponent(group.key)}`;
            heading.id = headingId;
            heading.tabIndex = -1;
            heading.setAttribute('data-fa-overlay-heading', '');
            panel.setAttribute('aria-labelledby', headingId);

            const header = vm.element('header', style('result-inspector-heading'));
            const headerCopy = vm.element('div', style('result-inspector-heading-copy'));
            const targetLabel = enhancement && group.targetIdentity?.label === group.label ? '' : group.targetIdentity?.label;
            const targetCopy = targetLabel && group.targetIdentity?.sku
                ? sprintf( __( '%1$s · %2$s', 'fotogenic-ai' ), targetLabel, group.targetIdentity.sku )
                : (targetLabel
                    || (group.targetIdentity?.sku ? sprintf( __( 'SKU %s', 'fotogenic-ai' ), group.targetIdentity.sku ) : ''))
                || (enhancement ? '' : sprintf( _n( '%d saved attachment', '%d saved attachments', group.attachments.length, 'fotogenic-ai' ), group.attachments.length ));
            const headingMeta = vm.element('p');
            if (targetCopy) headingMeta.append(vm.element('span', '', targetCopy), vm.element('span', '', '·'));
            headingMeta.append(
                vm.element('strong', '', embedded
                    ? sprintf( _n( '%d generated image', '%d generated images', group.attachments.length, 'fotogenic-ai' ), group.attachments.length )
                    : sprintf( __( '%1$d of %2$d', 'fotogenic-ai' ), position, total ))
            );
			headerCopy.append(heading, headingMeta);
			if (embedded) {
				const leading = vm.element('div', style('result-embedded-heading-leading'));
				if (typeof handlers.back === 'function') {
					const back = resultButton(__( 'Back', 'fotogenic-ai' ), style('secondary', 'results-back-button'));
					back.prepend(icons.create('arrow-left', { size: 15 }));
					back.disabled = Boolean(pending);
					back.setAttribute('data-fa-focus-key', 'results:back');
					back.addEventListener('click', () => void invoke('back', handlers.back, current, { navigation: true }));
					leading.appendChild(back);
				}
				leading.appendChild(headerCopy);
				header.appendChild(leading);
				const embeddedActions = renderEmbeddedHeadingActions(enhancement);
				if (embeddedActions.childElementCount) header.appendChild(embeddedActions);
			} else {
				header.appendChild(headerCopy);
				const previous = resultButton(__( 'Previous result', 'fotogenic-ai' ), style('result-inspector-heading-previous'));
                header.prepend(previous);
                const navigation = vm.element('div', style('result-inspector-heading-actions'));
                const next = resultButton(__( 'Next result', 'fotogenic-ai' ));
                const close = resultButton(__( 'Close result details', 'fotogenic-ai' ));
                previous.setAttribute('aria-label', __( 'Previous result', 'fotogenic-ai' ));
                next.setAttribute('aria-label', __( 'Next result', 'fotogenic-ai' ));
                close.setAttribute('aria-label', __( 'Close result details', 'fotogenic-ai' ));
                previous.disabled = position <= 1;
                next.disabled = position >= total;
                previous.addEventListener('click', () => openAdjacent(-1));
                next.addEventListener('click', () => openAdjacent(1));
                close.addEventListener('click', requestInspectorClose);
                previous.replaceChildren(icons.create('arrow-left', { size: 18 }));
                next.replaceChildren(icons.create('arrow-right', { size: 18 }));
                close.replaceChildren(icons.create('x', { size: 19 }));
                navigation.append(next, vm.element('span'), close);
                header.appendChild(navigation);
            }

            const scroll = vm.element('div', style('result-inspector-scroll'));
            const body = vm.element('div', style('result-inspector-content'));
            const media = vm.element('section', style('result-media-pane'));
            media.setAttribute('aria-label', __( 'Result images', 'fotogenic-ai' ));
            const tabs = vm.element('div', style('result-tabs'));
            const enhancementStatus = enhancement ? vm.element('div', style('enhancement-status')) : null;
            const viewport = vm.element('div', 'fotogenic-ai-result-viewport');
			if (hasViewSwitcher) {
				tabs.setAttribute('role', 'tablist');
				tabs.setAttribute('aria-label', __( 'Result views', 'fotogenic-ai' ));
				viewport.setAttribute('role', 'tabpanel');
			} else {
				viewport.setAttribute('role', 'region');
				viewport.setAttribute('aria-label', __( 'Generated image view', 'fotogenic-ai' ));
			}
            const tabNamespace = `fotogenic-ai-result-${encodeURIComponent(group.key).replace(/%/g, '-')}`;
            viewport.id = `${tabNamespace}-panel`;
            const thumbnails = vm.element('div', style('result-thumbnails'));
            thumbnails.setAttribute('aria-label', __( 'Generated outputs', 'fotogenic-ai' ));

			const viewAttachments = () => {
				if (activeView === 'generated') return group.attachments;
				if (activeView === 'comparison') return [group.source, group.attachments[0]].filter(Boolean);
                return [];
            };
			const imageLabel = (attachment, index, total) => {
				if (activeView === 'generated') {
					const noun = current.workflow === 'increase_resolution'
						? __( 'Enhanced image', 'fotogenic-ai' )
						: __( 'Generated image', 'fotogenic-ai' );
					return total > 1
						? sprintf( __( '%1$s %2$d of %3$d', 'fotogenic-ai' ), noun, index + 1, total )
						: noun;
				}
				if (activeView === 'comparison') {
					return index === 0 ? __( 'Original source image', 'fotogenic-ai' ) : __( 'Enhanced image', 'fotogenic-ai' );
				}
				return attachment.label;
			};
			const lightboxAttachments = (attachments) => attachments.map((attachment, index) => {
				const label = imageLabel(attachment, index, attachments.length);
				return { ...attachment, label, alt: label };
			});

            const renderViewport = () => {
                viewport.replaceChildren();
                thumbnails.replaceChildren();
                const attachments = viewAttachments();
                activeImageIndex = Math.min(activeImageIndex, Math.max(0, attachments.length - 1));
                if (activeView === 'comparison' && group.source && group.attachments[0]) {
                    const comparison = vm.element('div', style('enhance-comparison'));
                    comparison.setAttribute('aria-label', __( 'Source and enhanced comparison', 'fotogenic-ai' ));
					[[group.source, __( 'Source: unchanged', 'fotogenic-ai' )], [group.attachments[0], __( 'Enhanced: new attachment', 'fotogenic-ai' )]].forEach(([attachment, label]) => {
                        const figure = vm.element('figure');
                        const image = vm.element('img');
                        image.src = attachment.fullUrl;
						image.alt = '';
                        figure.append(image, vm.element('figcaption', '', label));
                        comparison.appendChild(figure);
                    });
                    const handle = vm.element('span', style('comparison-handle'));
                    handle.setAttribute('aria-hidden', 'true');
                    handle.appendChild(icons.create('arrows-clockwise', { size: 14 }));
                    comparison.appendChild(handle);
                    viewport.appendChild(comparison);
                } else if (attachments.length) {
                    const active = attachments[activeImageIndex];
					const accessibleLabel = imageLabel(active, activeImageIndex, attachments.length);
					const hero = vm.element('div', style('result-hero'));
                    const imageButton = resultButton('', style('result-hero-open'));
					imageButton.setAttribute('aria-label', sprintf( __( 'View %s full screen', 'fotogenic-ai' ), accessibleLabel ));
                    const image = vm.element('img');
                    image.src = active.fullUrl;
					image.alt = accessibleLabel;
                    const expand = vm.element('span');
                    expand.appendChild(icons.create('arrows-out', { size: 16 }));
                    imageButton.append(image, expand);
					imageButton.addEventListener('click', () => openLightbox(lightboxAttachments(attachments), activeImageIndex, group.label, imageButton, panel));
					hero.append(
						imageButton,
						vm.element('span', '', current.workflow === 'increase_resolution'
							? __( 'Enhanced · new attachment', 'fotogenic-ai' )
							: __( 'Generated', 'fotogenic-ai' ))
					);
                    viewport.appendChild(hero);
                } else {
					viewport.appendChild(vm.element('p', style('result-view-note'), __( 'No saved generated attachment is available.', 'fotogenic-ai' )));
                }
				if (attachments.length > 1 || campaignChoiceAvailable) {
					attachments.forEach((attachment, index) => {
						const accessibleLabel = sprintf(
							__( 'View %s', 'fotogenic-ai' ),
							imageLabel(attachment, index, attachments.length)
						);
						const button = resultButton('');
						button.setAttribute('aria-label', accessibleLabel);
                        if (index === activeImageIndex) {
                            button.className = style('is-active');
                            button.setAttribute('aria-current', 'true');
                        }
                        const image = vm.element('img');
                        image.src = attachment.thumbUrl;
                        image.alt = '';
                        button.append(image, vm.element('span', '', String(index + 1)));
                        button.addEventListener('click', () => {
                            activeImageIndex = index;
                            renderViewport();
                            renderDetails();
                        });
						if (!campaignChoiceAvailable) {
							thumbnails.appendChild(button);
							return;
						}
						const selectedIds = selectedCampaignOutputIds(group);
						const choice = vm.element('label', style('campaign-output-choice'));
						choice.setAttribute('data-fa-campaign-output-choice', '');
						const checkbox = document.createElement('input');
						checkbox.type = 'checkbox';
						checkbox.checked = selectedIds.has(attachment.attachmentId);
						checkbox.setAttribute(
							'aria-label',
							sprintf( __( 'Select %s for product gallery', 'fotogenic-ai' ), imageLabel(attachment, index, attachments.length) )
						);
						checkbox.addEventListener('change', () => {
							const selected = selectedCampaignOutputIds(group);
							if (checkbox.checked) selected.add(attachment.attachmentId);
							else selected.delete(attachment.attachmentId);
							renderDetails();
						});
						choice.appendChild(checkbox);
						const thumbnail = vm.element('div', style('result-thumbnail'));
						thumbnail.append(button, choice);
						thumbnails.appendChild(thumbnail);
					});
                }
            };

            if (hasViewSwitcher) views.forEach((view, index) => {
                const button = resultButton(view.label);
                button.id = `${tabNamespace}-tab-${view.id}`;
                button.setAttribute('role', 'tab');
                button.setAttribute('aria-controls', viewport.id);
                button.setAttribute('aria-selected', view.id === activeView ? 'true' : 'false');
                button.tabIndex = view.id === activeView ? 0 : -1;
                button.addEventListener('keydown', (event) => {
                    if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
                    const nextIndex = event.key === 'Home'
                        ? 0
                        : event.key === 'End'
                            ? views.length - 1
                            : (index + (event.key === 'ArrowRight' ? 1 : -1) + views.length) % views.length;
                    event.preventDefault();
                    tabs.children[nextIndex]?.click();
                    tabs.children[nextIndex]?.focus();
                });
                button.addEventListener('click', () => {
                    activeView = view.id;
                    activeImageIndex = 0;
                    [...tabs.children].forEach((tab) => {
                        const selected = tab === button;
                        tab.setAttribute('aria-selected', selected ? 'true' : 'false');
                        tab.tabIndex = selected ? 0 : -1;
                    });
                    viewport.setAttribute('aria-labelledby', button.id);
                    renderViewport();
                    renderDetails();
                });
                tabs.appendChild(button);
            });
            const activeTab = [...tabs.children].find((tab) => tab.getAttribute('aria-selected') === 'true');
            if (activeTab) viewport.setAttribute('aria-labelledby', activeTab.id);
            if (immersiveSingle) {
				if (hasViewSwitcher) media.appendChild(tabs);
				media.appendChild(viewport);
				if (group.attachments.length > 1 || campaignChoiceAvailable) media.appendChild(thumbnails);
            } else {
                if (hasViewSwitcher || enhancement) {
                    const galleryToolbar = vm.element('div', style('result-gallery-toolbar'));
                    if (hasViewSwitcher) galleryToolbar.appendChild(tabs);
                    if (enhancementStatus) galleryToolbar.appendChild(enhancementStatus);
					media.appendChild(galleryToolbar);
				}
				media.appendChild(viewport);
				if (group.attachments.length > 1 || campaignChoiceAvailable) media.appendChild(thumbnails);
            }

            const details = vm.element('aside', style('result-details-pane'));
            const footer = vm.element('footer', style('result-inspector-footer', ...(immersiveSingle || enhancement ? ['is-inline'] : [])));
            let activeMenu = null;
            let activeMenuTrigger = null;
            let menuCloseTimer = 0;
            const closeMenu = ({ restoreFocus = false, immediate = false } = {}) => {
                if (!activeMenu) return;
                const menu = activeMenu;
                const trigger = activeMenuTrigger;
                window.clearTimeout(menuCloseTimer);
                menu.classList.remove('is-open');
                menu.classList.add('is-closing');
                trigger?.setAttribute('aria-expanded', 'false');
                activeMenu = null;
                activeMenuTrigger = null;
                const finish = () => {
                    menuCloseTimer = 0;
                    menu.classList.remove('is-closing');
                    menu.hidden = true;
                    if (restoreFocus) trigger?.focus?.({ preventScroll: true });
                };
                const delay = immediate || window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ? 0 : 140;
                if (delay) menuCloseTimer = window.setTimeout(finish, delay);
                else finish();
            };
            const toggleMenu = (menu, trigger) => {
                if (activeMenu === menu) {
                    closeMenu({ restoreFocus: true });
                    return;
                }
                closeMenu({ immediate: true });
                window.clearTimeout(menuCloseTimer);
                activeMenu = menu;
                activeMenuTrigger = trigger;
                menu.hidden = false;
                menu.classList.remove('is-closing');
                menu.classList.add('is-open');
                trigger.setAttribute('aria-expanded', 'true');
                window.requestAnimationFrame(() => menu.querySelector('[role="menuitem"]')?.focus?.());
            };
            const wireMenuKeyboard = (menu) => {
                menu.addEventListener('keydown', (event) => {
                    const items = [...menu.querySelectorAll('[role="menuitem"]:not(:disabled)')];
                    const currentIndex = items.indexOf(document.activeElement);
                    const nextIndex = event.key === 'Home'
                        ? 0
                        : event.key === 'End'
                            ? items.length - 1
                            : event.key === 'ArrowDown'
                                ? (currentIndex + 1 + items.length) % items.length
                                : event.key === 'ArrowUp'
                                    ? (currentIndex - 1 + items.length) % items.length
                                    : -1;
                    if (nextIndex >= 0) {
                        event.preventDefault();
                        items[nextIndex]?.focus();
                    }
                    if (event.key === 'Escape') {
                        event.preventDefault();
                        event.stopPropagation();
                        closeMenu({ restoreFocus: true });
                    }
                });
            };
            panel.addEventListener('pointerdown', (event) => {
                if (activeMenu && !activeMenu.contains(event.target) && !activeMenuTrigger?.contains(event.target)) closeMenu();
            });
            panel.addEventListener('keydown', (event) => {
                if (event.key !== 'Escape' || !activeMenu) return;
                event.preventDefault();
                event.stopPropagation();
                closeMenu({ restoreFocus: true });
            });
            const renderDetails = () => {
                closeMenu();
                details.replaceChildren();
                footer.replaceChildren();
				const presentation = groupPresentation(group, current);
                const outcome = vm.element('section', style('inspector-outcome-card', `is-${presentation.tone}`));
				const outcomeStatus = vm.element('div', style('inspector-outcome-status'));
				const resultStatus = vm.element('span', style('result-status', `is-${presentation.tone}`));
                const statusLabel = enhancement && group.status === 'completed' && !group.appliedAction
                    ? __( 'Saved to Media Library', 'fotogenic-ai' )
                    : presentation.label;
				resultStatus.append(statusIcon(group.status), vm.element('span', '', statusLabel));
                outcomeStatus.append(
                    resultStatus,
                    vm.element('p', '', group.appliedAction
						? sprintf( __( 'Applied to the %s.', 'fotogenic-ai' ), appliedDestinationLabel(group.appliedAction, group) )
						: group.message || (group.status === 'completed'
                        ? __( 'Generated attachments are saved and ready for the next destination action.', 'fotogenic-ai' )
                        : group.status === 'removed'
                            ? __( 'The generated attachment was deleted from the Media Library.', 'fotogenic-ai' )
                        : group.status === 'partial'
                            ? __( 'The attachment was saved, but the confirmed destination action was not completed.', 'fotogenic-ai' )
                            : group.status === 'failed'
                                ? __( 'No attachment was created. Regeneration starts a new billable request.', 'fotogenic-ai' )
                                : __( 'Completed attachments remain available. Reopen setup to start a new run for unfinished items.', 'fotogenic-ai' )))
                );
                outcome.appendChild(outcomeStatus);
                if (group.targetIdentity?.targetType === 'variation') {
                    const destination = vm.element('div', style('inspector-outcome-destination'));
                    const destinationCopy = vm.element('div');
					const variationDestinationCopy = group.targetIdentity.sku
						? sprintf(
							__( 'Any product image action targets %1$s (%2$s), never the parent product.', 'fotogenic-ai' ),
							group.targetIdentity.label,
							group.targetIdentity.sku
						)
						: sprintf(
							__( 'Any product image action targets %s, never the parent product.', 'fotogenic-ai' ),
							group.targetIdentity.label
						);
                    destinationCopy.append(
                        vm.element('strong', '', __( 'Variation destination locked', 'fotogenic-ai' )),
						vm.element('p', '', variationDestinationCopy)
                    );
                    destination.append(icons.create('shield-check', { size: 20 }), destinationCopy);
                    outcome.appendChild(destination);
                }
                if (enhancementStatus) {
                    enhancementStatus.replaceChildren(resultStatus);
                    if (group.status === 'completed' && !group.appliedAction && !group.message) outcomeStatus.remove();
                }
                if (outcome.childElementCount) details.appendChild(outcome);
                if (actionError) details.appendChild(actionErrorElement());

				const activeGeneratedAttachment = group.attachments[activeImageIndex] || group.attachments[0] || null;
				const activeViewAttachments = viewAttachments();
				const activeDetailAttachment = activeView === 'comparison'
					? activeGeneratedAttachment
					: (activeViewAttachments[activeImageIndex] || activeViewAttachments[0] || null);
				const resultActionView = ['generated', 'comparison'].includes(activeView);
				const actionableResultAttachment = resultActionView ? activeGeneratedAttachment : null;
                let enhancementDelivery = null;
				if (activeDetailAttachment) {
                    const metadata = vm.element('dl', style('inspector-technical-details'));
					[
						...(!enhancement ? [[__( 'Attachment', 'fotogenic-ai' ), `#${activeDetailAttachment.attachmentId}`, false]] : []),
						...(group.quality ? [[__( 'Quality', 'fotogenic-ai' ), group.quality, false]] : []),
						[__( 'Dimensions', 'fotogenic-ai' ), vm.formatDimensions(activeDetailAttachment), false],
						[__( 'File type', 'fotogenic-ai' ), `${vm.formatFileType(activeDetailAttachment.mime)}${!enhancement && activeDetailAttachment.mime ? ` · ${activeDetailAttachment.mime}` : ''}`, false],
						[__( 'File size', 'fotogenic-ai' ), formatByteSize(activeDetailAttachment.bytes, enhancement), false],
						...(enhancement ? [[__( 'Attachment', 'fotogenic-ai' ), `#${activeDetailAttachment.attachmentId}`, false]] : []),
						[__( 'Outputs', 'fotogenic-ai' ), String(group.requestedOutputCount), false],
						...(!enhancement ? [[__( 'Delivery', 'fotogenic-ai' ), deliveryLabel(group, current), true]] : []),
					].forEach(([term, description, fullWidth]) => {
						const row = vm.element('div', fullWidth ? style('is-delivery') : '');
						row.append(vm.element('dt', '', term), vm.element('dd', '', description));
						metadata.appendChild(row);
					});
					details.appendChild(metadata);
                    if (enhancement) {
                        enhancementDelivery = vm.element('dl', style('enhancement-delivery'));
                        enhancementDelivery.append(
                            vm.element('dt', '', __( 'Delivery', 'fotogenic-ai' )),
                            vm.element('dd', '', deliveryLabel(group, current))
                        );
                    }
				}
                if (group.sources.length > 1) {
                    details.appendChild(vm.element(
                        'p',
                        style('result-view-note'),
                        sprintf( _n( '%d exact Campaign source image.', '%d exact Campaign source images.', group.sources.length, 'fotogenic-ai' ), group.sources.length )
                    ));
                }

                const actions = vm.element('div', style('inspector-primary-row'));
				const primaryWrap = vm.element('div', style('inspector-primary-wrap', 'inspector-action-grid'));
				const links = vm.element('nav', style('result-destination-links'));
                links.setAttribute('aria-label', __( 'Result links', 'fotogenic-ai' ));
				const linkLabels = targetLinkLabels(current.sourceType, group.targetIdentity);
				const availableActionChoices = resultActionView
					? group.availableActions.filter((action) => (
						GROUP_ACTIONS.has(action)
						|| (actionableResultAttachment && ATTACHMENT_ACTIONS.has(action))
					) && typeof handlers[action] === 'function')
					: [];
                const actionChoices = resultActionView ? destinationActions(group, availableActionChoices) : [];
                const reopensSetup = ['failed', 'skipped'].includes(group.status)
                    && typeof handlers.createAnother === 'function';
				const reconcilesStatus = group.status === 'uncertain' && typeof handlers.back === 'function';
				const attachmentOpenLabel = current.workflow === 'increase_resolution'
					? __( 'Open enhanced image', 'fotogenic-ai' )
					: __( 'Open image', 'fotogenic-ai' );
				const directAttachmentOpen = !actionChoices.length
					&& actionableResultAttachment
					&& !reopensSetup
					&& !reconcilesStatus;
                if (actionChoices.length) {
					primaryWrap.classList.add(style('inspector-destination-actions'));
					if (actionChoices.includes('add_selected_to_gallery')) {
						primaryWrap.classList.add(style('has-gallery-selection'));
					}
					if (actionChoices.length === 1) {
						primaryWrap.classList.add(style('is-single-destination-action'));
					}
					actionChoices.forEach((action, index) => {
                        const choice = actionButton(
                            action,
                            group,
							ATTACHMENT_ACTIONS.has(action) ? actionableResultAttachment : null,
							style(index === 0 ? 'primary' : 'secondary')
                        );
						if (index === 0) choice.setAttribute('data-fa-focus-key', `results:primary:${encodeURIComponent(group.key)}`);
						primaryWrap.appendChild(choice);
                    });
				} else {
					primaryWrap.classList.add(style('is-single-action'));
					const primary = resultButton(directAttachmentOpen ? attachmentOpenLabel : presentation.action, style('primary'));
					primary.setAttribute('data-fa-focus-key', `results:primary:${encodeURIComponent(group.key)}`);
					primary.disabled = Boolean(pending) || (!actionableResultAttachment && !reopensSetup && !reconcilesStatus);
					primaryWrap.appendChild(primary);
					if (reopensSetup) {
                    primary.addEventListener('click', () => void invoke(
                        'createAnother',
                        handlers.createAnother,
                        current,
                        { navigation: true }
                    ));
					} else if (reconcilesStatus) {
						primary.addEventListener('click', () => void invoke(
							'check_status',
							handlers.back,
							current,
							{ navigation: true }
						));
					} else if (actionableResultAttachment) {
						primary.addEventListener('click', () => window.open(actionableResultAttachment.fullUrl, '_blank', 'noopener'));
					}
                }
				if (linkLabels && group.targetLinks?.editUrl) {
					const editTarget = vm.element('a', style('result-link'), linkLabels.edit);
					editTarget.setAttribute('href', group.targetLinks.editUrl);
					editTarget.setAttribute('target', '_blank');
					editTarget.setAttribute('rel', 'noopener noreferrer');
					editTarget.prepend(icons.create('arrow-square-out', { size: 15 }));
					links.appendChild(editTarget);
				}
				if (linkLabels && group.targetLinks?.viewUrl) {
					const viewTarget = vm.element('a', style('result-link'), linkLabels.view);
					viewTarget.setAttribute('href', group.targetLinks.viewUrl);
					viewTarget.setAttribute('target', '_blank');
					viewTarget.setAttribute('rel', 'noopener noreferrer');
					viewTarget.prepend(icons.create('arrow-square-out', { size: 15 }));
					links.appendChild(viewTarget);
                }
				if (!enhancement && links.childElementCount) details.appendChild(links);
				if (
					group.status !== 'removed'
					&& (actionChoices.length || actionableResultAttachment || reopensSetup || reconcilesStatus)
				) actions.appendChild(primaryWrap);
				if (actionableResultAttachment) {
					if (!directAttachmentOpen) {
						const openAttachment = resultButton(attachmentOpenLabel, style('result-link'));
						openAttachment.prepend(icons.create('arrow-square-out', { size: 15 }));
						openAttachment.addEventListener('click', () => window.open(actionableResultAttachment.fullUrl, '_blank', 'noopener'));
						links.appendChild(openAttachment);
					}
					if (actionableResultAttachment.editUrl) {
						const openMedia = resultButton(__( 'Media Library', 'fotogenic-ai' ), style('result-link'));
						openMedia.prepend(icons.create('arrow-square-out', { size: 15 }));
						openMedia.addEventListener('click', () => window.open(actionableResultAttachment.editUrl, '_blank', 'noopener'));
                        links.appendChild(openMedia);
                    }
					if (actionableResultAttachment.canDelete && typeof handlers.delete_attachment === 'function') {
                        const remove = actionButton(
                            'delete_attachment',
                            group,
							actionableResultAttachment,
                            style('inspector-delete')
                        );
						remove.setAttribute('aria-label', __( 'Delete attachment', 'fotogenic-ai' ));
						remove.setAttribute('title', __( 'Delete attachment', 'fotogenic-ai' ));
						if (pending !== 'delete_attachment') remove.replaceChildren(icons.create('trash', { size: 18 }));
						primaryWrap.appendChild(remove);
                    }
					if (!enhancement && links.childElementCount && !links.parentElement) details.appendChild(links);
                }
                if (enhancementDelivery || (enhancement && links.childElementCount)) {
                    const context = vm.element('div', style('enhancement-footer-context'));
                    if (enhancementDelivery) context.appendChild(enhancementDelivery);
                    if (links.childElementCount) context.appendChild(links);
                    footer.appendChild(context);
                }
                if (actions.childElementCount) {
                    footer.appendChild(actions);
                }
                if ((immersiveSingle || enhancement) && footer.childElementCount) details.appendChild(footer);
            };

            body.append(media, details);
            scroll.appendChild(body);
            panel.append(header, scroll);
            if (!immersiveSingle && !enhancement) panel.appendChild(footer);
            renderViewport();
            renderDetails();
            return panel;
        };

        const filteredGroups = () => current.groups.filter((group) => {
            const haystack = [
                group.label,
                group.targetIdentity?.label,
                group.targetIdentity?.sku,
                ...group.attachments.map((attachment) => `${attachment.label} ${attachment.attachmentId}`),
            ].join(' ').toLowerCase();
            return (!query || haystack.includes(query.toLowerCase())) && (filter === 'all' || groupState(group) === filter);
        });
		const groupCanSelect = (group) => group.attachments.length > 0
			&& group.availableActions.some((action) => typeof handlers[action] === 'function');
		const selectGroups = (groups = [], selected = true) => {
			const keys = new Set(groups.filter(groupCanSelect).map((group) => group.key));
			if (selected) keys.forEach((key) => selectedKeys.add(key));
			else selectedKeys = new Set([...selectedKeys].filter((key) => !keys.has(key)));
		};
		const renderSelectionMenu = (allGroups = [], pageGroups = []) => {
			const eligibleAll = allGroups.filter(groupCanSelect);
			if (!eligibleAll.length) return null;
			const menu = vm.element('details', style('results-selection-menu'));
			const summary = document.createElement('summary');
			summary.append(vm.element('span', '', __( 'Selection', 'fotogenic-ai' )), icons.create('caret-down', { weight: 'bold', size: 13 }));
			const panel = vm.element('div');
			[
				[__( 'Select all results', 'fotogenic-ai' ), () => selectGroups(eligibleAll, true), eligibleAll.every((group) => selectedKeys.has(group.key))],
				[__( 'Select current page', 'fotogenic-ai' ), () => selectGroups(pageGroups, true), pageGroups.filter(groupCanSelect).every((group) => selectedKeys.has(group.key))],
				[__( 'Clear selection', 'fotogenic-ai' ), () => { selectedKeys = new Set(); }, !selectedKeys.size],
			].forEach(([label, callback, disabled]) => {
				const button = resultButton(label);
				button.disabled = Boolean(disabled) || Boolean(pending);
				button.addEventListener('click', () => {
					callback();
					renderCurrent();
				});
				panel.appendChild(button);
			});
			menu.append(summary, panel);
			return menu;
		};

        const openAdjacent = (offset) => {
            const groups = filteredGroups();
            const currentIndex = groups.findIndex((group) => group.key === activeGroupKey);
            const next = groups[currentIndex + offset];
            if (!next) return;
			const position = currentIndex + offset + 1;
			const panel = renderInspector(next, { position, total: groups.length });
			panel.classList.add('contained-side-overlay-panel');
			const heading = panel.querySelector('[data-fa-overlay-heading]');
			activeGroupKey = next.key;
			if (inspectorManager?.replacePanel?.(panel, { initialFocus: heading })) return;
			const currentPanel = inspectorLayer?.querySelector('[role="dialog"]');
			if (!currentPanel) return;
			currentPanel.replaceWith(panel);
			panel.setAttribute('role', 'dialog');
			panel.setAttribute('aria-modal', 'true');
			window.requestAnimationFrame(() => (heading || panel).focus?.({ preventScroll: true }));
        };

        const openInspector = (groupKey, trigger) => {
            const groups = filteredGroups();
            const index = groups.findIndex((group) => group.key === groupKey);
            if (index < 0) return;
            destroyInspector({ preserveKey: true });
            activeGroupKey = groupKey;
            inspectorReturnFocus = trigger || inspectorReturnFocus || document.activeElement;
            const layer = vm.element('div', style('results-inspector-layer'));
            const panel = renderInspector(groups[index], { position: index + 1, total: groups.length });
            panel.classList.add('contained-side-overlay-panel');
            layer.appendChild(panel);
            const workspace = mount.querySelector(`.${style('results-workspace')}`);
            (workspace || mount).appendChild(layer);
            inspectorLayer = layer;
            if (Shared.ui?.containedOverlay?.create) {
                inspectorManager = Shared.ui.containedOverlay.create({
                    layer,
                    panel,
                    onClose: requestInspectorClose,
                    initialFocus: panel.querySelector('[data-fa-overlay-heading]'),
                    returnFocus: inspectorReturnFocus,
                });
                inspectorManager.open({ returnFocus: inspectorReturnFocus });
            } else {
                layer.hidden = false;
                panel.setAttribute('role', 'dialog');
                panel.setAttribute('aria-modal', 'true');
                panel.focus({ preventScroll: true });
            }
        };

        const collectionRow = (group, displayLayout, showSelection = true) => {
            const article = vm.element(displayLayout === 'list' ? 'tr' : 'article');
            const preview = group.source || group.attachments[0] || null;
			const canSelect = groupCanSelect(group);
			const select = showSelection ? document.createElement('input') : null;
			if (select) {
				article.classList.add(style('has-result-selection'));
				select.type = 'checkbox';
				select.checked = selectedKeys.has(group.key);
				select.disabled = !canSelect || Boolean(pending);
				const selectionIdentity = group.targetIdentity?.sku
					? sprintf( __( '%1$s, %2$s, SKU %3$s', 'fotogenic-ai' ), group.label, group.targetIdentity.label, group.targetIdentity.sku )
					: group.label;
				select.setAttribute('aria-label', sprintf( __( 'Select %s', 'fotogenic-ai' ), selectionIdentity ));
				select.addEventListener('change', () => {
					if (select.checked) selectedKeys.add(group.key);
					else selectedKeys.delete(group.key);
					renderCurrent();
				});
			}
            const open = resultButton('');
            if (displayLayout === 'list') open.className = style('result-source-button');
            open.setAttribute('data-fa-focus-key', `results:open:${encodeURIComponent(group.key)}`);
            open.addEventListener('click', () => openInspector(group.key, open));
            const previewImage = preview ? vm.element('img') : null;
            if (preview) {
                previewImage.src = preview.thumbUrl;
                previewImage.alt = '';
            }
            const identity = group.targetIdentity?.sku
				? sprintf( __( '%1$s · %2$s', 'fotogenic-ai' ), group.targetIdentity.label, group.targetIdentity.sku )
				: (group.targetIdentity?.label
                    || sprintf( _n( '%d saved output', '%d saved outputs', group.attachments.length, 'fotogenic-ai' ), group.attachments.length ));
            const presentation = groupPresentation(group);
			const status = vm.element('span', style('result-status', `is-${presentation.tone}`));
            status.append(statusIcon(group.status), vm.element('span', '', presentation.label));
            if (displayLayout === 'list') {
                const sourceCopy = vm.element('span');
                sourceCopy.append(vm.element('strong', '', group.label), vm.element('small', '', identity));
                if (previewImage) open.appendChild(previewImage);
                open.appendChild(sourceCopy);
                const sourceCell = vm.element('td', style('result-source-column'));
                sourceCell.appendChild(open);
                const statusCell = vm.element('td', style('result-status-column'));
                statusCell.appendChild(status);
				if (select) {
					const selectCell = vm.element('td', style('result-check-column'));
					const selectHitbox = vm.element('label', style('result-checkbox-hitbox'));
					selectHitbox.appendChild(select);
					selectCell.appendChild(selectHitbox);
					article.appendChild(selectCell);
				}
				article.append(
					sourceCell,
					vm.element('td', style('result-output-column'), groupOutputLabel(group)),
                    statusCell,
                    (() => {
						const cell = vm.element('td', style('result-action-column'));
						const action = resultButton(presentation.action, style('suggested-action'));
						action.disabled = false;
						action.addEventListener('click', () => openInspector(group.key, action));
						cell.appendChild(action);
						return cell;
					})()
                );
            } else {
                if (previewImage) open.appendChild(previewImage);
                const statusWrap = vm.element('span');
                statusWrap.appendChild(status);
                const contactIdentity = group.targetIdentity?.targetType === 'variation'
                    ? group.targetIdentity.label
					: groupOutputLabel(group);
                open.append(statusWrap, vm.element('strong', '', group.label), vm.element('small', '', contactIdentity));
				article.appendChild(open);
				if (select) {
					const selectLabel = vm.element('label', style('result-checkbox-hitbox'));
					selectLabel.appendChild(select);
					article.appendChild(selectLabel);
				}
            }
            return article;
        };

        const renderCollection = (state) => {
            const controls = vm.element('section', style('results-command-bar'));
            controls.setAttribute('aria-label', __( 'Result filters', 'fotogenic-ai' ));
            const searchLabel = vm.element('label', style('results-search'));
            searchLabel.appendChild(icons.create('magnifying-glass', { size: 18 }));
            searchLabel.appendChild(vm.element('span', 'fotogenic-ai-studio-sr-only', __( 'Search results', 'fotogenic-ai' )));
            const search = document.createElement('input');
            search.value = query;
            search.placeholder = current.sourceType === 'product'
                ? __( 'Search by product, variation, or SKU', 'fotogenic-ai' )
                : sprintf( __( 'Search %s results', 'fotogenic-ai' ), sourceNoun(current.sourceType, 2) );
            search.setAttribute('data-fa-focus-key', 'results:search');
            search.addEventListener('input', () => {
                query = search.value;
                page = 1;
                renderCurrent();
            });
            searchLabel.appendChild(search);
            const statusFilterLabel = vm.element('label', style('results-status-filter'));
            statusFilterLabel.appendChild(vm.element('span', 'fotogenic-ai-studio-sr-only', __( 'Filter results by status', 'fotogenic-ai' )));
            const statusFilter = document.createElement('select');
            statusFilter.setAttribute('aria-label', __( 'Filter results by status', 'fotogenic-ai' ));
            statusFilter.setAttribute('data-fa-focus-key', 'results:filter');
            const statusGroups = [...new Set(current.groups.map(groupState))];
            const filterLabels = { ready: __( 'Ready', 'fotogenic-ai' ), applied: __( 'Applied', 'fotogenic-ai' ), removed: __( 'Removed', 'fotogenic-ai' ), attention: __( 'Attention', 'fotogenic-ai' ), stopped: __( 'Stopped', 'fotogenic-ai' ) };
            [['all', sprintf( __( 'All results · %d', 'fotogenic-ai' ), current.groups.length )], ...statusGroups.map((status) => [
                status,
                sprintf( __( '%1$s · %2$d', 'fotogenic-ai' ), filterLabels[status] || status, current.groups.filter((group) => groupState(group) === status).length ),
            ])].forEach(([value, label]) => {
                const option = document.createElement('option');
                option.value = value;
                option.textContent = label;
                option.selected = filter === value;
                statusFilter.appendChild(option);
            });
            statusFilter.addEventListener('change', () => {
                filter = statusFilter.value;
                page = 1;
                selectedKeys = new Set();
                renderCurrent();
            });
            statusFilterLabel.append(statusFilter, icons.create('caret-down', { weight: 'bold', size: 14 }));
            const layoutGroup = vm.element('div', style('results-layout-toggle'));
            layoutGroup.setAttribute('role', 'group');
            layoutGroup.setAttribute('aria-label', __( 'Results layout', 'fotogenic-ai' ));
            [['list', __( 'List', 'fotogenic-ai' ), 'list'], ['grid', __( 'Contact sheet', 'fotogenic-ai' ), 'squares-four']].forEach(([value, label, iconName]) => {
                const button = resultButton(label);
                button.prepend(icons.create(iconName, { size: 17 }));
                if (layout === value) button.className = style('is-active');
                button.setAttribute('aria-pressed', layout === value ? 'true' : 'false');
                button.addEventListener('click', () => {
                    layout = value;
                    renderCurrent();
                });
                layoutGroup.appendChild(button);
            });
            const filtered = filteredGroups();
			const pagination = paginateResults(filtered, page, pageSize);
			page = pagination.page;
			const hasSelectableResults = pagination.items.some(groupCanSelect);
			const commandActions = vm.element('div', style('results-command-actions'));
			commandActions.appendChild(statusFilterLabel);
			const selectionMenu = renderSelectionMenu(filtered, pagination.items);
			if (selectionMenu) commandActions.appendChild(selectionMenu);
			commandActions.appendChild(layoutGroup);
			if (current.groups.length >= 10) controls.appendChild(searchLabel);
			else controls.classList.add(style('has-no-search'));
			controls.appendChild(commandActions);
            state.appendChild(controls);

            const selected = current.groups.filter((group) => selectedKeys.has(group.key));
            const commonActions = intersectResultActions(selected).filter((action) => typeof handlers[action] === 'function');
            if (selected.length) {
                const bulk = vm.element('section', style('results-bulk-bar'));
                const selection = vm.element('span', '', sprintf( _n( '%d selected', '%d selected', selected.length, 'fotogenic-ai' ), selected.length ));
                selection.prepend(icons.create('check', { weight: 'bold', size: 15 }));
                bulk.appendChild(selection);
                const bulkActions = vm.element('div');
                commonActions.forEach((action) => {
					const button = resultButton(ACTION_LABELS[action]);
					decoratePendingAction(button, action, pendingActionLabel(action));
                    button.disabled = Boolean(pending);
					button.setAttribute('aria-busy', pending === action ? 'true' : 'false');
					button.setAttribute('data-fa-focus-key', `results:batch:${action}`);
                    button.addEventListener('click', () => void invokeApplicationBatch(action, selected, {
                        confirmation: {
                            title: sprintf(
                                _n( '%1$s for %2$d selected result?', '%1$s for %2$d selected results?', selected.length, 'fotogenic-ai' ),
                                ACTION_LABELS[action],
                                selected.length
                            ),
                            description: __( 'Each selected result will use this confirmed destination. Saved attachments remain available if the platform update cannot be completed.', 'fotogenic-ai' ),
                            note: __( 'Every variation remains locked to its exact variation identity.', 'fotogenic-ai' ),
                            confirmLabel: __( 'Apply selected', 'fotogenic-ai' ),
                        },
						returnFocus: button,
					}));
                    bulkActions.appendChild(button);
                });
                const clear = resultButton(__( 'Clear', 'fotogenic-ai' ), style('is-subtle'));
				clear.disabled = Boolean(pending);
                clear.addEventListener('click', () => {
                    selectedKeys = new Set();
                    renderCurrent();
                });
                bulkActions.appendChild(clear);
                bulk.appendChild(bulkActions);
                state.appendChild(bulk);
            }

            const frame = vm.element('section', style('results-list-frame'));
            frame.setAttribute('aria-label', __( 'Generated results', 'fotogenic-ai' ));
            if (layout === 'list') {
                const table = vm.element('table', style('results-command-table'));
                const head = document.createElement('thead');
                const row = document.createElement('tr');
				if (hasSelectableResults) {
					const selectHeading = vm.element('th', style('result-check-column'));
					const eligiblePage = pagination.items.filter(groupCanSelect);
					const selectedPage = eligiblePage.filter((group) => selectedKeys.has(group.key));
					const selectPage = document.createElement('input');
					selectPage.type = 'checkbox';
					selectPage.checked = Boolean(eligiblePage.length && selectedPage.length === eligiblePage.length);
					selectPage.indeterminate = selectedPage.length > 0 && selectedPage.length < eligiblePage.length;
					selectPage.disabled = Boolean(pending);
					selectPage.setAttribute('aria-label', __( 'Select current page', 'fotogenic-ai' ));
					selectPage.addEventListener('change', () => {
						selectGroups(eligiblePage, selectPage.checked);
						renderCurrent();
					});
					selectHeading.appendChild(selectPage);
					row.appendChild(selectHeading);
				}
				[
					[style('result-source-column'), current.sourceType === 'product' ? __( 'Product & variation (SKU)', 'fotogenic-ai' ) : sourceNoun(current.sourceType, 1)],
					[style('result-output-column'), __( 'Outputs', 'fotogenic-ai' )],
					[style('result-status-column'), __( 'Status', 'fotogenic-ai' )],
					[style('result-action-column'), __( 'Suggested action', 'fotogenic-ai' )],
				].forEach(([className, label]) => row.appendChild(vm.element('th', className, label)));
                head.appendChild(row);
                const body = document.createElement('tbody');
				pagination.items.forEach((group) => body.appendChild(collectionRow(group, 'list', hasSelectableResults)));
                table.append(head, body);
                frame.appendChild(table);
            } else {
                const sheet = vm.element('div', style('results-contact-sheet'));
				pagination.items.forEach((group) => sheet.appendChild(collectionRow(group, 'contact', hasSelectableResults)));
				frame.appendChild(sheet);
            }
            if (!pagination.items.length) {
                const empty = vm.element('section', style('results-empty'));
                empty.append(icons.create('image-square', { size: 26 }), vm.element('strong', '', __( 'No matching results', 'fotogenic-ai' )), vm.element('p', '', __( 'Clear the search or choose another status.', 'fotogenic-ai' )));
                const clear = resultButton(__( 'Clear filters', 'fotogenic-ai' ));
                clear.addEventListener('click', () => {
                    query = '';
                    filter = 'all';
                    page = 1;
                    renderCurrent();
                });
                empty.appendChild(clear);
                frame.appendChild(empty);
            }
            state.appendChild(frame);

            if (pagination.totalPages <= 1) return;

            const footer = vm.element('footer', style('results-pagination'));
            const sizeLabel = vm.element('label');
            sizeLabel.appendChild(vm.element('span', '', __( 'Rows per page', 'fotogenic-ai' )));
            const sizeSelect = document.createElement('select');
            [10, 25, 50, 100].forEach((size) => {
                const option = document.createElement('option');
                option.value = String(size);
                option.textContent = String(size);
                option.selected = pageSize === size;
                sizeSelect.appendChild(option);
            });
            sizeSelect.addEventListener('change', () => {
                pageSize = Number(sizeSelect.value);
                page = 1;
                renderCurrent();
            });
            sizeLabel.append(sizeSelect, icons.create('caret-down', { weight: 'bold', size: 13 }));
            const range = vm.element('span', '', pagination.totalItems
				? sprintf( __( '%1$d-%2$d of %3$d', 'fotogenic-ai' ), pagination.start, pagination.end, pagination.totalItems )
                : __( '0 results', 'fotogenic-ai' ));
            range.setAttribute('role', 'status');
            range.setAttribute('aria-live', 'polite');
            const pager = vm.element('div');
            const previous = resultButton(__( 'Previous results page', 'fotogenic-ai' ));
            const next = resultButton(__( 'Next results page', 'fotogenic-ai' ));
            previous.replaceChildren(icons.create('arrow-left', { size: 15 }));
            previous.setAttribute('aria-label', __( 'Previous results page', 'fotogenic-ai' ));
            next.replaceChildren(icons.create('arrow-right', { size: 15 }));
            next.setAttribute('aria-label', __( 'Next results page', 'fotogenic-ai' ));
            previous.disabled = pagination.page <= 1;
            next.disabled = pagination.page >= pagination.totalPages;
            previous.addEventListener('click', () => {
                page = Math.max(1, page - 1);
                renderCurrent();
            });
            next.addEventListener('click', () => {
                page = Math.min(pagination.totalPages, page + 1);
                renderCurrent();
            });
            pager.append(previous, vm.element('strong', '', `${pagination.page} / ${pagination.totalPages}`), next);
            footer.append(sizeLabel, range, pager);
            state.appendChild(footer);
        };

        const renderRunNavigation = () => {
            const navigation = vm.element('div', style('results-header-actions'));
            [
                ['checkStatus', __( 'Check status', 'fotogenic-ai' ), style('secondary')],
                ['createAnother', current.workflow === 'increase_resolution' ? __( 'Enhance another image', 'fotogenic-ai' ) : __( 'Create another', 'fotogenic-ai' ), style('secondary', 'create-another-button')],
                ['openHistory', __( 'Run history', 'fotogenic-ai' ), style('secondary', 'history-open-button')],
            ].forEach(([action, label, className]) => {
                if (typeof handlers[action] !== 'function') return;
                const control = resultButton(label, className);
                if (action === 'openHistory') {
                    control.prepend(icons.create('clock', { size: 16 }));
                }
                control.disabled = Boolean(pending);
                control.setAttribute('data-fa-focus-key', `results:${action}`);
                control.addEventListener('click', () => void invoke(action, handlers[action], current, { navigation: true }));
                navigation.appendChild(control);
            });
            return navigation;
        };

        const renderCurrent = () => {
            if (!mount || !current || destroyed) return null;
			const revision = ++renderRevision;
            const active = document.activeElement;
            restoreFocusKey = active && mount.contains?.(active) === true
                ? active.getAttribute?.('data-fa-focus-key') || restoreFocusKey
                : restoreFocusKey;
            const reopenKey = activeGroupKey;
			const inspectorFocusKey = reopenKey ? restoreFocusKey : '';
            destroyInspector({ preserveKey: true });
            const presentation = resultPresentation(current);
            const state = vm.element('main', style('results-workspace'));
            const header = vm.element('header', style('results-command-heading'));
            const heading = vm.element('h1');
            heading.tabIndex = -1;
            const readyCount = current.groups.filter((group) => groupPresentation(group).tone === 'ready' && group.availableActions.length).length;
			const appliedCount = current.groups.filter((group) => Boolean(group.appliedAction)).length;
            const savedCount = current.groups.filter((group) => groupPresentation(group).tone === 'ready' && !group.availableActions.length && !group.appliedAction).length;
			const removedCount = current.groups.filter((group) => group.status === 'removed').length;
			const attentionCount = current.groups.filter((group) => ['partial', 'failed', 'skipped', 'stopped', 'uncertain'].includes(group.status)).length;
            const availableCount = readyCount + savedCount;
            heading.textContent = availableCount
                ? sprintf(__( '%d ready', 'fotogenic-ai' ), availableCount)
                : __( 'Summary', 'fotogenic-ai' );
            const summary = current.status === 'loading' ? __( 'Loading saved results…', 'fotogenic-ai' ) : '';
            const headerCopy = vm.element('div');
			const summaryLine = vm.element('p');
			if (current.partialSnapshot) summaryLine.appendChild(vm.element('span', '', __( 'Loaded snapshot', 'fotogenic-ai' )));
			if (appliedCount) summaryLine.appendChild(vm.element('span', '', sprintf( _n( '%d applied', '%d applied', appliedCount, 'fotogenic-ai' ), appliedCount )));
			if (removedCount) summaryLine.appendChild(vm.element('span', '', sprintf( _n( '%d removed', '%d removed', removedCount, 'fotogenic-ai' ), removedCount )));
			if (attentionCount) summaryLine.appendChild(vm.element('span', '', sprintf( _n( '%d needs attention', '%d need attention', attentionCount, 'fotogenic-ai' ), attentionCount )));
			if (!summaryLine.childElementCount && summary) summaryLine.appendChild(vm.element('span', '', summary));
            headerCopy.appendChild(heading);
            if (summaryLine.childElementCount) headerCopy.appendChild(summaryLine);
			const headingLeading = vm.element('div', style('results-heading-leading'));
			if (typeof handlers.back === 'function') {
				const back = resultButton(__( 'Back', 'fotogenic-ai' ), style('secondary', 'results-back-button'));
				back.disabled = Boolean(pending);
				back.setAttribute('data-fa-focus-key', 'results:back');
				back.addEventListener('click', () => void invoke('back', handlers.back, current, { navigation: true }));
				headingLeading.appendChild(back);
			}
			headingLeading.appendChild(headerCopy);
            const navigation = renderRunNavigation();
			header.appendChild(headingLeading);
            if (navigation.childElementCount) header.appendChild(navigation);
            if (current.groups.length !== 1) state.appendChild(header);
            if (current.partialSnapshot) {
                const snapshot = vm.element('p', style('results-snapshot-note'), sprintf(
                    __( 'Showing %1$d exact loaded result rows from %2$d total. Unloaded rows are not fabricated.', 'fotogenic-ai' ),
                    current.groups.length,
                    current.totalItems
				));
				snapshot.setAttribute('role', 'status');
				state.appendChild(snapshot);
            }
            if (current.status === 'loading') {
				const loading = vm.element('section', style('results-aggregate-state'));
				loading.append(icons.create('clock', { size: 24 }), vm.element('div', '', __( 'Loading result details…', 'fotogenic-ai' )));
                loading.setAttribute('role', 'status');
                state.appendChild(loading);
            } else if (!current.groups.length) {
				const empty = vm.element('section', style('results-aggregate-state'));
				empty.append(icons.create('clock', { size: 24 }), vm.element('div', '', __( 'No exact result rows are available. Check the saved run status before starting anything new.', 'fotogenic-ai' )));
				state.appendChild(empty);
            } else if (current.groups.length === 1) {
                const shell = vm.element('section', style('single-result-shell'));
                shell.setAttribute('aria-label', __( 'Generated result', 'fotogenic-ai' ));
                shell.appendChild(renderInspector(current.groups[0], { embedded: true }));
                state.appendChild(shell);
            } else {
                renderCollection(state);
            }
            if (actionError && current.groups.length !== 1) state.appendChild(actionErrorElement());
            mount.replaceChildren(state);
			const focusHeading = current.groups.length === 1
				? mount.querySelector('[data-fa-overlay-heading]')
				: heading;

            const restoreTarget = [...mount.querySelectorAll('[data-fa-focus-key]')]
                .find((node) => node.getAttribute('data-fa-focus-key') === restoreFocusKey);
            if (restoreTarget?.focus && !restoreTarget.disabled && !restoreTarget.hidden) {
                restoreTarget.focus({ preventScroll: true });
                restoreFocusKey = '';
            } else if (restoreFocusKey && !pending && !reopenKey) {
                restoreFocusKey = '';
				focusHeading?.focus({ preventScroll: true });
            }
            if (reopenKey && current.groups.length > 1 && current.groups.some((group) => group.key === reopenKey)) {
				vm.afterPaint(() => {
					if (revision !== renderRevision || destroyed) return;
					openInspector(reopenKey, null);
					if (inspectorFocusKey) {
						vm.afterPaint(() => {
							if (revision !== renderRevision || pending || restoreFocusKey !== inspectorFocusKey || activeGroupKey !== reopenKey) return;
							const target = [...mount.querySelectorAll('[data-fa-focus-key]')]
								.find((node) => node.getAttribute('data-fa-focus-key') === inspectorFocusKey);
							if (target?.focus && !target.disabled && !target.hidden) {
								target.focus({ preventScroll: true });
								restoreFocusKey = '';
							}
						});
						}
				});
            }
            if (lastResultKey !== current.resultKey) {
                lastResultKey = current.resultKey;
				vm.afterPaint(() => {
					if (revision === renderRevision && !destroyed) focusHeading?.focus({ preventScroll: true });
				});
                announce(`${heading.textContent}. ${summary}`);
            }
            return current;
        };

        const render = (value, nextHandlers = {}) => {
            closeConfirmation(false, { immediate: true });
            actionError = '';
			current = normalizeResults(value);
            handlers = nextHandlers && typeof nextHandlers === 'object' ? nextHandlers : {};
            query = '';
            filter = 'all';
            page = 1;
			selectedKeys = new Set();
			campaignOutputSelections = new Map();
            activeGroupKey = '';
            return renderCurrent();
        };

        return Object.freeze({
            render,
            destroy() {
                destroyed = true;
                closeConfirmation(false, { immediate: true });
                destroyInspector();
                mount?.replaceChildren?.();
                current = null;
                handlers = {};
            },
        });
    };

    Studio.results = Object.freeze({
        createResultsView,
        normalizeResults,
        normalizeActionList,
        allowedActions,
        paginateResults,
        intersectResultActions,
        resultPresentation,
        isImmersiveSingleResult,
    });
})();
