import styles from './account-menu.module.css'; interface RestResult { ok: boolean; data?: unknown; status?: number; aborted?: boolean; wpSessionExpired?: boolean; message?: string; endpoint?: string; } type RestFetch = ( path: string, options?: { method?: string; body?: unknown; signal?: AbortSignal }, ) => Promise; interface AccountContext { root?: HTMLElement | null; restFetch?: RestFetch; i18n?: { __?: (text: string, domain?: string) => string }; notify?: AccountNotifier; onHistory?: () => void; closeNotifications?: () => void; } export interface AccountNotifier { success?: (message: string, options?: Record) => void; info?: (message: string, options?: Record) => void; warning?: (message: string, options?: Record) => void; } interface AccountController { close: (restoreFocus?: boolean) => void; isConnected: () => boolean; startLogin: () => Promise; openTopup: () => void; openPlans: () => void; destroy: () => void; } interface IconApi { update: ( element: Element, name: string, options: { weight: 'regular'; size: number }, ) => void; } interface AuthTransitionController { show: (state: string, handlers?: Record void>, description?: string) => Promise | void; close: () => void; destroy: () => void; } interface SharedRuntime { ui?: { icon?: IconApi; experienceDialog?: { createAuthTransitionController?: (options: { containmentRoot: HTMLElement | null; restoreFocusTo: HTMLElement | null; }) => AuthTransitionController; }; }; creditsCache?: { setBalance?: (balance: number, metadata?: Record) => void; clearBalance?: () => void; ensure?: ( fetchBalance: () => Promise, options?: { force?: boolean }, ) => Promise; }; } interface RuntimeWindow extends Window { FotogenicAI?: { Shared?: SharedRuntime; }; } type CreditStatus = 'ready' | 'refreshing' | 'stale' | 'unknown'; const record = (value: unknown): Record => ( value !== null && typeof value === 'object' ? value as Record : {} ); const css = (name: string): string => { const value = styles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} account style.`); return value; }; const createAccountController = (context: AccountContext = {}): AccountController => { const shared = (window as RuntimeWindow).FotogenicAI?.Shared; const icons = shared?.ui?.icon; if (!icons?.update) throw new Error('Fotogenic AI: icon system must load before account controls.'); const translate = (value: string): string => context.i18n?.__?.(value, 'fotogenic-ai') || value; const applicationRoot = context.root instanceof HTMLElement ? context.root : document.querySelector('[data-fa-studio-root], .fotogenic-ai-settings-shell, [data-fa-home]'); const headerActions = document.querySelector('[data-fa-header-actions]'); const accountCluster = document.querySelector('[data-fa-account-cluster]'); const accountDropdown = document.querySelector('[data-fa-account-dropdown]'); const accountToggle = document.querySelector('[data-fa-account-toggle]'); const accountMenu = document.querySelector('[data-fa-account-menu]'); const accountConnectionStatus = document.querySelector('[data-fa-account-connection-status]'); const accountConnectionDot = document.querySelector('[data-fa-account-connection-dot]'); const accountConnectionCopy = document.querySelector('[data-fa-account-connection-copy]'); const accountDivider = document.querySelector('[data-fa-account-divider]'); const accountCaret = document.querySelector('[data-fa-account-caret]'); const accountSummary = document.querySelector('[data-fa-account-summary]'); const accountEmail = document.querySelector('[data-fa-account-email]'); const accountStatus = document.querySelector('[data-fa-account-status]'); const accountStatusDot = document.querySelector('[data-fa-account-status-dot]'); const accountStatusCopy = document.querySelector('[data-fa-account-status-copy]'); const accountBalance = document.querySelector('[data-fa-account-balance]'); const accountHelp = document.querySelector('[data-fa-account-help]'); const accountConnectedActions = document.querySelector('[data-fa-account-connected-actions]'); const accountDisconnectedActions = document.querySelector('[data-fa-account-disconnected-actions]'); const accountTriggerIcon = document.querySelector('[data-fa-account-trigger-icon]'); const accountSignIn = document.querySelector('[data-fa-account-signin]'); const accountLoginLabel = document.querySelector('[data-fa-account-login-label]'); const creditsElement = document.querySelector('[data-fa-credits]'); const creditsLabel = document.querySelector('[data-fa-credits-label]'); const creditsRefresh = document.querySelector('[data-fa-credits-refresh]'); const accountLogout = document.querySelector('[data-fa-account-logout]'); const accountLogin = document.querySelector('[data-fa-account-login]'); const accountTopup = document.querySelector('[data-fa-account-topup]'); const accountPricing = document.querySelector('[data-fa-account-pricing]'); const accountPrimaryActions = [...document.querySelectorAll('[data-fa-account-primary]')]; const accountLists = [...document.querySelectorAll('[data-fa-account-list]')]; const historyActions = [...document.querySelectorAll('[data-fa-open-history]')]; const settingsRoot = document.querySelector('.fotogenic-ai-settings[data-auth-connected]'); const homeRoot = applicationRoot?.matches('[data-fa-home]') === true; const initialConnected = headerActions?.dataset.faAuthConnected === '1'; if ( !applicationRoot || !headerActions || !accountCluster || !accountDropdown || !accountToggle || !accountMenu || !accountConnectionStatus || !accountConnectionDot || !accountDivider || !accountCaret || !accountSummary || !accountStatus || !accountStatusDot || !accountLogout || !accountLogin || accountPrimaryActions.length !== 2 || accountLists.length !== 2 ) { throw new Error('Fotogenic AI: account anatomy is unavailable.'); } headerActions.className = css('headerActions'); accountCluster.className = css('cluster'); accountConnectionStatus.className = css('connection'); accountConnectionDot.className = css('connectionDot'); accountDivider.className = css('divider'); accountDropdown.className = css('dropdown'); accountToggle.className = css('trigger'); accountCaret.classList.add(css('caret')); accountMenu.className = css('menu'); accountMenu.inert = accountMenu.hidden !== false; accountSummary.className = css('summary'); if (accountEmail) accountEmail.className = css('email'); if (accountHelp) accountHelp.className = css('help'); accountStatus.className = css('status'); accountStatusDot.className = css('statusDot'); accountPrimaryActions.forEach((action) => { action.className = css('primary'); }); accountLists.forEach((list) => { list.className = css('list'); }); accountLogout.className = css('logout'); let connected = initialConnected; let connectedEmail = initialConnected ? accountEmail?.textContent?.trim() || '' : ''; let expired = false; let pending = false; let destroyed = false; let authRequest: AbortController | null = null; let successPresented = false; let queuedCreditRefresh = false; let queuedCreditRefreshAnnouncement = false; let menuCloseTimer = 0; const menuMotionDuration = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 160; let flushQueuedCreditRefresh = (): void => {}; let lastKnownBalance = Number(String(creditsElement?.textContent ?? '').replaceAll(',', '')); if (!Number.isFinite(lastKnownBalance) || lastKnownBalance < 0) lastKnownBalance = Number.NaN; let creditStatus: CreditStatus = initialConnected && Number.isFinite(lastKnownBalance) ? 'ready' : 'unknown'; const authTransitions = shared?.ui?.experienceDialog?.createAuthTransitionController?.({ containmentRoot: applicationRoot, restoreFocusTo: accountToggle, }); const request = async ( path: string, options: { method?: string; body?: unknown; signal?: AbortSignal } = {}, ): Promise => { if (typeof context.restFetch !== 'function') { return { ok: false, data: {}, status: 0, message: 'Account transport is unavailable.' }; } try { return await context.restFetch(path, options); } catch (error) { return { ok: false, data: {}, status: 0, aborted: options.signal?.aborted === true, message: error instanceof Error ? error.message : String(error), }; } }; const formatBalance = (value: unknown): string => { const balance = Number(String(value ?? '').replaceAll(',', '')); return Number.isFinite(balance) && balance >= 0 ? `${balance.toLocaleString()} ${translate('credits')}` : translate('Balance unknown'); }; const currentCreditLabel = (): string => creditStatus === 'refreshing' ? translate('Refreshing…') : creditStatus === 'stale' ? translate('Balance stale') : creditStatus === 'unknown' ? translate('Balance unknown') : formatBalance(lastKnownBalance); const syncAccountToggleLabel = (): void => { const label = connected ? currentCreditLabel() : expired ? translate('Reconnect') : translate('Sign in'); accountToggle.setAttribute('aria-label', `${label}, ${translate('Account and credits')}`); }; const syncCreditPresentation = (): void => { if (!connected) return; const ready = creditStatus === 'ready'; const label = currentCreditLabel(); if (creditsElement) creditsElement.hidden = !ready; if (creditsLabel) creditsLabel.hidden = !ready; if (accountSignIn) { accountSignIn.hidden = ready; accountSignIn.textContent = label; } if (accountBalance) accountBalance.hidden = true; if (accountHelp) { accountHelp.hidden = ready || creditStatus === 'refreshing'; accountHelp.textContent = creditStatus === 'ready' ? '' : creditStatus === 'refreshing' ? translate('Confirming the latest authoritative balance.') : creditStatus === 'stale' ? translate('Last known balance; generation remains blocked.') : translate('No authoritative balance is currently available.'); } syncAccountToggleLabel(); }; const setCreditStatus = (status: CreditStatus): void => { creditStatus = status; syncCreditPresentation(); }; const syncState = (next: { connected?: boolean; balance?: unknown; expired?: boolean; user?: unknown } = {}): void => { connected = next.connected ?? connected; if (!connected) connectedEmail = ''; else if (next.user !== undefined) { const email = record(next.user).email; connectedEmail = typeof email === 'string' ? email.trim() : ''; } if (accountEmail) { accountEmail.textContent = connectedEmail; accountEmail.hidden = !connectedEmail; } expired = !connected && next.expired === true; if (!connected) successPresented = false; if (headerActions) headerActions.dataset.faAuthConnected = connected ? '1' : '0'; if (accountConnectionStatus) accountConnectionStatus.hidden = !expired; if (accountConnectionCopy) accountConnectionCopy.textContent = expired ? translate('Session expired') : translate('Not connected'); if (accountDivider) accountDivider.hidden = !expired; if (accountConnectedActions) accountConnectedActions.hidden = !connected; if (accountDisconnectedActions) accountDisconnectedActions.hidden = connected; if (accountStatusCopy) accountStatusCopy.textContent = connected ? translate('Connected account') : translate('Fotogenic AI account'); accountStatusDot.classList.toggle(css('statusDotConnected'), connected); if (accountTriggerIcon) { icons.update(accountTriggerIcon, connected ? 'coins' : 'sign-in', { weight: 'regular', size: connected ? 19 : 18, }); } if (creditsElement) creditsElement.hidden = !connected; if (creditsLabel) creditsLabel.hidden = !connected; if (accountSignIn && !connected) { accountSignIn.hidden = false; accountSignIn.textContent = expired ? translate('Reconnect') : translate('Sign in'); } if (accountLoginLabel) accountLoginLabel.textContent = expired ? translate('Reconnect Fotogenic AI') : translate('Login to Fotogenic AI'); if (connected && typeof next.balance !== 'undefined') { const numeric = Number(String(next.balance ?? '').replaceAll(',', '')); const formatted = Number.isFinite(numeric) && numeric >= 0 ? numeric.toLocaleString() : '-'; lastKnownBalance = Number.isFinite(numeric) && numeric >= 0 ? numeric : Number.NaN; creditStatus = Number.isFinite(lastKnownBalance) ? 'ready' : 'unknown'; if (creditsElement && creditsElement.textContent !== formatted) creditsElement.textContent = formatted; syncCreditPresentation(); } else if (!connected) { if (accountBalance) accountBalance.hidden = false; if (accountBalance) accountBalance.textContent = expired ? translate('Session expired') : translate('Connect to continue'); if (accountHelp) { accountHelp.hidden = false; accountHelp.textContent = translate('Sign in to view credits and start generations.'); } } syncAccountToggleLabel(); }; const visibleMenuItems = (): HTMLElement[] => accountMenu ? [...accountMenu.querySelectorAll('[role="menuitem"]')] .filter((item) => !('disabled' in item && item.disabled) && !item.closest('[hidden]')) : []; const close = (restoreFocus = false): void => { if (!accountMenu || accountMenu.hidden || accountMenu.inert) return; window.clearTimeout(menuCloseTimer); accountMenu.classList.remove(css('menuOpen')); accountMenu.classList.add(css('menuClosing')); accountMenu.inert = true; accountToggle?.setAttribute('aria-expanded', 'false'); const finish = (): void => { accountMenu.hidden = true; accountMenu.classList.remove(css('menuClosing')); menuCloseTimer = 0; }; if (menuMotionDuration === 0) finish(); else menuCloseTimer = window.setTimeout(finish, menuMotionDuration); if (restoreFocus) accountToggle?.focus({ preventScroll: true }); }; const setPending = (value: boolean): void => { pending = value; accountMenu?.setAttribute('aria-busy', value ? 'true' : 'false'); if (creditsRefresh) creditsRefresh.disabled = value; if (accountLogout) accountLogout.disabled = value; if (accountLogin) accountLogin.disabled = value; if (!value && queuedCreditRefresh) { void Promise.resolve().then(flushQueuedCreditRefresh); } }; const closeTransition = (): void => { authTransitions?.close(); window.requestAnimationFrame(() => accountToggle?.focus({ preventScroll: true })); }; const showLoginSuccess = (): void => { if (successPresented) return; successPresented = true; void authTransitions?.show('login_success', { close: closeTransition, dismiss: closeTransition }); }; const cancelLogin = (): void => { const controller = authRequest; authRequest = null; controller?.abort(); setPending(false); void authTransitions?.show('login_cancelled', { retry: () => void startLogin(), dismiss: closeTransition, }); }; const startLogin = async (): Promise => { if (pending || connected) return { ok: false, aborted: true }; close(); setPending(true); const controller = new AbortController(); authRequest = controller; void authTransitions?.show('login_starting', { cancel: cancelLogin, dismiss: cancelLogin }); let result = await request('/auth/start', { method: 'POST', body: homeRoot ? { source: 'home' } : settingsRoot ? { source: 'settings' } : { source: 'studio', route: { workflow: applicationRoot.dataset.workflow, sourceType: applicationRoot.dataset.sourceType, scope: applicationRoot.dataset.scope, }, }, signal: controller.signal, }); if (authRequest !== controller) return result; authRequest = null; setPending(false); if (result.aborted) { closeTransition(); return result; } const authorizationUrl = String(record(result.data).authorizationUrl ?? '').trim(); if (result.ok) { try { if (!authorizationUrl) throw new Error('Missing authorization URL.'); const destination = new URL(authorizationUrl, window.location.href); if (!['https:', 'http:'].includes(destination.protocol)) { throw new Error('Unsupported authorization URL protocol.'); } if (!settingsRoot && !homeRoot) window.dispatchEvent(new CustomEvent('fotogenic-ai:auth-leaving')); window.location.assign(destination.href); return result; } catch { result = { ok: false, data: {}, status: 0, message: translate('We could not open the Fotogenic AI sign-in page. Try again.'), }; } } const { code, message } = record(result.data); let description = ''; if (result.wpSessionExpired || code === 'rest_not_logged_in' || (code === 'rest_forbidden' && result.status === 401)) { description = translate('Sign in to WordPress again, then open Fotogenic AI Settings and choose Connect.'); } else if (code === 'rest_forbidden' || code === 'fotogenic_ai_forbidden') { description = translate('Ask your WordPress site administrator to connect Fotogenic AI.'); } else if (code === 'fotogenic_ai_auth_encryption_unavailable') { description = translate('Ask your hosting provider to enable PHP Sodium or OpenSSL, then try signing in again.'); } else if (code === 'fotogenic_ai_invalid_auth_route') { description = translate('Reload Studio, then try signing in again.'); } else if (code === 'fotogenic_ai_auth_redirect_invalid' && typeof message === 'string') { description = message; } void authTransitions?.show('login_failed', { ...(description ? {} : { retry: () => void startLogin() }), close: closeTransition, dismiss: closeTransition, }, description); return result; }; const refreshBalance = async (announceSuccess = true): Promise => { if (!connected) return; if (pending) { queuedCreditRefresh = true; queuedCreditRefreshAnnouncement = queuedCreditRefreshAnnouncement || announceSuccess; return; } setPending(true); setCreditStatus('refreshing'); const fetchBalance = (): Promise => request('/credits/refresh', { method: 'POST' }); let balance: number | null = null; if (shared?.creditsCache?.ensure) { balance = await shared.creditsCache.ensure(fetchBalance, { force: true }); } else { const result = await fetchBalance(); const data = record(result.data); const returnedBalance = Number(data.balance); if (result.ok && Number.isFinite(returnedBalance)) { balance = returnedBalance; shared?.creditsCache?.setBalance?.(balance, { fetchedAt: data.fetchedAt, ttlSeconds: data.ttlSeconds, provenance: data.provenance, }); } } setPending(false); if (null !== balance && Number.isFinite(balance)) { syncState({ connected: true, balance }); if (announceSuccess) { context.notify?.success?.(`${balance.toLocaleString()} ${translate('credits confirmed.')}`, { title: translate('Balance refreshed'), dedupeKey: 'credits:refresh-success', }); } return; } if (!connected) return; const nextStatus: CreditStatus = Number.isFinite(lastKnownBalance) ? 'stale' : 'unknown'; setCreditStatus(nextStatus); const title = nextStatus === 'unknown' ? translate('We could not load your credit balance') : translate('We could not update your credit balance'); const message = nextStatus === 'unknown' ? translate('Try again to check your credits before creating images.') : `${translate('Last shown balance:')} ${lastKnownBalance.toLocaleString()} ${translate('credits. Try again to check your current balance before creating images.')}`; context.notify?.warning?.(message, { title, ttlMs: 0, dedupeKey: `credits:${nextStatus}`, actions: [{ label: translate('Try again'), onClick: () => void refreshBalance() }], }); }; flushQueuedCreditRefresh = (): void => { if (!queuedCreditRefresh) return; if (destroyed || !connected) { queuedCreditRefresh = false; queuedCreditRefreshAnnouncement = false; return; } if (pending) return; const announceSuccess = queuedCreditRefreshAnnouncement; queuedCreditRefresh = false; queuedCreditRefreshAnnouncement = false; void refreshBalance(announceSuccess); }; const logout = async (): Promise => { if (pending || !connected) return; close(); setPending(true); void authTransitions?.show('logout_pending'); const result = await request('/auth/logout', { method: 'POST' }); setPending(false); if (result.ok) { authTransitions?.close(); shared?.creditsCache?.clearBalance?.(); syncState({ connected: false, expired: false }); window.dispatchEvent(new CustomEvent('fotogenic-ai:auth-changed', { detail: { auth: record(result.data).auth || { connected: false, balance: null } }, })); context.notify?.info?.(translate('Disconnected from Fotogenic AI'), { title: translate('Account disconnected'), dedupeKey: 'auth:logout:success', }); return; } void authTransitions?.show('logout_failed', { retry: () => void logout(), close: closeTransition, dismiss: closeTransition, }); }; const openTopup = (): void => { close(); accountTopup?.click(); }; const openPlans = (): void => { close(); accountPricing?.click(); }; const handleAccountToggle = (): void => { if (!accountMenu || !accountToggle || pending) return; const opening = accountMenu.hidden || accountMenu.classList.contains(css('menuClosing')); if (opening) { window.clearTimeout(menuCloseTimer); menuCloseTimer = 0; accountMenu.hidden = false; accountMenu.inert = false; accountMenu.classList.remove(css('menuClosing')); accountMenu.classList.add(css('menuOpen')); } else { close(true); return; } accountToggle.setAttribute('aria-expanded', opening ? 'true' : 'false'); if (opening) { context.closeNotifications?.(); window.requestAnimationFrame(() => visibleMenuItems()[0]?.focus({ preventScroll: true })); } }; const handleHistory = (event: Event): void => { close(); if (context.onHistory) { context.onHistory(); return; } const target = event.currentTarget as HTMLElement | null; const url = target?.dataset.faHistoryUrl || historyActions[0]?.dataset.faHistoryUrl; if (url) window.location.assign(url); }; const handlePointer = (event: PointerEvent): void => { if (!accountMenu || accountMenu.hidden || accountMenu.inert) return; const target = event.target as Node | null; if (target && (accountMenu.contains(target) || accountToggle?.contains(target))) return; close(); }; const handleKey = (event: KeyboardEvent): void => { if (!accountMenu || accountMenu.hidden || accountMenu.inert) return; if (event.key === 'Escape') { event.preventDefault(); close(true); return; } if (event.key === 'Tab') { close(); return; } const items = visibleMenuItems(); if (!items.length) return; const currentIndex = items.indexOf(document.activeElement as HTMLElement); let nextIndex = currentIndex; if (event.key === 'ArrowDown') nextIndex = (currentIndex + 1 + items.length) % items.length; else if (event.key === 'ArrowUp') nextIndex = (currentIndex - 1 + items.length) % items.length; else if (event.key === 'Home') nextIndex = 0; else if (event.key === 'End') nextIndex = items.length - 1; else return; event.preventDefault(); items[nextIndex]?.focus({ preventScroll: true }); }; const handleAuthChanged = (event: Event): void => { const detail = record((event as CustomEvent).detail); const auth = record(detail.auth || detail); const wasConnected = connected; authRequest?.abort(); authRequest = null; setPending(false); syncState({ connected: auth.connected === true, balance: auth.balance, expired: auth.expired === true, user: auth.user || {}, }); if (!wasConnected && connected) showLoginSuccess(); }; const handleCreditsUpdated = (event: Event): void => { const detail = record((event as CustomEvent).detail); if (connected && Number.isFinite(Number(detail.balance))) { syncState({ connected: true, balance: detail.balance }); } }; const handleCreditsRefreshRequested = (event: Event): void => { const detail = record((event as CustomEvent).detail); const scope = String(detail.scope ?? ''); const reason = String(detail.reason ?? ''); const valid = (scope === 'single' && ['accepted_start', 'terminal'].includes(reason)) || (['bulk', 'store_queue'].includes(scope) && ['accepted_item_count', 'terminal'].includes(reason)); if (valid) void refreshBalance(false); }; const handleAuthTransition = (event: Event): void => { if (String(record((event as CustomEvent).detail).state ?? '').trim() === 'login_success') { showLoginSuccess(); } }; const handleRefresh = (): void => { close(true); void refreshBalance(); }; const handleLogout = (): void => void logout(); const handleLogin = (): void => void startLogin(); accountToggle?.addEventListener('click', handleAccountToggle); historyActions.forEach((action) => action.addEventListener('click', handleHistory)); creditsRefresh?.addEventListener('click', handleRefresh); accountLogout?.addEventListener('click', handleLogout); accountLogin?.addEventListener('click', handleLogin); document.addEventListener('pointerdown', handlePointer); document.addEventListener('keydown', handleKey); window.addEventListener('fotogenic-ai:auth-changed', handleAuthChanged); window.addEventListener('fotogenic-ai:auth-transition', handleAuthTransition); window.addEventListener('fotogenic-ai:credits-updated', handleCreditsUpdated); window.addEventListener('fotogenic-ai:credits-refresh-requested', handleCreditsRefreshRequested); syncState({ connected: initialConnected, balance: creditsElement?.textContent }); if (initialConnected && creditStatus === 'unknown') { void refreshBalance(false); } return Object.freeze({ close, isConnected: () => connected, startLogin, openTopup, openPlans, destroy(): void { if (destroyed) return; destroyed = true; window.clearTimeout(menuCloseTimer); accountToggle?.removeEventListener('click', handleAccountToggle); historyActions.forEach((action) => action.removeEventListener('click', handleHistory)); creditsRefresh?.removeEventListener('click', handleRefresh); accountLogout?.removeEventListener('click', handleLogout); accountLogin?.removeEventListener('click', handleLogin); document.removeEventListener('pointerdown', handlePointer); document.removeEventListener('keydown', handleKey); window.removeEventListener('fotogenic-ai:auth-changed', handleAuthChanged); window.removeEventListener('fotogenic-ai:auth-transition', handleAuthTransition); window.removeEventListener('fotogenic-ai:credits-updated', handleCreditsUpdated); window.removeEventListener('fotogenic-ai:credits-refresh-requested', handleCreditsRefreshRequested); authRequest?.abort(); authRequest = null; authTransitions?.destroy(); }, }); }; export type { AccountContext, AccountController }; export { createAccountController };