import styles from './feedback-dialog.module.css'; import { buildSafeErrorReport } from './error-core'; type UnknownRecord = Record; type Tone = 'neutral' | 'success' | 'warning' | 'danger'; type AuthState = 'login_starting' | 'login_cancelled' | 'login_failed' | 'login_success' | 'logout_pending' | 'logout_failed'; interface IconApi { create: (name: string, options?: { weight?: string; size?: number }) => HTMLElement; } interface OverlayManager { open: (options?: { returnFocus?: HTMLElement | null; initialFocus?: HTMLElement | null }) => boolean; close: (options?: { restoreFocus?: boolean; immediate?: boolean }) => boolean; destroy: () => void; } interface OverlayApi { create: (options: { layer: HTMLElement; panel: HTMLElement; onClose?: () => void; onClosed?: (manager: OverlayManager) => void; closeOnBackdrop?: boolean; closeOnEscape?: boolean; initialFocus?: HTMLElement | null; returnFocus?: HTMLElement | null; decorate?: boolean; }) => OverlayManager; } interface FeedbackAction { label: string; action: string; url: string; newTab: boolean; } interface ExperiencePayload { id: string; kind: 'welcome_disconnected' | 'welcome_connected' | 'zero' | 'low'; priority: number; balance: number | null; grantedCredits: number | null; hasPlan: boolean; imageUrl: string; productImageUrl: string; logoUrl: string; primary: FeedbackAction | null; secondary: FeedbackAction | null; } interface DialogAction extends FeedbackAction { disabled?: boolean; pendingLabel?: string; } interface DialogFooterNote { text: string; icon: string; } interface DialogConfig { compact?: boolean; footerNote?: DialogFooterNote; promotion?: { imageUrl: string; productImageUrl?: string; logoUrl: string; imageFocus?: 'upper' | 'center' | 'lower'; qualification?: string; balance?: string; footer: string }; tone?: Tone; icon: string; iconWeight?: string; eyebrow?: string; title: string; description: string; benefits?: string[]; content?: HTMLElement | HTMLElement[]; primary?: DialogAction | null; secondary?: DialogAction | null; dismissible?: boolean; closeOnEscape?: boolean; busy?: boolean; role?: 'dialog' | 'alertdialog'; initialFocus?: 'primary' | 'secondary' | 'dismiss' | 'dialog'; returnFocus?: HTMLElement | null; mount?: HTMLElement | null; contained?: boolean; backdropTarget?: HTMLElement | null; immediateClose?: boolean; onAction?: (action: DialogAction) => unknown | Promise; onError?: (error: unknown) => void; actionErrorMessage?: string; onClose?: (outcome: string, action: DialogAction | null) => void; } const globalWindow = window as typeof window & { FotogenicAI?: { Shared?: { ui?: { icon?: IconApi; containedOverlay?: OverlayApi; experienceDialog?: UnknownRecord; feedbackDialog?: { create: () => FeedbackDialog }; }; }; }; wp?: { i18n?: { __?: (text: string, domain: string) => string } }; }; const shared = globalWindow.FotogenicAI?.Shared; const icons = shared?.ui?.icon; const overlays = shared?.ui?.containedOverlay; if (!icons?.create) throw new Error('Fotogenic AI: the direct feedback component requires the icon owner.'); if (!overlays?.create) throw new Error('Fotogenic AI: the direct feedback component requires the contained-overlay owner.'); const iconApi: IconApi = icons; const overlayApi: OverlayApi = overlays; const translate = (text: string): string => globalWindow.wp?.i18n?.__?.(text, 'fotogenic-ai') ?? text; const css = (name: string): string => { const value = styles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} feedback style.`); return value; }; const record = (value: unknown): UnknownRecord => ( value && typeof value === 'object' && !Array.isArray(value) ? value as UnknownRecord : {} ); const text = (value: unknown): string => String(value ?? '').trim(); const finite = (value: unknown): number | null => { if (value === null || value === undefined || value === '') return null; const number = Number(value); return Number.isFinite(number) ? number : null; }; const actionFailed = (value: unknown): boolean => ( value === false || record(value).ok === false || record(record(value).result).ok === false ); const numberLabel = (value: number): string => new Intl.NumberFormat().format(value); const safeUrl = (value: unknown): string => { const raw = text(value); if (!raw) return ''; const url = document.createElement('a'); url.href = raw; return ['http:', 'https:'].includes(url.protocol) ? url.href : ''; }; const resolveElement = (value: unknown): HTMLElement | null => { if (value instanceof HTMLElement) return value; if (typeof value !== 'function') return null; const result = value(); return result instanceof HTMLElement ? result : null; }; let dialogSequence = 0; class FeedbackDialog { private root: HTMLElement | null = null; private overlay: OverlayManager | null = null; private actionPending = false; private footerNote: DialogFooterNote | null = null; private backdropTarget: HTMLElement | null = null; show(config: DialogConfig): void { this.close(false); dialogSequence += 1; const titleId = `fotogenic-ai-feedback-title-${dialogSequence}`; const descriptionId = `fotogenic-ai-feedback-description-${dialogSequence}`; const root = document.createElement('div'); root.className = [ css('feedback-dialog-layer'), ...(config.promotion ? [css('is-promotion-layer')] : []), ...(config.contained ? [css('is-contained')] : []), ...(config.backdropTarget ? [css('is-scoped-backdrop')] : []), ].join(' '); const panel = document.createElement('section'); panel.className = [ css('feedback-dialog'), ...(config.compact ? [css('is-compact')] : []), ...(config.promotion ? [css('is-promotion')] : []), ...(config.tone && config.tone !== 'neutral' ? [css(`is-${config.tone}`)] : []), ].join(' '); panel.setAttribute('role', config.role ?? 'dialog'); panel.setAttribute('aria-modal', 'true'); panel.setAttribute('aria-labelledby', titleId); panel.setAttribute('aria-describedby', descriptionId); panel.tabIndex = -1; if (config.busy) panel.setAttribute('aria-busy', 'true'); let dismissButton: HTMLButtonElement | null = null; if (config.dismissible) { dismissButton = document.createElement('button'); dismissButton.className = css('feedback-dialog-close'); dismissButton.type = 'button'; dismissButton.setAttribute('aria-label', translate('Close')); dismissButton.appendChild(iconApi.create('x', { weight: 'regular', size: 18 })); dismissButton.addEventListener('click', () => this.finish(config, 'dismissed', null)); panel.appendChild(dismissButton); } const icon = document.createElement('div'); icon.className = css('feedback-dialog-icon'); const glyph = iconApi.create(config.icon, { weight: config.iconWeight ?? ((config.tone ?? 'neutral') === 'neutral' ? 'regular' : 'fill'), size: 22, }); if (config.busy) glyph.classList.add('fotogenic-ai-icon--spin'); icon.appendChild(glyph); const copy = document.createElement('div'); copy.className = css('feedback-dialog-copy'); if (config.eyebrow) { const eyebrow = document.createElement('span'); eyebrow.textContent = config.eyebrow; copy.appendChild(eyebrow); } const title = document.createElement('h2'); title.id = titleId; title.textContent = config.title; const description = document.createElement('p'); description.id = descriptionId; description.textContent = config.description; copy.append(title); if (!config.compact) copy.append(description); let contentHost = panel; if (config.promotion) { const viewport = document.createElement('div'); viewport.className = css('promotion-viewport'); const media = document.createElement('div'); media.className = css('promotion-media'); if (config.promotion.imageFocus) media.classList.add(css(`media-focus-${config.promotion.imageFocus}`)); const image = document.createElement('img'); image.src = config.promotion.imageUrl; image.alt = ''; media.appendChild(image); if (config.promotion.productImageUrl) { const product = document.createElement('div'); product.className = css('promotion-product'); const label = document.createElement('span'); label.textContent = translate('Your product'); const thumbnail = document.createElement('img'); thumbnail.src = config.promotion.productImageUrl; thumbnail.alt = translate('Product photo'); product.append(label, thumbnail); media.appendChild(product); } contentHost = document.createElement('div'); contentHost.className = css('promotion-body'); const logo = document.createElement('img'); logo.className = css('promotion-logo'); logo.src = config.promotion.logoUrl; logo.alt = 'Fotogenic AI'; logo.width = 5042; logo.height = 893; contentHost.append(logo, copy); viewport.append(media, contentHost); panel.appendChild(viewport); } else { panel.append(icon, copy); } if (config.compact) { description.className = css('feedback-dialog-message'); contentHost.appendChild(description); } if (config.benefits?.length) { const benefits = document.createElement(config.promotion ? 'ol' : 'ul'); benefits.className = css('feedback-benefits'); config.benefits.forEach((benefit) => { const item = document.createElement('li'); item.textContent = benefit; benefits.appendChild(item); }); contentHost.appendChild(benefits); } if (config.content) { const content = Array.isArray(config.content) ? config.content : [config.content]; contentHost.append(...content); } if (config.promotion) { for (const [className, label] of [ ['promotion-balance', config.promotion.balance], ['promotion-qualification', config.promotion.qualification], ]) { if (!label) continue; const line = document.createElement('p'); line.className = css(className!); line.textContent = label; contentHost.appendChild(line); } } let primaryButton: HTMLButtonElement | null = null; let secondaryButton: HTMLButtonElement | null = null; if (config.primary || config.secondary) { const actions = document.createElement('div'); actions.className = css('feedback-dialog-actions'); if (config.footerNote) { const note = document.createElement('p'); note.className = css('feedback-dialog-footer-note'); note.setAttribute('role', 'status'); note.setAttribute('aria-live', 'polite'); note.setAttribute('aria-atomic', 'true'); actions.appendChild(note); } if (config.secondary) { secondaryButton = this.actionButton(config, config.secondary, 'secondary', 'secondary'); actions.appendChild(secondaryButton); } if (config.primary) { primaryButton = this.actionButton(config, config.primary, 'primary', 'primary'); actions.appendChild(primaryButton); } if (config.promotion && primaryButton) actions.prepend(primaryButton); contentHost.appendChild(actions); } if (config.promotion?.footer) { const footer = document.createElement('p'); footer.className = css('promotion-footer'); footer.textContent = config.promotion.footer; contentHost.appendChild(footer); } root.appendChild(panel); const mount = config.mount ?? document.body; if (mount === document.body) root.classList.add('fotogenic-ai-contained-overlay'); mount.appendChild(root); this.backdropTarget = config.backdropTarget ?? null; this.backdropTarget?.classList.add(css('feedback-blur-target')); const initialFocus = config.initialFocus === 'dialog' || (config.promotion && !config.initialFocus) ? panel : config.initialFocus === 'secondary' ? secondaryButton : config.initialFocus === 'dismiss' ? dismissButton : primaryButton ?? secondaryButton ?? dismissButton ?? panel; this.root = root; this.updateFooterNote(config.footerNote ?? null); this.overlay = overlayApi.create({ layer: root, panel, decorate: false, closeOnBackdrop: false, closeOnEscape: config.dismissible === true || config.closeOnEscape === true, onClose: () => this.finish(config, 'escape', null), onClosed: (manager) => { manager.destroy(); root.remove(); }, returnFocus: config.returnFocus ?? null, initialFocus, }); this.overlay.open({ returnFocus: config.returnFocus ?? null, initialFocus }); } updateFooterNote(note: DialogFooterNote | null): void { const host = this.root?.querySelector(`.${css('feedback-dialog-footer-note')}`); if (!host) return; if (this.footerNote?.text === note?.text && this.footerNote?.icon === note?.icon) return; this.footerNote = note ? { ...note } : null; host.hidden = !note?.text; if (!note?.text) { host.replaceChildren(); return; } const label = document.createElement('span'); label.textContent = note.text; host.replaceChildren(iconApi.create(note.icon, { weight: 'regular', size: 18 }), label); } close(restoreFocus = true, immediate = false): void { if (!this.root) return; const root = this.root; const overlay = this.overlay; this.root = null; this.overlay = null; this.actionPending = false; this.footerNote = null; this.backdropTarget?.classList.remove(css('feedback-blur-target')); this.backdropTarget = null; const closeImmediately = immediate || window.matchMedia('(prefers-reduced-motion: reduce)').matches; overlay?.close({ restoreFocus, immediate: closeImmediately }); if (!overlay) root.remove(); } destroy(): void { this.close(false); } isVisible(): boolean { return this.root !== null; } clearPromotionBalance(): void { this.root?.querySelector(`.${css('promotion-balance')}`)?.remove(); } private actionButton(config: DialogConfig, action: DialogAction, className: string, outcome: string): HTMLButtonElement { const button = document.createElement('button'); button.className = css(className); button.type = 'button'; button.disabled = action.disabled === true; button.textContent = action.label; button.addEventListener('click', () => { if (this.actionPending) return; const actionRoot = this.root; this.setActionPending(config, action, button, true); Promise.resolve().then(() => this.root === actionRoot ? config.onAction?.(action) : false).then((result) => { if (this.root !== actionRoot) return; if (actionFailed(result)) { this.setActionPending(config, action, button, false); this.showActionError(config); button.focus({ preventScroll: true }); return; } this.finish(config, outcome, action); }).catch((error: unknown) => { if (this.root !== actionRoot) return; this.setActionPending(config, action, button, false); this.showActionError(config); config.onError?.(error); button.focus({ preventScroll: true }); }); }); return button; } private showActionError(config: DialogConfig): void { if (!config.actionErrorMessage) return; const descriptionId = this.root?.querySelector('[aria-describedby]')?.getAttribute('aria-describedby'); const description = descriptionId ? document.getElementById(descriptionId) : null; if (description) { description.setAttribute('role', 'alert'); description.textContent = config.actionErrorMessage; } } private setActionPending( config: DialogConfig, selected: DialogAction, selectedButton: HTMLButtonElement, pending: boolean, ): void { this.actionPending = pending; const panel = this.root?.querySelector('[aria-modal="true"]'); if (pending || config.busy) panel?.setAttribute('aria-busy', 'true'); else panel?.removeAttribute('aria-busy'); const primary = this.root?.querySelector(`.${css('primary')}`); const secondary = this.root?.querySelector(`.${css('secondary')}`); const dismiss = this.root?.querySelector(`.${css('feedback-dialog-close')}`); if (primary) primary.disabled = pending || config.primary?.disabled === true; if (secondary) secondary.disabled = pending || config.secondary?.disabled === true; if (dismiss) dismiss.disabled = pending; selectedButton.textContent = pending && selected.pendingLabel ? selected.pendingLabel : selected.label; if (pending) { const spinner = iconApi.create('arrows-clockwise', { size: 16 }); spinner.classList.add('fotogenic-ai-icon--spin'); selectedButton.prepend(spinner); selectedButton.setAttribute('aria-busy', 'true'); } else selectedButton.removeAttribute('aria-busy'); } private finish(config: DialogConfig, outcome: string, action: DialogAction | null): void { if (this.actionPending && ['dismissed', 'escape'].includes(outcome)) return; this.close(true, config.immediateClose === true); config.onClose?.(outcome, action); } } interface BlockingErrorInput { kind?: unknown; code?: unknown; message?: unknown; debugId?: unknown; source?: unknown; } interface BlockingErrorActions { onRetry?: () => unknown | Promise; onExit?: () => void; retryLabel?: string; exitLabel?: string; } const blockingCode = (error: BlockingErrorInput): string => text(error.code).toUpperCase().replace(/^FOTOGENIC_AI_/, ''); const blockingTitle = (error: BlockingErrorInput, translateError: (value: string) => string): string => { const code = blockingCode(error); if (code === 'INSUFFICIENT_CREDITS') return translateError('You need more credits'); if (['INVALID_REQUEST', 'VALIDATION_FAILED', 'UNPROCESSABLE_ENTITY', 'UNPROCESSABLE_REQUEST'].includes(code)) { return translateError('Check your image settings'); } if (code === 'PROHIBITED_CONTENT') return translateError('Content restriction'); if (error.source === 'picker') return translateError("We couldn't load your items"); if (['REST_ERROR', 'API_ERROR', 'REQUEST_FAILED', 'NETWORK_ERROR'].includes(code)) { return translateError("We couldn't connect to Fotogenic AI"); } return translateError("Something didn't work"); }; const blockingMessage = (error: BlockingErrorInput, translateError: (value: string) => string): string => { const code = blockingCode(error); const rawMessage = text(error.message); if (code === 'PROHIBITED_CONTENT') { return translateError('This request was blocked by content restrictions. Review your photos and instructions, or contact support with the Support ID if this seems incorrect.'); } if (code === 'INSUFFICIENT_CREDITS') { return translateError('Add credits to your Fotogenic AI account, then try again.'); } if (['INVALID_REQUEST', 'VALIDATION_FAILED', 'UNPROCESSABLE_ENTITY', 'UNPROCESSABLE_REQUEST'].includes(code)) { return translateError('Check your selected photos and settings, then try again.'); } if (error.source === 'picker') { return translateError('Try again to reload the list. Your selections are still here.'); } if (code === 'API_ERROR' && /timed out/i.test(rawMessage)) { return translateError('This took longer than expected. Try again in a moment.'); } if (['REST_ERROR', 'API_ERROR', 'REQUEST_FAILED', 'NETWORK_ERROR'].includes(code)) { return translateError('Try again in a moment. If this keeps happening, contact support.'); } return translateError('Try again. If you still need help, copy the support details below and send them to our support team.'); }; const appendReportDetail = ( list: HTMLDListElement, label: string, value: unknown, useCode = false, ): void => { const row = document.createElement('div'); const term = document.createElement('dt'); const detail = document.createElement('dd'); term.textContent = label; if (useCode) { const code = document.createElement('code'); code.textContent = text(value) || '-'; detail.appendChild(code); } else { detail.textContent = text(value) || '-'; } row.append(term, detail); list.appendChild(row); }; const writeClipboard = async (value: string): Promise => { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(value); return; } const textarea = document.createElement('textarea'); textarea.value = value; textarea.readOnly = true; textarea.style.position = 'fixed'; textarea.style.opacity = '0'; document.body.appendChild(textarea); textarea.select(); const copied = document.execCommand('copy'); textarea.remove(); if (!copied) throw new Error('Copy was not available.'); }; class BlockingErrorDialog { private readonly dialog = new FeedbackDialog(); private copyResetTimer = 0; constructor( private readonly root: HTMLElement, private readonly translateError: (value: string) => string, ) { this.root.classList.add(css('error-root')); if (this.root.hasAttribute('data-fa-error-fullscreen')) this.root.classList.add(css('is-fullscreen')); } show(error: BlockingErrorInput, actions: BlockingErrorActions = {}): void { const reportData = buildSafeErrorReport(error); const supportId = reportData.reference; this.clearCopyTimer(); const message = blockingMessage(error, this.translateError); const support = document.createElement('div'); support.className = css('feedback-support-id'); const supportLabel = document.createElement('span'); supportLabel.textContent = this.translateError('Support ID'); const supportCode = document.createElement('code'); supportCode.textContent = supportId; support.append(supportLabel, supportCode); const details = document.createElement('details'); details.className = css('feedback-report-details'); const summary = document.createElement('summary'); summary.textContent = this.translateError('Details for support'); const report = document.createElement('div'); report.className = css('feedback-report-content'); const list = document.createElement('dl'); appendReportDetail(list, this.translateError('Category'), reportData.category); appendReportDetail(list, this.translateError('Code'), reportData.code, true); appendReportDetail(list, this.translateError('Reference'), supportId, true); appendReportDetail(list, this.translateError('Summary'), reportData.summary); const copy = document.createElement('button'); copy.type = 'button'; copy.textContent = this.translateError('Copy support details'); copy.addEventListener('click', async () => { const reportText = reportData.text; if (!reportText) return; this.clearCopyTimer(); try { await writeClipboard(reportText); copy.textContent = this.translateError('Details copied'); } catch { copy.textContent = this.translateError("Couldn't copy. Try again."); } this.copyResetTimer = window.setTimeout(() => { copy.textContent = this.translateError('Copy support details'); this.copyResetTimer = 0; }, 2200); }); report.append(list, copy); details.append(summary, report); const primary = typeof actions.onRetry === 'function' ? { label: actions.retryLabel || this.translateError('Try again'), pendingLabel: this.translateError('Trying again…'), action: 'retry', url: '', newTab: false, } : null; const secondary = { label: actions.exitLabel || this.translateError('Close'), action: 'exit', url: '', newTab: false, }; this.root.hidden = false; this.root.setAttribute('aria-hidden', 'false'); this.dialog.show({ compact: true, tone: 'danger', icon: 'warning', iconWeight: 'regular', title: blockingTitle(error, this.translateError), description: message, content: [support, details], dismissible: true, primary, secondary, role: 'alertdialog', mount: this.root, contained: true, immediateClose: true, actionErrorMessage: this.translateError("That didn't work. Try again in a moment, or contact support if it keeps happening."), onAction: async (selected) => { if (selected.action === 'exit') { return true; } return actions.onRetry?.(); }, onError: () => window.dispatchEvent(new CustomEvent('fotogenic-ai:error-retry-failed', { detail: Object.freeze({ supportId }), })), onClose: (_outcome, selected) => { this.hideRoot(); if (selected?.action !== 'retry') actions.onExit?.(); }, }); } hide(): void { this.dialog.close(true); this.hideRoot(); } isVisible(): boolean { return this.dialog.isVisible(); } destroy(): void { this.clearCopyTimer(); this.dialog.destroy(); this.hideRoot(); this.root.classList.remove(css('error-root'), css('is-fullscreen')); } private hideRoot(): void { this.clearCopyTimer(); this.root.hidden = true; this.root.setAttribute('aria-hidden', 'true'); } private clearCopyTimer(): void { if (!this.copyResetTimer) return; window.clearTimeout(this.copyResetTimer); this.copyResetTimer = 0; } } const action = (raw: unknown, label: string, fallbackAction = ''): FeedbackAction | null => { const value = record(raw); const actionId = text(value.id) || fallbackAction; if (!actionId || !label) return null; return { label, action: actionId, url: safeUrl(value.url), newTab: value.newTab === true || ['add_credits', 'view_plans'].includes(actionId), }; }; const experienceImage = (imageUrls: unknown, kind: string): string => { const map = record(imageUrls); const mapped = safeUrl(map[kind]); if (mapped) return mapped; return Array.isArray(imageUrls) ? safeUrl(imageUrls[0]) : ''; }; const normalizeExperiencePayload = (payload: unknown, imageUrls: unknown = {}): ExperiencePayload | null => { const envelope = record(payload); const source = record(envelope.experience); if (envelope.claimed !== true) return null; const kind = text(source.kind); if (!['welcome_disconnected', 'welcome_connected', 'zero', 'low'].includes(kind)) return null; const id = text(source.claimId); if (!id) return null; const balance = finite(source.balance); if ((kind === 'zero' || kind === 'low') && (balance === null || balance < 0)) return null; const grantedCredits = finite(source.grantedCredits); const hasPlan = source.hasPlan === true; let primary: FeedbackAction | null = null; let secondary: FeedbackAction | null = null; if (kind === 'welcome_disconnected') { primary = action(source.primaryAction, translate('Connect Fotogenic AI'), 'connect'); secondary = action({ id: 'dismiss' }, translate('Explore first')); } else if (kind === 'welcome_connected') { primary = action(source.primaryAction, translate('Start creating'), 'open_dashboard'); } else { primary = action(source.primaryAction, translate('Add credits'), hasPlan ? 'add_credits' : 'view_plans'); secondary = action({ id: 'dismiss' }, translate('Not now')); } return { id, kind: kind as ExperiencePayload['kind'], priority: kind.startsWith('welcome_') ? 30 : kind === 'zero' ? 20 : 10, balance, grantedCredits, hasPlan, imageUrl: experienceImage(imageUrls, kind), productImageUrl: kind.startsWith('welcome_') ? safeUrl(record(imageUrls).welcome_product) : '', logoUrl: safeUrl(record(imageUrls).logo), primary, secondary, }; }; const experienceDialogConfig = (payload: ExperiencePayload): DialogConfig | null => { if (payload.kind === 'welcome_connected') { const amount = payload.grantedCredits ?? 0; if (amount <= 0 || !payload.imageUrl) return null; const balance = payload.balance; return { tone: 'success', icon: 'gift', eyebrow: translate('Welcome to Fotogenic AI'), title: translate("You're connected"), description: translate('Try image generation, campaigns, or image enhancement.'), promotion: { imageUrl: payload.imageUrl, productImageUrl: payload.productImageUrl, logoUrl: payload.logoUrl, imageFocus: 'upper', balance: balance === null ? '' : `${numberLabel(balance)} ${translate(balance === 1 ? 'credit available' : 'credits available')}`, footer: '', }, primary: payload.primary, dismissible: true, }; } if (payload.kind === 'welcome_disconnected') { return { tone: 'neutral', icon: 'sign-in', eyebrow: translate('Meet your new image studio'), title: translate('Start creating'), description: translate('Create new images, build campaigns, and enhance your existing photos.'), promotion: { imageUrl: payload.imageUrl, productImageUrl: payload.productImageUrl, logoUrl: payload.logoUrl, qualification: translate('For new eligible accounts. No credit card required.'), footer: '', }, primary: payload.primary, secondary: payload.secondary, dismissible: true, }; } if (payload.kind === 'zero' || payload.kind === 'low') { const balance = payload.balance ?? 0; return { tone: 'neutral', icon: 'coins', iconWeight: 'fill', eyebrow: translate('Keep creating with Fotogenic AI'), title: payload.kind === 'zero' ? translate('Add credits') : translate('Time to top up'), description: payload.kind === 'zero' ? translate('Add credits to generate new images, create campaigns, or enhance photos.') : translate('Top up your balance to keep creating with Fotogenic AI.'), promotion: { imageUrl: payload.imageUrl, logoUrl: payload.logoUrl, balance: `${numberLabel(balance)} ${translate('credits remaining')}`, imageFocus: payload.kind === 'low' ? 'lower' : 'center', footer: '', }, primary: payload.primary, secondary: payload.secondary, dismissible: true, }; } return null; }; const createCreditShortfallController = (options: UnknownRecord = {}) => { const dialog = new FeedbackDialog(); const imageUrls = record(options.imageUrls); let visible = false; return Object.freeze({ show(required: number, balance: number, returnFocus: HTMLElement | null = null): boolean { if (visible || !Number.isFinite(required) || !Number.isFinite(balance) || required <= balance || balance < 0) return false; const shortage = Math.ceil((required - balance - 0.000001) * 100) / 100; const url = safeUrl(options.pricingUrl); if (shortage <= 0 || !url) return false; visible = true; dialog.show({ tone: 'neutral', icon: 'coins', eyebrow: translate('Keep creating with Fotogenic AI'), title: translate('%s more credits').replace('%s', numberLabel(shortage)), description: translate('Add the remaining credits to start this run, or reduce your selection.'), promotion: { imageUrl: safeUrl(imageUrls.shortfall), logoUrl: safeUrl(imageUrls.logo), imageFocus: 'upper', balance: translate('%s credits required · %s available').replace('%s', numberLabel(required)).replace('%s', numberLabel(balance)), footer: '', }, primary: { label: translate('Add credits'), action: 'add_credits', url, newTab: true }, secondary: { label: translate('Back to review'), action: 'dismiss', url: '', newTab: false }, dismissible: true, returnFocus, onAction: (selected) => selected.action === 'dismiss' || followAction(selected), onClose: () => { visible = false; }, }); return true; }, close(): void { visible = false; dialog.close(true); }, destroy(): void { visible = false; dialog.destroy(); }, }); }; const followAction = (value: FeedbackAction): boolean => { const url = safeUrl(value.url); if (!url) return false; if (value.newTab && value.action !== 'connect') { 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(); } else { window.location.assign(url); } return true; }; const createExperienceController = (options: UnknownRecord = {}) => { const dialog = new FeedbackDialog(); const claim = typeof options.claim === 'function' ? options.claim as (body: UnknownRecord) => Promise : null; const dismiss = typeof options.dismiss === 'function' ? options.dismiss as (body: UnknownRecord) => Promise : null; const onAction = typeof options.onAction === 'function' ? options.onAction as (action: FeedbackAction, payload: ExperiencePayload) => unknown : null; const onError = typeof options.onError === 'function' ? options.onError as (detail: UnknownRecord) => void : null; const canPresent = typeof options.canPresent === 'function' ? options.canPresent as () => boolean : () => true; let destroyed = false; let inFlight: Promise | null = null; let lastClaimAt = 0; let pending: ExperiencePayload | null = null; let visible: ExperiencePayload | null = null; let balanceRevision = 0; let updatedBalance: number | null = null; let revision = 0; let cancelPresentation: (() => void) | null = null; let cancelClaimDelay: (() => void) | null = null; const report = (operation: string, code: string): void => { const detail = Object.freeze({ operation, code }); window.dispatchEvent(new CustomEvent('fotogenic-ai:experience-error', { detail })); onError?.(detail); }; const recordOutcome = async (payload: ExperiencePayload, outcome: string): Promise => { if (!dismiss) return; try { const response = record(await dismiss({ claimId: payload.id, outcome })); if (response.ok === false) report('dismiss', text(record(response.data).code) || 'request_failed'); } catch { report('dismiss', 'network_error'); } }; const runAction = (selected: FeedbackAction, payload: ExperiencePayload): unknown => { if (selected.action === 'dismiss') return true; return onAction ? onAction(selected, payload) : followAction(selected); }; const present = (payload: ExperiencePayload): Promise => { const config = experienceDialogConfig(payload); if (!config) { report('present', 'invalid_response'); return Promise.resolve(null); } return new Promise((resolve) => { visible = payload; cancelPresentation = () => { visible = null; dialog.close(false, true); cancelPresentation = null; resolve(null); }; dialog.show({ ...config, actionErrorMessage: payload.kind === 'welcome_disconnected' ? translate("We couldn't connect to Fotogenic AI. Try connecting again, or choose Explore first.") : translate('That action could not be completed. Please try again.'), returnFocus: resolveElement(options.restoreFocusTo), onAction: (selected) => runAction(selected, payload), onError: () => report('action', 'action_failed'), onClose: (outcome, selected) => { visible = null; cancelPresentation = null; const result = outcome === 'primary' || outcome === 'secondary' ? outcome : 'dismissed'; void recordOutcome(payload, result); resolve({ outcome, action: selected, payload }); }, }); }); }; const onCreditsUpdated = (event: Event): void => { if (destroyed) return; balanceRevision += 1; const detail = record((event as CustomEvent).detail); updatedBalance = detail.isFresh === true ? finite(detail.balance) : null; let recheckDepletion = false; for (const payload of [pending, visible]) { if (!payload || (updatedBalance !== null && updatedBalance === payload.balance)) continue; if (payload.kind === 'welcome_connected') { payload.balance = null; if (payload === visible) dialog.clearPromotionBalance(); } else if (payload.kind === 'zero' || payload.kind === 'low') recheckDepletion = true; } if (recheckDepletion) { controller.invalidate(); void controller.claimNext({ force: true }); } }; const controller = Object.freeze({ claimNext({ force = false }: { force?: boolean } = {}): Promise { if (destroyed || !claim || !canPresent()) return Promise.resolve(null); if (inFlight) return inFlight; if (pending) { const payload = pending; pending = null; const presentationRevision = revision; inFlight = present(payload).finally(() => { if (presentationRevision === revision) inFlight = null; }); return inFlight; } const requestRevision = revision; let requestBalanceRevision = balanceRevision; const now = Date.now(); if (!force && now - lastClaimAt < 1000) return inFlight ?? Promise.resolve(null); if (inFlight) return inFlight; let claimStarted = false; inFlight = new Promise((resolve) => { const timer = window.setTimeout(() => { cancelClaimDelay = null; resolve(); }, 500); cancelClaimDelay = () => { window.clearTimeout(timer); cancelClaimDelay = null; resolve(); }; }).then(() => { if (destroyed || requestRevision !== revision || !canPresent()) return null; claimStarted = true; requestBalanceRevision = balanceRevision; lastClaimAt = Date.now(); return claim({}); }).then((response) => { if (!claimStarted || destroyed || requestRevision !== revision) return null; const result = record(response); if (result.ok === false) { report('claim', text(record(result.data).code) || 'request_failed'); return null; } if (record(result.data).claimed === false) return null; const payload = normalizeExperiencePayload(result.data, options.imageUrls); if (!payload) { report('claim', 'invalid_response'); return null; } if (requestBalanceRevision !== balanceRevision && updatedBalance !== payload.balance) { if (payload.kind === 'welcome_connected') payload.balance = null; else if (payload.kind === 'zero' || payload.kind === 'low') { controller.invalidate(); return controller.claimNext({ force: true }); } } if (!canPresent()) { pending = payload; return null; } return present(payload); }).catch(() => { report('claim', 'network_error'); return null; }).finally(() => { if (requestRevision === revision) inFlight = null; }); return inFlight; }, invalidate(): void { revision += 1; pending = null; cancelClaimDelay?.(); cancelPresentation?.(); inFlight = null; lastClaimAt = 0; }, destroy(): void { destroyed = true; pending = null; window.removeEventListener('fotogenic-ai:credits-updated', onCreditsUpdated); cancelClaimDelay?.(); cancelPresentation?.(); dialog.destroy(); }, }); window.addEventListener('fotogenic-ai:credits-updated', onCreditsUpdated); return controller; }; const authDefinition = (state: AuthState): DialogConfig | null => { const definitions: Record = { login_starting: { tone: 'neutral', icon: 'arrows-clockwise', title: translate('Connecting to Fotogenic AI'), description: translate('Opening the sign-in page…'), primary: { label: translate('Cancel'), action: 'cancel', url: '', newTab: false }, busy: true, initialFocus: 'primary', closeOnEscape: true, }, login_cancelled: { tone: 'neutral', icon: 'sign-in', title: translate('Connection cancelled'), description: translate('Nothing changed. Connect again whenever you are ready to view credits and generate.'), primary: { label: translate('Connect again'), action: 'retry', url: '', newTab: false }, dismissible: true, }, login_failed: { tone: 'danger', icon: 'warning', iconWeight: 'fill', title: translate('Could not connect'), description: translate("We couldn't open the Fotogenic AI sign-in page. Refresh this page and try signing in again. If it still fails, contact support."), primary: { label: translate('Try again'), action: 'retry', url: '', newTab: false }, secondary: { label: translate('Not now'), action: 'close', url: '', newTab: false }, closeOnEscape: true, }, login_success: { tone: 'success', icon: 'check-circle', iconWeight: 'fill', title: translate('Fotogenic AI connected'), description: translate('Your Fotogenic AI account is connected to this site.'), primary: { label: translate('Continue'), action: 'close', url: '', newTab: false }, closeOnEscape: true, }, logout_pending: { tone: 'neutral', icon: 'arrows-clockwise', title: translate('Disconnecting account'), description: translate('Disconnecting your Fotogenic AI account. Your saved images and settings will stay here.'), busy: true, initialFocus: 'dialog', }, logout_failed: { tone: 'danger', icon: 'warning', iconWeight: 'fill', title: translate('Could not log out'), description: translate('Your account is still connected. Try disconnecting again, or return to Studio.'), primary: { label: translate('Try again'), action: 'retry', url: '', newTab: false }, secondary: { label: translate('Return to Studio'), action: 'close', url: '', newTab: false }, closeOnEscape: true, }, }; return definitions[state] ?? null; }; const createAuthTransitionController = (options: UnknownRecord = {}) => { const dialog = new FeedbackDialog(); let destroyed = false; return Object.freeze({ show(state: AuthState, handlers: Record void) | undefined> = {}, description = ''): Promise { if (destroyed) return Promise.resolve(null); const config = authDefinition(state); if (!config) { dialog.close(true); return Promise.resolve(null); } return new Promise((resolve) => dialog.show({ ...config, ...(state === 'login_failed' && description ? { description } : {}), ...(state === 'login_failed' && !handlers.retry ? { primary: { label: translate('Close'), action: 'close', url: '', newTab: false }, secondary: null, } : {}), returnFocus: resolveElement(options.restoreFocusTo), onAction: (selected) => { handlers[selected.action]?.(); return false; }, onClose: (outcome) => { if (['dismissed', 'escape'].includes(outcome)) handlers.dismiss?.(); resolve({ outcome, state }); }, })); }, close(): void { dialog.close(true); }, destroy(): void { destroyed = true; dialog.destroy(); }, }); }; const createBlockingErrorOverlay = ( root: HTMLElement, i18n: { __?: (value: string, domain?: string) => string } = {}, ) => { if (!(root instanceof HTMLElement)) throw new TypeError('Fotogenic AI: blocking error root is unavailable.'); const translateError = (value: string): string => i18n.__?.(value, 'fotogenic-ai') ?? value; return new BlockingErrorDialog(root, translateError); }; if (!shared?.ui) throw new Error('Fotogenic AI: shared UI namespace is unavailable.'); shared.ui.feedbackDialog = Object.freeze({ create: (): FeedbackDialog => new FeedbackDialog() }); shared.ui.experienceDialog = Object.freeze({ createCreditShortfallController, createAuthTransitionController, createBlockingErrorOverlay, createExperienceController, normalizeExperiencePayload, }); export { FeedbackDialog, createCreditShortfallController, createAuthTransitionController, createBlockingErrorOverlay, createExperienceController, normalizeExperiencePayload, followAction as followExperienceAction, };