(() => {
    'use strict';

    window.FotogenicAI = window.FotogenicAI || {};
    const Studio = window.FotogenicAI.Studio = window.FotogenicAI.Studio || {};
    const { __ } = Studio.i18n;

    const start = () => {
        const root = document.querySelector('[data-fa-studio-root]');
        if (!root || Studio.app) {
            return;
        }
        const errorRoot = document.getElementById('fotogenic-ai-error-overlay-root');
        const createErrorSystem = window.FotogenicAI?.Shared?.core?.error?.createErrorSystem;
        const handleAuthExpired = () => {
            window.dispatchEvent(new CustomEvent('fotogenic-ai:auth-changed', {
                detail: { auth: { connected: false, balance: null, expired: true } },
            }));
        };
        const handleErrorExit = () => {
            window.dispatchEvent(new CustomEvent('fotogenic-ai:open-select'));
        };
        const feedbackContext = {
            i18n: { __ },
            restUrl: Studio.boot?.restUrl || '',
            restNonce: Studio.boot?.nonce || '',
            state: { currentStepKey: root.dataset.faCurrentView || 'select' },
            handleAuthExpired,
            handleErrorExit,
            errorExitLabel: __( 'Exit to Select', 'fotogenic-ai' ),
        };
        Studio.feedbackContext = feedbackContext;
        if (errorRoot && typeof createErrorSystem === 'function') {
            Studio.errors = createErrorSystem(feedbackContext);
        }
        const createNotifySystem = window.FotogenicAI?.Shared?.ui?.notifications?.createNotifySystem;
        if (typeof createNotifySystem === 'function') {
            Studio.notify = createNotifySystem({
                i18n: { __ },
                restUrl: feedbackContext.restUrl,
                restNonce: feedbackContext.restNonce,
            });
        }
        const createRestFetch = window.FotogenicAI?.Shared?.api?.restFetch?.createRestFetch;
        const notificationFetch = typeof createRestFetch === 'function'
            ? createRestFetch(feedbackContext.restUrl, feedbackContext.restNonce, { onAuthExpired: handleAuthExpired })
            : null;
        const createNotificationCenter = window.FotogenicAI?.Shared?.ui?.notifications?.notificationCenter?.create;
        if (typeof createNotificationCenter === 'function') {
            Studio.notificationCenter = createNotificationCenter({
                root,
                restFetch: notificationFetch,
                i18n: { __ },
                notify: Studio.notify,
                onHistory: () => window.dispatchEvent(new CustomEvent('fotogenic-ai:open-history')),
                onRun: (runId) => window.dispatchEvent(new CustomEvent('fotogenic-ai:open-history-run', { detail: { runId } })),
            });
        }
        const initializeExperienceController = () => {
            const createController = window.FotogenicAI?.Shared?.ui?.experienceDialog?.createExperienceController;
            const experienceRest = Studio.boot?.rest && typeof Studio.boot.rest === 'object'
                ? Studio.boot.rest
                : {};
            const claimEndpoint = String(experienceRest.experienceClaim || '').trim();
            const dismissEndpoint = String(experienceRest.experienceDismiss || '').trim();
            if (
                typeof createController !== 'function'
                || typeof notificationFetch !== 'function'
                || !claimEndpoint
                || !dismissEndpoint
            ) {
                return null;
            }

            const followAction = (action) => {
                const actionId = String(action?.action || '').trim();
				if (actionId === 'open_studio') return true;
				if (actionId === 'connect') {
					const reportAuthenticationFailure = (error, status) => {
						Studio.errors?.normalizeAndReport?.(
							error,
							{ source: 'network', endpoint: '/auth/start', method: 'POST', status },
							{
								onRetry: beginAuthentication,
								onExit: () => {},
								retryLabel: __( 'Try again', 'fotogenic-ai' ),
								exitLabel: __( 'Close', 'fotogenic-ai' ),
							}
						);
						return false;
					};
					const beginAuthentication = () => notificationFetch('/auth/start', {
						method: 'POST',
						body: { source: 'studio' },
					}).then((result) => {
						const authorizationUrl = String(result?.data?.authorizationUrl || '').trim();
						if (!result?.ok || !authorizationUrl) {
							return reportAuthenticationFailure(result, result?.status);
						}
						try {
							const destination = new URL(authorizationUrl, window.location.href);
							if (!['https:', 'http:'].includes(destination.protocol)) throw new Error('Unsupported authorization URL protocol.');
							window.location.assign(destination.href);
							return true;
						} catch (error) {
							return reportAuthenticationFailure(error);
						}
					}).catch((error) => reportAuthenticationFailure(error));
					return beginAuthentication();
				}
                const url = String(action?.url || '').trim();
				if (!url) return false;
                if (action?.newTab) {
                    const link = document.createElement('a');
                    link.href = url;
                    link.target = '_blank';
                    link.rel = 'noopener noreferrer';
                    link.hidden = true;
                    document.body.appendChild(link);
                    link.click();
                    link.remove();
					return true;
                }
                window.setTimeout(() => window.location.assign(url), 120);
				return true;
            };
            const controller = createController({
                presentation: 'studio',
                containmentRoot: root,
                imageUrls: Studio.boot?.experienceImages,
                restoreFocusTo: () => (
                    root.querySelector('[data-fa-view]:not([hidden]) h2[tabindex="-1"]') || root
                ),
                claim: (payload) => notificationFetch(claimEndpoint, { method: 'POST', body: payload }),
                dismiss: (payload) => notificationFetch(dismissEndpoint, { method: 'POST', body: payload }),
                notify: Studio.notify,
                onAction: followAction,
                onError: ({ operation }) => {
                    Studio.notify?.warning?.(operation === 'dismiss'
                        ? __( 'The notice was closed, but its state could not be saved.', 'fotogenic-ai' )
                        : __( 'Account notices could not be loaded.', 'fotogenic-ai' ));
                },
            });
            const onCreditsUpdated = () => controller.claimNext();
            const onAuthChanged = () => controller.claimNext({ force: true });
            window.addEventListener('fotogenic-ai:credits-updated', onCreditsUpdated);
            window.addEventListener('fotogenic-ai:auth-changed', onAuthChanged);

            return Object.freeze({
                claimNext: controller.claimNext,
                destroy() {
                    window.removeEventListener('fotogenic-ai:credits-updated', onCreditsUpdated);
                    window.removeEventListener('fotogenic-ai:auth-changed', onAuthChanged);
                    controller.destroy();
                },
            });
        };
		Studio.experienceController = initializeExperienceController();
		const revealPage = () => {
			const page = root.closest('[data-fa-studio-page][data-fa-ui-state="pending"]');
			if (!page) return;
			page.dataset.faUiState = 'ready';
			page.removeAttribute('aria-busy');
		};
		if (typeof Studio.createApp !== 'function') {
            const shell = typeof Studio.shell?.createShell === 'function'
                ? Studio.shell.createShell({ root })
                : null;
			shell?.showBlocking?.(__( 'The Studio runtime is unavailable.', 'fotogenic-ai' ));
			revealPage();
			return;
        }
        const pending = Promise.resolve(Studio.createApp({
			root,
			boot: Studio.boot || {},
			onAuthExpired: handleAuthExpired,
		})).then((app) => {
			revealPage();
            void Studio.experienceController?.claimNext?.();
            return app;
        }).catch((error) => {
            Studio.errors?.normalizeAndReport?.(
                error,
                { source: 'global' },
                {
                    onRetry: () => window.location.reload(),
                    retryLabel: __( 'Reload', 'fotogenic-ai' ),
                    exitLabel: __( 'Close', 'fotogenic-ai' ),
                }
            );
			const shell = typeof Studio.shell?.createShell === 'function'
                ? Studio.shell.createShell({ root })
                : null;
			shell?.showBlocking?.(__( 'The Studio interface could not be initialized. Refresh the page and try again.', 'fotogenic-ai' ));
			revealPage();
            return Object.freeze({
                blocked: true,
                reason: __( 'Studio initialization failed.', 'fotogenic-ai' ),
                destroy() {},
            });
        });
        const loadingApp = Object.freeze({
            pending: true,
            ready: pending.then((app) => {
                Studio.app = app;
                return app;
            }),
        });
        Studio.app = loadingApp;
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', start, { once: true });
    } else {
        start();
    }
})();
